def test_country_code(self): """is_vat_number_format_valid('..', country_code='..') """ for country_code, cases in VAT_NUMBER_FORMAT_CASES.items(): for vat_number, expected_result in cases: verbal_expected_result = \ 'valid' if expected_result else 'invalid' self.assertEqual(is_vat_number_format_valid(vat_number, country_code), expected_result, 'expected non-prefixed VAT number %s (%s) ' 'to be %s' % (vat_number, country_code, verbal_expected_result)) self.assertEqual( is_vat_number_format_valid( '%s%s' % (country_code, vat_number), country_code ), expected_result, 'expected prefixed VAT number %s%s (%s) to be %s' % (country_code, vat_number, country_code, verbal_expected_result) )
def clean(self): if (self.sales_tax_number and is_vat_number_format_valid(self.sales_tax_number, self.country) is False): raise ValidationError( {'sales_tax_number': 'The sales tax number is not valid.'} )
def is_valid_formatted_vat(vat_num: str) -> bool: try: res = pyvat.is_vat_number_format_valid(vat_num, None) if res == True: return True else: return False except Exception as e: return False
def validate(self, attrs): country = attrs.get('country') vat_code = attrs.get('vat_code') if vat_code: # Check VAT format if not pyvat.is_vat_number_format_valid(vat_code, country): raise serializers.ValidationError( {'vat_code': _('VAT number has invalid format.')} ) # Check VAT number in EU VAT Information Exchange System # if customer is new or either VAT number or country of the customer has changed if ( not self.instance or self.instance.vat_code != vat_code or self.instance.country != country ): check_result = pyvat.check_vat_number(vat_code, country) if check_result.is_valid: attrs['vat_name'] = check_result.business_name attrs['vat_address'] = check_result.business_address if not attrs.get('contact_details'): attrs['contact_details'] = attrs['vat_address'] elif check_result.is_valid is False: raise serializers.ValidationError( {'vat_code': _('VAT number is invalid.')} ) else: logger.debug( 'Unable to check VAT number %s for country %s. Error message: %s', vat_code, country, check_result.log_lines, ) raise serializers.ValidationError( {'vat_code': _('Unable to check VAT number.')} ) return attrs