|
Download tasks/data/forward/agilegeeks__pyvat.591565e/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 57.4 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/agilegeeks__pyvat.591565e/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/agilegeeks__pyvat.591565e/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/agilegeeks__pyvat.591565e/instruction.md
57.4 kB
| # agilegeeks/pyvat | |
| ## Project Overview | |
| pyVat (published on PyPI as vat-format-checker) is a Python library for checking the format of European VAT identification numbers. Its purpose is to give applications a simple, dependency-light way to verify that a VAT number supplied by a customer or partner is syntactically valid for the EU member state it claims to come from, before the number is used in invoicing, tax reporting, or cross-border transactions. The project focuses on format validation rather than live registration lookups: it applies the official validation routines published in the European Commission's VIES documentation (bundled in the repository as /doc/VIES-VAT Validation Routines-v15.0.doc), which combine per-country structural rules, checksum algorithms, and regular expressions. The library targets Python 2.6 and later, keeping it usable in a wide range of environments. | |
| The primary entry point is the Validator class in the pyVat.api module. A caller constructs a Validator with a VAT number string, calls its validate() method, and receives a boolean result; on failure the validator exposes the detected country code so error messages can be reported to users. Internally the package is organized around a validators subpackage containing one module per country, each implementing that jurisdiction's structure and checksum rules. Validation proceeds by parsing the country prefix from the number, dispatching to the matching country validator, and applying its algorithm — typically a regular-expression shape check followed by a modulus-based digit check where the EU specification defines one. This per-country design makes it straightforward to add or amend national rules as the VIES routines evolve. | |
| One documented limitation is that the Croatian validation algorithm is not implemented, so Croatian numbers are checked purely by regular expression against their expected shape. The repository includes a test suite under tests/ and is configured for continuous integration on Travis CI, supporting the library's goal of reliable, community-maintained VAT format checking. | |
| Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance. | |
| ## Submission Constraints (read carefully — the evaluation depends on these) | |
| This is a **closed-book** task. The graded test suite is **hidden** and will be | |
| injected into the workspace at evaluation time. To be scored correctly you MUST | |
| follow these rules: | |
| 1. **Do NOT create or modify any files under the test directories** (e.g. | |
| `tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`). | |
| The grader injects its own test files at those paths; any file you place | |
| there will collide with the injected suite and cause the whole evaluation to | |
| score 0. Implement **only** the library/source code — never the tests. | |
| 2. **Your package MUST be importable by the name the tests use.** The hidden | |
| tests `import` your package by its documented top-level name (see the | |
| Project Directory Structure and API Usage Guide below). Provide a valid | |
| `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that | |
| `pip install -e .` succeeds and the package imports cleanly. If your package | |
| is not installable/importable, every test errors out and the reward is 0. | |
| 3. **Match the documented module paths and public API exactly** (names, | |
| signatures, and any literal error/exception strings). Internal helpers not | |
| listed in the API guide may be implemented however you like. | |
| ## Install / Reconstruction Contract | |
| Follow this contract before implementing the documented APIs: | |
| - **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`. | |
| - **Package/distribution name**: `vat-format-checker` | |
| - **Package roots**: `.` | |
| - **Install strategy**: `editable-install` | |
| - **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package. | |
| - **Provision commands**: | |
| ```bash | |
| python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' | |
| programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } | |
| export -f programgen_pip_install | |
| programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel | |
| programgen_pip_install python3 -m pip install 'setuptools>=61,<82' wheel | |
| ( | |
| programgen_install_report="$(mktemp)" | |
| trap 'rm -f "$programgen_install_report"' EXIT | |
| SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" | |
| python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report" | |
| ) | |
| ``` | |
| - **Runtime setup**: | |
| ```bash | |
| { | |
| [ -e "$PWD"/README.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; }; | |
| SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; | |
| } | |
| ``` | |
| - **Project root for installation**: `.` | |
| - **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0` | |
| - **Test directory**: `tests` | |
| - **Test command**: `bash -lc 'set -uo pipefail | |
| run=(python3 -m pytest -vv -o addopts= tests/test_validator.py) | |
| if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_validator.py); fi | |
| collect=(python3 -m pytest -q -o addopts= tests/test_validator.py) | |
| collected_output=$("${collect[@]}" --collect-only) | |
| collect_rc=$? | |
| if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then | |
| printf "%s\n" "$collected_output" >&2 | |
| printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 | |
| exit "$collect_rc" | |
| fi | |
| mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') | |
| if [ "${#collected[@]}" -gt 500 ]; then | |
| while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') | |
| fi | |
| "${run[@]}"; exit $?'` | |
| - **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately. | |
| ## Environment & Project Structure | |
| - **Language**: python | |
| - **Build system**: python | |
| - **Test command**: `bash -lc set -uo pipefail | |
| run=(python3 -m pytest -vv -o addopts= tests/test_validator.py) | |
| if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_validator.py); fi | |
| collect=(python3 -m pytest -q -o addopts= tests/test_validator.py) | |
| collected_output=$("${collect[@]}" --collect-only) | |
| collect_rc=$? | |
| if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then | |
| printf "%s\n" "$collected_output" >&2 | |
| printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 | |
| exit "$collect_rc" | |
| fi | |
| mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') | |
| if [ "${#collected[@]}" -gt 500 ]; then | |
| while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') | |
| fi | |
| "${run[@]}"; exit $?` | |
| ### Project Directory Structure | |
| ``` | |
| .gitignore | |
| .travis.yml | |
| AUTHORS | |
| LICENSE | |
| README.md | |
| doc/VIES-VAT Validation Routines-v15.0.doc | |
| pyVat/__init__.py | |
| pyVat/api.py | |
| pyVat/validators/__init__.py | |
| pyVat/validators/at.py | |
| pyVat/validators/be.py | |
| pyVat/validators/bg.py | |
| pyVat/validators/cy.py | |
| pyVat/validators/cz.py | |
| pyVat/validators/de.py | |
| pyVat/validators/dk.py | |
| pyVat/validators/ee.py | |
| pyVat/validators/es.py | |
| pyVat/validators/fi.py | |
| pyVat/validators/fr.py | |
| pyVat/validators/gb.py | |
| pyVat/validators/generic.py | |
| pyVat/validators/gr.py | |
| pyVat/validators/hr.py | |
| pyVat/validators/hu.py | |
| pyVat/validators/ie.py | |
| pyVat/validators/it.py | |
| pyVat/validators/lt.py | |
| pyVat/validators/lu.py | |
| pyVat/validators/lv.py | |
| pyVat/validators/mt.py | |
| pyVat/validators/nl.py | |
| pyVat/validators/pl.py | |
| pyVat/validators/pt.py | |
| pyVat/validators/ro.py | |
| pyVat/validators/se.py | |
| pyVat/validators/si.py | |
| pyVat/validators/sk.py | |
| setup.py | |
| ``` | |
| ## API Usage Guide | |
| Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely. | |
| ### Capability: Dynamic country validator loading | |
| # Dynamic country validator loading | |
| ## Purpose | |
| pyVat does not keep a registry object that maps country codes to validator classes. Instead, the mapping is encoded in a naming convention: every supported jurisdiction lives in its own module under `pyVat.validators`, named with the lowercase two-letter country code (e.g. `pyVat.validators.es`), and each such module must expose a class named exactly `Validator`. Dynamic loading is the mechanism that turns a country code produced during normal validation into the correct class object at runtime, without any static import of the per-country modules up front. | |
| The two functions split the work cleanly: | |
| - `load_cc_validator(cc)` is the domain-level entry point. It knows only the convention: build the module name `'pyVat.validators.%s' % cc` and the fixed class name `'Validator'`, then delegate. | |
| - `load_class(module_name, class_name)` is the generic import helper. It knows nothing about VAT: it imports an arbitrary dotted module path and fetches an arbitrary attribute from it. | |
| This separation is what makes the loading mechanism extensible: supporting a country means adding one module file plus registering its uppercase code in the module-level `EU_COUNTRIES` list defined in `pyVat/api.py` — a code absent from that list raises `VatValidationError('Invalid VAT country')` during normalization, before any loading occurs. Only the loading mechanism itself needs no changes. | |
| ## How the pieces connect in a real validation run | |
| The public workflow is `Validator(vat_number, vat_country_code=None)` then `.validate()`. Inside `validate()`, loading is the third step of a strict sequence: | |
| 1. **Normalization (`clean`)** — the raw number and optional explicit country code are coerced to `str`, spaces are removed, and codes are uppercased. The explicit-code branch is selected by the identity test `vat_country_code is not None`, not by truthiness (see below). If `vat_country_code` is `None`, the first two characters of the number become the country code and the remainder becomes the number body. The Greek convention `EL` is rewritten to `GR` before any membership check. If the resulting code is not in the module-level `EU_COUNTRIES` list, `VatValidationError('Invalid VAT country')` is raised. Additionally, when the body is longer than two characters and its first two characters (uppercased) equal the country code, that duplicated prefix is stripped. | |
| 2. **Error capture** — `validate()` wraps the `clean()` call in a `try/except VatValidationError`. On failure it stores `str(e)` in `self.error_message` and returns `False`; the exception never escapes `validate()`. | |
| 3. **Dynamic dispatch** — only after normalization succeeds does `validate()` call `load_cc_validator(self.country_code.lower())`. The lowercasing happens at the call site, not inside `load_cc_validator`. The returned class is instantiated with **no arguments** and its `validate(str(self.vat_number))` result is returned to the caller unchanged. | |
| State changes to be aware of. On the success path, after `validate()` runs, `self.vat_number` and `self.country_code` hold the *cleaned* values — the uppercased, space-free number body with any duplicated prefix removed, and the uppercased country code — and `self.error_message` stays `None`; note that a country validator returning `False` for a syntactically bad number does **not** populate `error_message` — only normalization failures do. On the failure path, the tuple assignment inside `validate()` never executes: `self.vat_number` keeps the raw constructor value (still containing spaces, if any), `self.country_code` is never created — it exists only after a successful `clean()` inside `validate()`, so accessing it before that raises `AttributeError` — and `self.error_message` is set. `self.vat_country_code` is never normalized or updated (`clean` operates on local copies). Consequently, repeated `validate()` calls are not idempotent: a second call re-cleans the already-cleaned number using the original raw `vat_country_code`, so on an instance created without an explicit code the next call typically fails the `EU_COUNTRIES` gate with `'Invalid VAT country'` and returns `False`. | |
| ## Ordering, defaults, and dispatch details | |
| - **Case sensitivity of `cc`.** `load_cc_validator` interpolates `cc` verbatim. Because the validator modules are lowercase filenames, passing `'ES'` directly attempts to import `pyVat.validators.ES` and fails with `ImportError`. The library's own caller lowercases first; re-implementations and direct callers must do the same. `EL` must already have been mapped to `GR` (that happens in `clean`, which returns uppercase codes, hence the `.lower()` at the dispatch site). | |
| - **`None` vs falsy for `vat_country_code`.** The explicit-code branch in `clean` triggers on any non-`None` value: the check is `vat_country_code is not None`, not a truthiness test. Falsy non-`None` codes such as `''` are therefore treated as provided — coerced, space-stripped, uppercased — and then rejected by the `EU_COUNTRIES` membership gate with `'Invalid VAT country'` instead of falling back to extracting the code from the number's first two characters. | |
| - **`__import__` semantics.** `load_class` calls `__import__(module_name, fromlist=[class_name])`, which resolves the *submodule* itself (not the parent package) because a non-empty `fromlist` is given, then uses `getattr(mod, class_name)`. A missing module surfaces as `ImportError`; a module lacking the expected attribute surfaces as `AttributeError`. Neither is caught anywhere in `pyVat.api`, so both propagate to the caller — unlike `VatValidationError`, which is absorbed by `validate()`. | |
| - **Import caching.** The import system consults `sys.modules`, so the first dispatch of a given country performs the real import and subsequent calls return the same cached module and therefore the *same class object*. Modules are loaded lazily, on first validation that needs them, never at package import time. | |
| - **Membership gate lives in `clean`, not in the loader.** `EU_COUNTRIES` (28 uppercase codes including `GB`) is only consulted during normalization. `load_cc_validator` itself will happily attempt any string — e.g. `load_cc_validator('generic')` raises `AttributeError` because that module contains `GenericValidator`, not a class named `Validator`. | |
| ## Edge cases that matter for tests | |
| - **Empty bodies.** An empty body reaches the country validator in exactly two ways. With no explicit code, a two-character input like `Validator('ES')` has both characters consumed as the country code, leaving body `''`, which is dispatched as `validate('')`. With an explicit `vat_country_code`, only an empty or all-whitespace input normalizes to body `''`. With an explicit code, a two-character input like `Validator('ES', 'ES')` keeps body `'ES'` — the explicit-code branch never slices the number, and the duplicate-prefix strip requires length > 2 — so the loaded validator is asked to validate `'ES'`, not `''`. Any empty body is rejected by `GenericValidator`'s default regexp `^.{1,}$` (at least one character required), so the result is `False`. | |
| - **Duplicate-prefix stripping is conditional.** The body prefix is removed only when the body is longer than two characters and its first two characters match the country code; a body of exactly two characters equal to the code is left intact. The rule applies identically however the code was obtained. It fires on the no-explicit-code path too, whenever the raw number starts with a doubled country prefix (`'ESESB123'` → code `'ES'`, body `'ESB123'`, stripped to `'B123'`), and a two-character body equal to the code can also arise without an explicit code (`'ESES'` → body `'ES'`, left intact because its length is 2). | |
| - **Coercion quirk.** In `clean`, the `try: str(...)` blocks construct a `VatValidationError('Invalid VAT number provided')` / `('Invalid VAT country provided')` object in the `except` branch but do **not** raise it; flow continues with the original value. These literals therefore exist in the source but are not, in practice, raised from `clean`. | |
| - **The `str()` re-coercion at dispatch.** `validate()` passes `str(self.vat_number)` to the country validator, so integer-like inputs that survive `clean` arrive as digit strings. | |
| - **Croatia.** The `HR` module has no checksum algorithm; its `Validator` is shape-only, which is a direct consequence of the per-module design — the loader simply returns whatever the module provides. | |
| ## `GenericValidator` as the loading target's base | |
| Country validators that need no checksum typically subclass `GenericValidator` and override the compiled `regexp` attribute set in its `__init__`. Its `validate(vat_number)` coerces the input with `str()`, matches against `self.regexp`, returns `False` on no match — and on a successful match falls through and returns `None` (implicitly), which is falsy. Subclasses are therefore expected to override `validate` for anything beyond a pure shape check, or to accept that a matching number yields `None` rather than `True`. Its `sum_weights(weights, number, start_pos=0)` helper computes the weighted digit sum over positions `start_pos .. len(weights)-1` of `number`, indexing both arrays positionally; checksum-based modules use it after loading, sharing one implementation across countries. | |
| ## Re-implementation checklist | |
| A from-scratch implementation passes the original suite if it preserves: the module/class naming contract with lowercase codes; verbatim interpolation in `load_cc_validator` with lowercasing done by the caller; `__import__(... fromlist=...)` + `getattr` in `load_class`; lazy loading with `sys.modules` caching; the `clean` → error-capture → dispatch ordering; the `vat_country_code is not None` identity check that selects the explicit-code path; `EL→GR` mapping and the `EU_COUNTRIES` membership check before dispatch; zero-argument instantiation of the loaded class; the failure-path state behavior (raw `vat_number` retained, `country_code` absent until a successful `clean()`, `error_message` set, `vat_country_code` untouched, non-idempotent repeated `validate()` calls); and `error_message` populated only for normalization failures while `False` is returned. | |
| #### Exact API Reference | |
| #### `pyVat.api.load_class` | |
| - **Import Path**: `from pyVat.api import load_class` | |
| - **Signature**: | |
| ```python | |
| def load_class(module_name, class_name) | |
| ``` | |
| #### `pyVat.api.load_cc_validator` | |
| - **Import Path**: `from pyVat.api import load_cc_validator` | |
| - **Signature**: | |
| ```python | |
| def load_cc_validator(cc) | |
| ``` | |
| #### `pyVat.api.Validator` | |
| - **Import Path**: `from pyVat.api import Validator` | |
| - **Required Test Import Paths**: | |
| - pyVat.api.Validator | |
| - **Exact Test Import Statements**: | |
| - from pyVat.api import Validator | |
| - **Kind**: class | |
| - **Signature**: | |
| ```python | |
| class Validator(object): | |
| def __init__(self, vat_number, vat_country_code=None) | |
| def clean(self) | |
| def validate(self) | |
| error_message: Any | |
| vat_number: Any | |
| vat_country_code: Any | |
| country_code: Any | |
| ``` | |
| - **Raises** (implementation must reproduce these exact messages): | |
| - `Invalid VAT country` | |
| - `Invalid VAT number provided` | |
| #### `pyVat.validators.generic.GenericValidator` | |
| - **Import Path**: `from pyVat.validators.generic import GenericValidator` | |
| - **Signature**: | |
| ```python | |
| class GenericValidator: | |
| def validate(self, vat_number) | |
| def sum_weights(self, weights, number, start_pos=0) | |
| ``` | |
| - **Behavior**: Generic validator | |
| ### Capability: Country-specific format and checksum algorithms | |
| # Country-specific format and checksum algorithms | |
| ## Purpose | |
| Each module under `pyVat.validators` implements the official VIES v15.0 routine for one EU member state as a `Validator` class exposing a single method `validate(vat_number)` that returns a bool. Every routine is a two-stage pipeline: a compiled regular expression stored in `self.regexp` enforces the national shape, and only structurally valid input reaches modulus/weighted checksum arithmetic. A re-implementation must reproduce both stages per country: a well-formed number with a wrong check digit is rejected, and a number failing the regex never reaches the arithmetic at all. | |
| States covered: AT, BE, BG, CY, CZ, DE, DK, EE, ES, FI, FR, GB, GR, HR, HU, IE, IT, LT, LU, LV, MT, NL, PL, PT, RO, SE, SI, SK. Greece lives only in module `gr`; the `EL` alias is resolved upstream before any country module is loaded. | |
| ## Input contract | |
| Country validators never see the raw caller string. The dispatcher strips the two-letter country prefix, removes spaces, uppercases everything, maps `EL` to `GR`, strips a duplicated leading country code when more than two characters remain, and re-coerces with `str()`. Each `validate` therefore receives the bare national part, e.g. `136695976` for `DE136695976`. Consequences: | |
| - Country regexes are written against the national part only (`^\d{9}$` for Germany, not `^DE\d{9}$`). | |
| - Calling a country validator directly with a prefixed string fails its own regex; the caller must strip the prefix. | |
| - Country modules must not strip prefixes or remove spaces - that work is already done. Case is likewise handled upstream, with one load-bearing in-module exception: ES lowercases the national part again before matching, because its regex is written in lowercase (`[\da-z]\d{7}[\da-z]`) - without that pass, every ES letter would fail its own regex once the dispatcher has uppercased. CY uppercases the ninth character in-module; given upstream normalization that is a defensive no-op. | |
| ## Shared machinery and its quirks | |
| All country validators subclass `GenericValidator`, which supplies two behaviors that shape every implementation: | |
| 1. The base `validate` returns `False` when `self.regexp` does not match and `None` (implicitly) when it does. Country overrides open with `if super().validate(vat_number) is False: return False`, so `None` means shape OK, continue. The `is False` comparison is exact; a base returning `True` on match would break the pipeline. | |
| 2. `sum_weights(weights, number, start_pos=0)` sums `int(number[i]) * weights[i]` for `i` in `range(start_pos, len(weights))`. Iteration is bounded by `len(weights)`, not `len(number)`: an 8-element weight list over a 9-digit string silently ignores the ninth digit. Most checksums rely on this to exclude the check digit(s) from the weighted sum. | |
| ## Per-country algorithms | |
| Positions are 1-based. Reject marks explicit early-`False` guards beyond the regex. | |
| - **AT** `U` + 8 digits - has a checksum, contrary to common assumption. After the leading `U`, index the eight digits as digits 1-8 (digit 1 is the second character). Digits 1, 3, 5 and 7 sum plainly; digits 2, 4 and 6 contribute the Luhn term `int(d/5) + (2*d) % 10`; digit 8 - the ninth and final character - is the check digit and stays out of the sum. With r the resulting weighted sum and c the fixed initial carry of 4, the number is valid iff digit 8 equals `(10 - (r + c) % 10) % 10`. The official example `U13585627` checks out: r = 29, so digit 8 must be 7. | |
| - **BE** regex `0[1-9]\d{8}` forces a leading zero; the last two digits must equal `97 - (first 8 digits as int) % 97`. | |
| - **BG** 9 or 10 digits. 9-digit legal entities: weights 1-8 mod 11; if that remainder is 10, a second pass with weights 3-10 (second remainder 10 maps to 0). 10-digit: three sequential branches, any of which may pass - physical persons (weights 2,4,8,5,10,9,7,3,6 mod 11, 10 to 0), foreigners (weights 21,19,17,13,11,9,7,3,1 mod 10), others (weights 4,3,2,7,6,5,4,3,2, 11 to 0, 10 rejects). | |
| - **CY** 8 digits + letter: first digit must be in {0,1,3,4,5,9}; prefix `12` rejected; odd positions map through {0:1, 1:0, 2:5, 3:7, 4:9, 5:13, 6:15, 7:17, 8:19, 9:21}, even positions count plainly; sum mod 26 indexes A-Z and must equal the ninth character, which CY uppercases in-module - a defensive no-op, since input already arrives uppercase. | |
| - **CZ** 8, 9, or 10 digits. 8-digit legal entities reject a leading 9 and use the round-up-to-next-multiple-of-11 scheme (weights 8-2; sum % 11 == 0 adds 11, otherwise the sum is multiplied by the ceiling of sum/11; check digit is the difference mod 10). 9-digit numbers split: leading 6 reuses the scheme over digits 2-8 with a fixed remainder-to-digit mapping; other leading digits are birth numbers requiring year <= 53, month in 1-12 or 51-62 (minus 50), and a real calendar day via `calendar.monthrange`. 10-digit numbers need divisibility by 11, year in 0..current or 54-99, month codes 1-12/21-32/51-62/71-82 (minus 20/50/70), a valid day, and the sum of the five two-digit pairs divisible by 11. | |
| - **DE** 9 digits: leading 0 rejected; iterative scheme - product starts at 10; per digit compute `s = digit + product`, `m = s % 10` (0 becomes 10), `product = (2 * m) % 11`; check digit is `11 - product` with 10 mapped to 0. There is no weight table; guessing one fails. | |
| - **DK** 8 digits: leading 0 rejected; weighted sum (2,7,6,5,4,3,2,1 - the final weight covers the check digit) must be divisible by 11. There is no separate check-digit comparison. | |
| - **EE** 9 digits: must start with `10`; check digit equals `ceil(weighted_sum / 10) * 10 - weighted_sum` with weights 3,7,1,3,7,1,3,7. | |
| - **ES** 9 characters, one alphanumeric + 7 digits + one alphanumeric: the routine lowercases its input in-module before matching `[\da-z]\d{7}[\da-z]`, which is what keeps both letter branches reachable under upstream uppercasing. Three branches selected by whether positions 1 and 9 are digits. A numeric position 9 requires a company leading letter (A-H,J,U,V) and compares `10 - (s1+s2) % 10` mod 10, where s1 sums digits 3,5,7 and s2 Luhn-doubles digits 2,4,6,8. A letter position 9 with leading letter K,L,M,X,Y,Z (or a leading digit; Y counts as 1, Z as 2) uses the mod-23 table T,R,W,A,G,M,Y,F,P,D,X,B,N,J,Z,S,Q,V,H,L,C,K,E. A letter position 9 with company leading letters uses a 1-10 to A-J mapping. These tables differ; merging them is a classic re-implementation error. | |
| - **FI** 8 digits: `r = 11 - (sum weighted 7,9,10,5,8,4,2) % 11`; r = 10 rejects; r = 11 accepts check digit 0. | |
| - **FR** 2 alphanumerics + 9 digits, two styles. Numeric: first two digits must equal `(last 9 digits + '12') % 97`. Alphanumeric: leading characters convert through a 0-9,A-Z code map (I and O excluded); `s = s1*34 + s2 - 100` when position 1 is a letter, `s = s1*24 + s2 - 10` when it is a digit; valid iff `s % 11 == int(digits) % 11`. | |
| - **GB** four shapes: `GD` + 3 digits must be 000-499, `HA` + 3 digits must be 500-999. The 9- and 12-digit forms compute `r = sum(weights 8 down to 2 over the first 7 digits) + int(digits 8-9)`, then `r1 = r % 97` and `r2 = (r + 55) % 97`; the number is valid iff exactly one of r1, r2 is 0 (`r1 * r2 == 0` and `r1 + r2 != 0`). When r1 is 0 the first 7 digits must fall outside 100000-999999, 9490001-9700000 and 9990001-9999999; when r2 is 0, outside 1-1000000. 12-digit branch numbers additionally require the last three digits to be non-zero; the checksum covers only the first nine digits. | |
| - **GR** 9 digits: weighted sum (256,128,64,32,16,8,4,2) mod 11, then mod 10, must equal digit 9. Remainder 10 folds to 0 rather than rejecting. | |
| - **HR** 11 digits: regex only - the VIES checksum is deliberately not implemented (the documented limitation). | |
| - **HU** 8 digits: weighted sum (9,7,3,1,9,7,3) of the first seven; check digit is 0 if the sum ends in 0, otherwise `10 - (last digit of the sum)`. Implemented by string last-character inspection. | |
| - **IE** two formats: 7 digits + letter, or digit + letter/`+`/`*` + 5 digits + letter. Old style rewrites the number to `0 + digits 3-7 + digit 1` before weighting. Both take weights 8 down to 2 mod 23 and index the table W,A,B,C,...,V (0 maps to W). | |
| - **IT** 11 digits: digits 8-10 must be in 1-101 or one of 120, 121, 999, 888; digit 11 must equal `(10 - (odd-position sum + Luhn-doubled even-position sum) % 10) % 10`. | |
| - **LT** 9 or 12 digits: digit 9 (respectively 12) must be 1; weights 1-8 (or 1-9 followed by 1,2) mod 11, with the same weights-plus-2 fallback and 10-to-0 rule as BG legal entities. | |
| - **LU** 8 digits: last two digits equal the first six mod 89. | |
| - **LV** 11 digits: first digit above 3 (legal entities) uses weights 9,1,4,8,3,10,2,5,7,6 and `r = 3 - sum % 11`; r below -1 becomes r+11; r in -1..1 rejects; otherwise r must equal digit 11. First digit 3 or below (natural persons): the first six characters must parse as a `%d%m%y` date via `datetime.strptime`, and that parse is exception-guarded - any unparseable value (e.g. a first digit <= 3 followed by 99999, which reads as day 99) returns `False` without raising. | |
| - **MT** 8 digits: first six digits must exceed 100000; weighted sum (3,4,6,7,8,9) over the first six; check value `37 - sum % 37` (0 becomes 37) must equal the last two digits. | |
| - **NL** 9 digits + `B` + 2 digits: suffix `00` rejected; weighted sum (9 down to 2) of the nine digits mod 11 must equal digit 9; remainder 10 rejects. | |
| - **PL** 10 digits: weighted sum (6,5,7,2,3,4,5,6,7) mod 11 must equal digit 10; remainder 10 rejects. | |
| - **PT** 9 digits: leading 0 rejected; `r = 11 - (sum weights 9 down to 2) % 11`; r of 10 or 11 folds to 0. | |
| - **RO** 2-10 digits: leading 0 rejected; the number is left-padded with zeros to 10 characters, weighted (7,5,3,2,1,7,5,3,2), multiplied by 10, taken mod 11 (10 becomes 0) and compared with digit 10. The padding is what admits the short historical format. | |
| - **SE** 12 digits: digits 11-12 must be 01-94; digit 10 is a Luhn-style check digit over the first nine (odd positions contribute `int(d/5) + (2d) % 10`, even positions count plainly; result `(10 - total % 10) % 10`). | |
| - **SI** 8 digits: first seven digits must be at least 1000000; `r = 11 - (sum weights 8 down to 2) % 11`; r = 10 maps to check digit 0; r = 11 rejects. | |
| - **SK** 10 digits: first digit non-zero, third digit in {2,3,4,7,8,9}, whole number divisible by 11. | |
| ## Failure semantics and test-sensitive details | |
| - Country validators never raise and never write `error_message`; every in-country rejection is a plain `False`. Only the dispatcher sets `error_message` (for unknown countries or malformed input), so a failed checksum leaves `error_message` as `None` while `validate()` still returns `False`. The LV `strptime` call is exception-guarded, so a failed date parse returns `False` rather than raising. | |
| - Leading-zero handling is deliberate, not a regex accident: DE, DK, PT, RO and SK reject leading zeros explicitly after the regex; BE requires one; EE requires the `10` prefix; EE, SI and MT impose minimum-value floors on the significant digits. | |
| - Range guards run before arithmetic and carry as much test weight as the modulus: GB exclusion windows, IT digits 8-10, SE suffix 01-94, MT and SI floors, CZ and LV calendar validation, SK third digit, LT position-9 digit, NL suffix ban. | |
| - The Luhn-style term `int(d / 5) + (2 * d) % 10` appears in AT, ES, IT and SE. With `from __future__ import division` in force it computes `floor(d/5) + ((2d) mod 10)`, not a plain doubling. | |
| - Mod-11 remainder conventions differ per country and must not be unified: remainder 10 rejects outright (NL, PL), folds to 0 (PT, BG physical-person and CZ fallback branches), triggers a second weighted pass (BG, LT legal entities), or takes a mapped value (CZ leading-6 branch). FI rejects 10 and treats 11 as check digit 0; SI rejects 11 and maps 10 to 0. | |
| - Validators are stateless and deterministic - safe to instantiate per call, no I/O or caching. The one clock dependency is the CZ 10-digit branch, which compares the birth year against the current year (`datetime.date.today()`), so verdicts for years near the boundary can change over time. | |
| #### Exact API Reference | |
| #### `pyVat.validators.at.Validator` | |
| - **Import Path**: `from pyVat.validators.at import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.be.Validator` | |
| - **Import Path**: `from pyVat.validators.be import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.bg.Validator` | |
| - **Import Path**: `from pyVat.validators.bg import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.cy.Validator` | |
| - **Import Path**: `from pyVat.validators.cy import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.cz.Validator` | |
| - **Import Path**: `from pyVat.validators.cz import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.de.Validator` | |
| - **Import Path**: `from pyVat.validators.de import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.dk.Validator` | |
| - **Import Path**: `from pyVat.validators.dk import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.ee.Validator` | |
| - **Import Path**: `from pyVat.validators.ee import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.es.Validator` | |
| - **Import Path**: `from pyVat.validators.es import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.fi.Validator` | |
| - **Import Path**: `from pyVat.validators.fi import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.fr.Validator` | |
| - **Import Path**: `from pyVat.validators.fr import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.gb.Validator` | |
| - **Import Path**: `from pyVat.validators.gb import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.gr.Validator` | |
| - **Import Path**: `from pyVat.validators.gr import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.hr.Validator` | |
| - **Import Path**: `from pyVat.validators.hr import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.hu.Validator` | |
| - **Import Path**: `from pyVat.validators.hu import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.ie.Validator` | |
| - **Import Path**: `from pyVat.validators.ie import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.it.Validator` | |
| - **Import Path**: `from pyVat.validators.it import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.lt.Validator` | |
| - **Import Path**: `from pyVat.validators.lt import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.lu.Validator` | |
| - **Import Path**: `from pyVat.validators.lu import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.lv.Validator` | |
| - **Import Path**: `from pyVat.validators.lv import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.mt.Validator` | |
| - **Import Path**: `from pyVat.validators.mt import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.nl.Validator` | |
| - **Import Path**: `from pyVat.validators.nl import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.pl.Validator` | |
| - **Import Path**: `from pyVat.validators.pl import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.pt.Validator` | |
| - **Import Path**: `from pyVat.validators.pt import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.ro.Validator` | |
| - **Import Path**: `from pyVat.validators.ro import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.se.Validator` | |
| - **Import Path**: `from pyVat.validators.se import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.si.Validator` | |
| - **Import Path**: `from pyVat.validators.si import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| #### `pyVat.validators.sk.Validator` | |
| - **Import Path**: `from pyVat.validators.sk import Validator` | |
| - **Signature**: | |
| ```python | |
| class Validator: | |
| def validate(self, vat_number) | |
| ``` | |
| - **Behavior**: For rules see /docs/VIES-VAT Validation Routines-v15.0.doc | |
| ## Detailed Implementation Nodes | |
| ### Node: Dynamic country validator loading | |
| ## Functional constraints | |
| **Module naming contract.** Country validators live at `pyVat.validators.<cc>` with `cc` lowercase; each must define a class named exactly `Validator`. `load_cc_validator(cc)` interpolates `cc` verbatim — no case normalization, no membership check. Passing an uppercase code (e.g. `'ES'`) or an unknown code raises `ImportError` (uncaught, propagates); a module without a `Validator` attribute raises `AttributeError` (e.g. `'generic'`). | |
| **Lowercasing is the caller's job.** `Validator.validate()` dispatches with `self.country_code.lower()`, where `country_code` comes from `clean()` (uppercased, `EL` already mapped to `GR`, gated against the `EU_COUNTRIES` list — non-members raise `VatValidationError('Invalid VAT country')`, which `validate()` catches, stores in `self.error_message`, and turns into `False`). Direct `load_cc_validator` callers must pass lowercase codes themselves. | |
| **Import mechanics.** `load_class` uses `__import__(module_name, fromlist=[class_name])` + `getattr`, so a non-empty `fromlist` makes the call return the submodule object. Imports are lazy (first dispatch) and cached via `sys.modules`: repeated loads return the identical class object. | |
| **Instantiation contract.** `validate()` instantiates the loaded class with zero arguments and returns `validator.validate(str(self.vat_number))` unchanged — country `validate` methods must accept one string argument and return a truthy/falsey value without needing constructor parameters. | |
| **Pre-dispatch normalization.** `clean()` strips spaces, uppercases both parts, selects the explicit-code branch with the identity check `vat_country_code is not None` (so `''` and other falsy non-`None` codes count as provided and are rejected by the `EU_COUNTRIES` gate), extracts the code from the first two characters when no explicit code is given (consuming them from the number), maps `EL→GR`, and strips a duplicated country prefix from the body only when the body is longer than two characters and starts with the code — a rule that applies identically on both paths. On success, `validate()` stores the cleaned values in `self.vat_number`/`self.country_code`; on normalization failure the tuple assignment never happens, so `self.vat_number` keeps its raw constructor value, `self.country_code` is never created (accessing it before a successful `validate()` raises `AttributeError`), `self.error_message` is set and `False` is returned. `self.vat_country_code` is never normalized or updated, so repeated `validate()` calls are not idempotent: the already-cleaned number is re-cleaned with the original raw code, and for instances created without an explicit code a second call typically fails the membership gate with `'Invalid VAT country'`. | |
| **`GenericValidator`.** Base class for shape-only countries. Sets `self.regexp = re.compile(r'^.{1,}$')` (matches any non-empty string); `validate` coerces with `str()`, returns `False` on no match, and implicitly returns `None` on match (falsy — subclasses override for real results). `sum_weights(weights, number, start_pos=0)` sums `int(number[i]) * weights[i]` for `i` in `range(start_pos, len(weights))`, sharing checksum math across country modules. | |
| **Extension rule.** Supporting a new country = adding `pyVat.validators.<cc>` exposing `Validator` (plus the uppercase code in `EU_COUNTRIES` in `pyVat/api.py` so `clean` passes the membership gate); no loader changes. | |
| ## Usage example | |
| ```python | |
| from pyVat.api import Validator, load_cc_validator, load_class | |
| # Direct dynamic load: lowercase module code, fixed class name 'Validator' | |
| ESValidator = load_cc_validator('es') # -> the Validator class object from module pyVat.validators.es | |
| GBValidator = load_class('pyVat.validators.gb', 'Validator') | |
| assert ESValidator is load_cc_validator('es') # sys.modules caching: same object | |
| # Normal workflow: clean() normalizes, then validate() loads + dispatches | |
| v = Validator(' ESB12345678 ') # no explicit country code | |
| print(v.validate()) # dispatched to pyVat.validators.es.Validator() | |
| print(v.country_code) # 'ES' (uppercase, EL already mapped to GR) | |
| print(v.vat_number) # 'B12345678' (cleaned body) | |
| print(v.error_message) # None unless clean() raised VatValidationError | |
| v.validate() # False on a second call: the stored body 'B12345678' is re-cleaned with the | |
| # original raw vat_country_code (None), so 'B1' fails the EU_COUNTRIES gate | |
| Validator('ZZ123').validate() # False; error_message == 'Invalid VAT country' | |
| load_cc_validator('ES') # ImportError: module files are lowercase | |
| ``` | |
| ### Node: Country-specific format and checksum algorithms | |
| # Implementation nodes | |
| ## Hard constraints | |
| - One module per state at `pyVat/validators/<lowercase cc>.py`; class named `Validator`; method `validate(self, vat_number)` returning a bool. No other public surface is consumed. | |
| - Input arrives uppercase, space-free and prefix-free (the dispatcher stripped the country code, mapped EL to GR, removed a doubled prefix, and coerced with `str()`). Never re-strip inside a country module; calling one directly with a prefixed string fails its regex. The single case exception is ES, which lowercases its input in-module before its lowercase regex; CY's uppercasing of the ninth character is a defensive no-op. | |
| - Regex first (`self.regexp`, set in `__init__`), arithmetic second. Regex failure returns `False` without running any checksum. | |
| - Total function of the string: never raise, never set `error_message`, return `False` for any structurally invalid input. All `int()` and indexing happens after the regex match; the LV `strptime` parse is exception-guarded so date failures return `False`. | |
| - Subclass `GenericValidator`. Its base `validate` returns `False` on regex mismatch and `None` on match; overrides must test `is False` before continuing. | |
| - `sum_weights(weights, number, start_pos=0)` iterates `range(start_pos, len(weights))` - the weights list length, not the string length, bounds the loop. Short weight lists silently exclude trailing digits (this is how check digits stay out of the sum). | |
| - Luhn-style term shared by AT, ES, IT, SE: `int(d/5) + (2*d) % 10` (floor plus doubled mod 10). | |
| - Adding a state requires a module plus an `EU_COUNTRIES` entry in `pyVat.api`; unknown codes are rejected before any import. | |
| ## Per-country algorithm constraints | |
| - AT: `U\d{8}`; of the eight digits after `U`, digits 1,3,5,7 sum plainly, digits 2,4,6 contribute `int(d/5)+(2*d)%10`, digit 8 (the 9th character) is the check digit; with r the weighted sum and c = 4, valid iff digit 8 == (10-(r+c)%10)%10. | |
| - BE: `0[1-9]\d{8}`; last 2 digits == 97 - first8 % 97. | |
| - BG: 9-digit legal weights 1-8 mod 11, fallback 3-10 (10 to 0); 10-digit passes any of three branches (weights 2,4,8,5,10,9,7,3,6 mod 11 with 10 to 0; 21,19,17,13,11,9,7,3,1 mod 10; 4,3,2,7,6,5,4,3,2 with 11 to 0 and 10 rejecting). | |
| - CY: `\d{8}[A-Z]`; first digit in {0,1,3,4,5,9}; prefix 12 banned; odd positions map {0:1,1:0,2:5,3:7,4:9,5:13,6:15,7:17,8:19,9:21}; sum mod 26 indexes A-Z and must equal the ninth character (uppercased in-module; a no-op since input arrives uppercase). | |
| - CZ: 8-digit bans leading 9, round-up-to-11 scheme; 9-digit leading 6 uses mapped scheme, otherwise birth number (year <= 53, month 1-12 or 51-62, real day via monthrange); 10-digit needs % 11 == 0, year in 0..current year or 54-99 (compared against `datetime.date.today()`), month codes 1-12/21-32/51-62/71-82 (minus 20/50/70), valid day, and pairwise two-digit sums divisible by 11. | |
| - DE: `\d{9}`; leading 0 rejected; iterative product/sum (start 10; (d+p)%10 with 0 to 10; p=(2m)%11; check 11-p with 10 to 0). | |
| - DK: `\d{8}`; leading 0 rejected; weights 2,7,6,5,4,3,2,1; sum % 11 == 0. | |
| - EE: `\d{9}`; prefix 10 required; check = ceil(weighted sum 3,7,1,3,7,1,3,7 / 10)*10 - sum. | |
| - ES: `[\da-z]\d{7}[\da-z]` after in-module lowercasing; three branches selected by digit/letter at positions 1 and 9: digit 9 requires a company leading letter (A-H,J,U,V) and compares 10-(s1+s2)%10 mod 10; letter 9 with leading K,L,M,X,Y,Z or a leading digit (Y as 1, Z as 2) uses the mod-23 table T,R,W,A,G,M,Y,F,P,D,X,B,N,J,Z,S,Q,V,H,L,C,K,E; letter 9 with company leading letters uses the 1-10 to A-J table. | |
| - FI: weights 7,9,10,5,8,4,2; r = 11 - sum%11; 10 rejects; 11 accepts check digit 0. | |
| - FR: numeric style first2 == (last9 + '12') % 97; alphanumeric style maps leading characters (I, O excluded) and requires s%11 == digits%11 with s = s1*34+s2-100 (letter first) or s1*24+s2-10 (digit first). | |
| - GB: GD+3d restricted to 000-499, HA+3d to 500-999; 9/12-digit: r = sum(weights 8..2 over first 7) + int(digits 8-9); r1 = r%97, r2 = (r+55)%97; exactly one must be 0; r1 = 0 requires the first 7 digits outside 100000-999999, 9490001-9700000 and 9990001-9999999, r2 = 0 requires them outside 1-1000000; 12-digit suffix must not be 000. | |
| - GR: weights 256..2; (sum % 11) % 10 == digit 9. | |
| - HR: `\d{11}`, shape only. | |
| - HU: weights 9,7,3,1,9,7,3; check digit 0 if the sum ends in 0 else 10 minus the final digit. | |
| - IE: 7d+letter or d+[letter/+/*]+5d+letter; old style rewrites to 0+d3..d7+d1; weights 8..2 mod 23 index W,A..V. | |
| - IT: `\d{11}`; digits 8-10 in 1-101 or {120,121,999,888}; Luhn-style check digit. | |
| - LT: 9 or 12 digits; position 9/12 must be 1; weights 1-8 or 1-9+1,2 mod 11, fallback weights+2, 10 to 0. | |
| - LU: last 2 digits == first 6 % 89. | |
| - LV: digit 1 above 3 uses weights 9,1,4,8,3,10,2,5,7,6 with r = 3 - sum%11 (r below -1 becomes r+11; -1..1 rejects); otherwise the first 6 characters must parse as %d%m%y via `datetime.strptime`, exception-guarded so any parse failure returns `False` without raising. | |
| - MT: first 6 digits above 100000; weights 3,4,6,7,8,9; check value 37 - sum%37 (0 to 37) == last 2 digits. | |
| - NL: `\d{9}B\d{2}`; suffix 00 banned; weights 9..2 mod 11 == digit 9; remainder 10 rejects. | |
| - PL: weights 6,5,7,2,3,4,5,6,7 mod 11 == digit 10; remainder 10 rejects. | |
| - PT: leading 0 rejected; r = 11 - sum(weights 9..2)%11; r of 10 or 11 folds to 0. | |
| - RO: `\d{2,10}`; leading 0 rejected; left-pad to 10; weights 7,5,3,2,1,7,5,3,2; (sum*10)%11 (10 to 0) == digit 10. | |
| - SE: `\d{12}`; digits 11-12 in 1-94; Luhn-style check digit at position 10 over the first 9. | |
| - SI: first 7 digits at least 1000000; r = 11 - sum(weights 8..2)%11; 10 maps to 0; 11 rejects. | |
| - SK: digit 1 non-zero; digit 3 in {2,3,4,7,8,9}; whole number divisible by 11. | |
| ## Integration constraints | |
| - The dispatcher instantiates each country `Validator` with no arguments and re-coerces the number with `str()` before the call. | |
| - Only `VatValidationError` is handled upstream; country modules must not raise it or anything else, and must never write `error_message`. | |
| ## Example | |
| ```python | |
| from pyVat.api import Validator | |
| from pyVat.validators.de import Validator as DEValidator | |
| v = Validator('EL 123 456 783') # spaces, case, EL alias handled upstream | |
| v.validate() # True -> dispatched to pyVat.validators.gr | |
| v.error_message # None | |
| DEValidator().validate('136695976') # True -> shape ok, product/sum checksum ok | |
| DEValidator().validate('136695975') # False -> shape ok, checksum digit mismatch | |
| Validator('XX123').validate() # False; error_message == 'Invalid VAT country' | |
| ``` | |