"""Address schema.""" import re from abacus_common_logic.marshalling.custom_fields import ma from marshmallow import validates_schema, ValidationError from marshmallow.validate import Length from payee.constants.constants import COUNTRIES_NOT_REQUIRED_FIELD_ZIP from payee.schemas.mixins import SanitizeEmptyStringsMixin from payee.schemas.validators import UnicodeRegexp from payee.utils.validations import validate_country_code class AddressSchema(ma.Schema): """Address schema.""" country_code = ma.String(required=True, validate=validate_country_code) address_1 = ma.String( required=True, validate=[ UnicodeRegexp(r'^[\p{L}0-9\s,\.\/_\-\)\(\\#`,*\'°":&]+$', re.UNICODE), Length(min=1, max=40), ], ) address_2 = ma.String( allow_none=True, required=False, metadata={'allow_blank': True}, validate=[ UnicodeRegexp(r'^[\p{L}0-9\s,\.\/_\-\)\(\\#`,*\'°":&]*$', re.UNICODE), Length(max=40), ], ) city = ma.String( required=True, validate=[ UnicodeRegexp(r'^[\p{L}\.][\p{L}\.\'\- ]*[\p{L}\.\'\(\)]$', re.UNICODE), Length(min=1, max=40), ], ) province = ma.String() zip = ma.String( required=False, allow_none=True, metadata={'allow_blank': True}, validate=[ UnicodeRegexp(r'^[0-9a-zA-Z -]+$', re.UNICODE), Length(min=3, max=10), ], ) @validates_schema def validate_zip_for_non_ag_countries(self, data, **kwargs): country_code = data.get('country_code') zip_value = data.get('zip') if country_code in COUNTRIES_NOT_REQUIRED_FIELD_ZIP: return if not zip_value: raise ValidationError('This field is required.', field_name='zip') class PayoneerWhitelabelAddressSchema(AddressSchema): city = ma.String( required=True, validate=[ UnicodeRegexp( r'[\p{L}\.\'()#`,*\":&\'ºª°\.\/_\-\\][\p{L}\. \'()#`,*\":&\'ºª°\.\/_\-\\]*[\p{L}\.\'()#`,*\":&\'ºª°\.\/_\-\\]$', re.UNICODE, ), Length(min=1, max=40), ], ) zip = ma.String( required=True, validate=[ UnicodeRegexp(r'^[0-9a-zA-Z -]+$', re.UNICODE), Length(min=3, max=10), ], ) class NonUSAddressSchema(AddressSchema): """Address schema with less validation rules.""" address_1 = ma.String( required=False, allow_none=True, metadata={'allow_blank': True}, validate=Length(min=1, max=255), ) address_2 = ma.String( required=False, allow_none=True, metadata={'allow_blank': True}, validate=Length(max=255), ) city = ma.String( required=False, allow_none=True, metadata={'allow_blank': True}, validate=Length(min=1, max=100), ) province = ma.String( required=False, allow_none=True, metadata={'allow_blank': True} ) @validates_schema def validate_zip_for_non_ag_countries(self, data, **kwargs): """Override parent validation to make zip always optional for non-US addresses.""" return class MigrationAddressSchema(ma.Schema, SanitizeEmptyStringsMixin): """Address schema for bank_details migration.""" country_code = ma.String(allow_none=True) address_1 = ma.String(allow_none=True) address_2 = ma.String(allow_none=True) city = ma.String(allow_none=True) province = ma.String(allow_none=True) zip = ma.String(allow_none=True)