diff --git a/src/extractor.py b/src/extractor.py index 716654b..d5a4ec8 100644 --- a/src/extractor.py +++ b/src/extractor.py @@ -435,9 +435,15 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData: "//rsm:ExchangedDocument/ram:IssueDateTime/udt:DateTimeString[@format='102']/text()", namespaces=NAMESPACES, ) + # BT-9 payment due date due_date = xml_root.xpath( - "//ram:ApplicableHeaderTradeAgreement/ram:ApplicableTradeDeliveryTerms/" - "ram:Description/text()", + "//ram:ApplicableHeaderTradeSettlement/ram:SpecifiedTradePaymentTerms/" + "ram:DueDateDateTime/udt:DateTimeString/text()", + namespaces=NAMESPACES, + ) + # BT-10 buyer reference (Leitweg-ID on XRechnung invoices) + buyer_reference = xml_root.xpath( + "//ram:ApplicableHeaderTradeAgreement/ram:BuyerReference/text()", namespaces=NAMESPACES, ) notes = xml_root.xpath( @@ -453,7 +459,10 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData: return XmlData( invoice_number=invoice_number[0] if invoice_number else "", invoice_date=_normalize_cii_date(invoice_date[0]) if invoice_date else "", - due_date=due_date[0] if due_date else None, + due_date=_normalize_cii_date(due_date[0]) if due_date else None, + buyer_reference=(buyer_reference[0].strip() or None) + if buyer_reference + else None, supplier=parse_supplier(xml_root), buyer=parse_buyer(xml_root), line_items=parse_line_items(xml_root), diff --git a/src/models.py b/src/models.py index f2a99ca..0065f4c 100644 --- a/src/models.py +++ b/src/models.py @@ -97,6 +97,10 @@ class XmlData(BaseModel): invoice_number: str = Field(description="Invoice number") invoice_date: str = Field(description="Invoice date (YYYY-MM-DD)") due_date: str | None = Field(default=None, description="Due date (YYYY-MM-DD)") + buyer_reference: str | None = Field( + default=None, + description="Buyer reference (BT-10); the Leitweg-ID on XRechnung invoices", + ) supplier: Supplier = Field(description="Supplier information") buyer: Buyer = Field(description="Buyer information") line_items: list[LineItem] = Field(description="Line items") @@ -178,6 +182,14 @@ class ValidateRequest(BaseModel): default=None, description="Extracted PDF text for comparison" ) checks: list[str] = Field(description="List of validation checks to run") + profile: str | None = Field( + default=None, + description=( + "Invoice profile as returned by /extract in 'zugferd_profil'. " + "Enables profile-specific rules, e.g. the mandatory buyer " + "reference on XRechnung invoices." + ), + ) class ValidateResponse(BaseModel): diff --git a/src/ubl_parser.py b/src/ubl_parser.py index c058eb4..f619d84 100644 --- a/src/ubl_parser.py +++ b/src/ubl_parser.py @@ -308,6 +308,7 @@ def parse_ubl_xml(xml_root: etree._Element) -> XmlData: invoice_number=_text(xml_root, "./cbc:ID") or "", invoice_date=_text(xml_root, "./cbc:IssueDate") or "", due_date=due_date, + buyer_reference=_text(xml_root, "./cbc:BuyerReference"), supplier=parse_ubl_supplier(xml_root), buyer=parse_ubl_buyer(xml_root), line_items=parse_ubl_line_items(xml_root), diff --git a/src/validator.py b/src/validator.py index 4522ff0..bf7c232 100644 --- a/src/validator.py +++ b/src/validator.py @@ -15,8 +15,30 @@ from src.models import ( from src.utils import amounts_match -def validate_pflichtfelder(xml_data: XmlData) -> list[ErrorDetail]: - """Check required fields are present.""" +def is_xrechnung_profile(profile: str | None) -> bool: + """Check whether a profile name denotes an XRechnung invoice. + + Args: + profile: Profile as returned by /extract (e.g. 'XRECHNUNG_3.0') + + Returns: + True for XRechnung profiles + """ + return bool(profile) and profile.strip().upper().startswith("XRECHNUNG") + + +def validate_pflichtfelder( + xml_data: XmlData, profile: str | None = None +) -> list[ErrorDetail]: + """Check required fields are present. + + Args: + xml_data: Parsed invoice data + profile: Invoice profile; enables profile-specific required fields + + Returns: + List of errors and warnings for missing fields + """ errors = [] def add_error(field: str, severity: str, message: str | None = None) -> None: @@ -58,6 +80,19 @@ def validate_pflichtfelder(xml_data: XmlData) -> list[ErrorDetail]: if not xml_data.buyer.name or not xml_data.buyer.name.strip(): add_error("buyer.name", "critical") + # XRechnung BR-DE-15: the buyer reference (BT-10, Leitweg-ID) is mandatory + if is_xrechnung_profile(profile) and not ( + xml_data.buyer_reference and xml_data.buyer_reference.strip() + ): + add_error( + "buyer_reference", + "critical", + message=( + "XRechnung requires a buyer reference (BT-10, Leitweg-ID) " + "in 'buyer_reference'" + ), + ) + if xml_data.totals.net == 0: add_error("totals.net", "critical") @@ -337,7 +372,7 @@ def validate_invoice(request: ValidateRequest) -> ValidationResult: check_errors: list[ErrorDetail] = [] if check_name == "pflichtfelder": - check_errors = validate_pflichtfelder(xml_data) + check_errors = validate_pflichtfelder(xml_data, request.profile) checks_run += 1 elif check_name == "betraege": check_errors = validate_betraege(xml_data) diff --git a/tests/test_fixture_sweep.py b/tests/test_fixture_sweep.py index 9e020ab..bd72bdc 100644 --- a/tests/test_fixture_sweep.py +++ b/tests/test_fixture_sweep.py @@ -77,6 +77,7 @@ def test_fixture_sweep(filename: str) -> None: xml_data=result.xml_data.model_dump(), pdf_text=result.pdf_text, checks=ALL_CHECKS, + profile=result.zugferd_profil, ) validation = validate_invoice(request) critical_fields = {error.field for error in validation.errors} diff --git a/tests/test_real_invoice_regressions.py b/tests/test_real_invoice_regressions.py index 26a7a1d..60cae03 100644 --- a/tests/test_real_invoice_regressions.py +++ b/tests/test_real_invoice_regressions.py @@ -6,6 +6,7 @@ tests/fixtures/real/, verify it contains no real-world data, and add a test here that locks in the correct behavior. """ +import re from io import BytesIO from pathlib import Path @@ -51,6 +52,7 @@ class TestFcTaxNumberBasisQuantityInvoice: data = result.xml_data assert data.invoice_number == "4711" + assert re.fullmatch(r"\d{4}-\d{2}-\d{2}", data.due_date) assert data.supplier.tax_number == "1112223334444" assert data.supplier.vat_id is None assert data.supplier.email == "rechnung@beispielwerkstatt.example" diff --git a/tests/test_xml_formats.py b/tests/test_xml_formats.py index 261be1a..7ef5c6c 100644 --- a/tests/test_xml_formats.py +++ b/tests/test_xml_formats.py @@ -111,6 +111,7 @@ class TestPlainXml: assert result.extraction_meta.xml_attachment_name is None assert result.xml_data.invoice_number == "123456XX" assert result.xml_data.invoice_date == "2016-04-04" + assert result.xml_data.buyer_reference == "04011000-12345-03" assert result.xml_data.totals.gross == pytest.approx(336.9) def test_ubl_xml(self): @@ -124,6 +125,7 @@ class TestPlainXml: data = result.xml_data assert data.invoice_number == "123456XX" assert data.invoice_date == "2016-04-04" + assert data.buyer_reference == "04011000-12345-03" assert data.currency == "EUR" assert data.supplier.name == "[Seller name]" assert data.supplier.vat_id == "DE 123456789" @@ -173,6 +175,46 @@ class TestPlainXml: assert not result.xml_raw.startswith("") +class TestBuyerReference: + """BT-10 (Leitweg-ID) is mandatory on XRechnung invoices only.""" + + def _data_without_reference(self): + xml_data = extract_invoice(UBL_XML.read_bytes()).xml_data + xml_data.buyer_reference = None + return xml_data.model_dump() + + def test_missing_on_xrechnung_is_critical(self): + request = ValidateRequest( + xml_data=self._data_without_reference(), + checks=["pflichtfelder"], + profile="XRECHNUNG_3.0", + ) + validation = validate_invoice(request) + + assert validation.is_valid is False + assert [e.field for e in validation.errors] == ["buyer_reference"] + + @pytest.mark.parametrize("profile", [None, "EN16931", "PEPPOL_BIS_BILLING_3.0"]) + def test_missing_on_other_profiles_is_fine(self, profile): + request = ValidateRequest( + xml_data=self._data_without_reference(), + checks=["pflichtfelder"], + profile=profile, + ) + + assert validate_invoice(request).errors == [] + + def test_present_on_xrechnung_passes(self): + result = extract_invoice(CII_XML.read_bytes()) + request = ValidateRequest( + xml_data=result.xml_data.model_dump(), + checks=ALL_CHECKS, + profile=result.zugferd_profil, + ) + + assert validate_invoice(request).errors == [] + + class TestUblCreditNote: """UBL CreditNote uses its own line and quantity element names.""" diff --git a/validator_schema.json b/validator_schema.json index c91c3cf..5a47eb2 100644 --- a/validator_schema.json +++ b/validator_schema.json @@ -29,6 +29,10 @@ "pattern": "^\\d{4}-\\d{2}-\\d{2}$", "examples": ["2024-02-01", "2025-01-15"] }, + "buyer_reference": { + "type": ["string", "null"], + "description": "Buyer reference (BT-10). On XRechnung invoices this is the Leitweg-ID and mandatory. Optional otherwise." + }, "due_date": { "type": ["string", "null"], "description": "Payment due date in ISO 8601 format (YYYY-MM-DD). Optional but recommended.", @@ -283,6 +287,11 @@ "description": "Raw text extracted from the PDF document. Used for 'pdf_abgleich' validation check to compare XML data with PDF text.", "examples": ["Invoice RE-2024-001\nTotal: 1190.00 EUR\n..."] }, + "profile": { + "type": ["string", "null"], + "description": "Invoice profile as returned by /extract in 'zugferd_profil' (e.g. EN16931, XRECHNUNG_3.0). Optional. Enables profile-specific rules: on XRECHNUNG_* profiles the buyer_reference is a required field.", + "examples": ["EN16931", "XRECHNUNG_3.0"] + }, "checks": { "type": "array", "description": "List of validation checks to run. Each check validates different aspects of the invoice data.",