feat: extract due date and buyer reference, require it on XRechnung

- CII: due_date is read from the payment due date (BT-9) instead of the
  delivery terms description, normalized to YYYY-MM-DD
- new field buyer_reference (BT-10, the Leitweg-ID) for CII and UBL
- /validate accepts an optional profile; on XRECHNUNG_* profiles a
  missing buyer reference is a critical error (BR-DE-15)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 18:33:08 +01:00
co-authored by Claude Fable 5.2
parent 4ff994a299
commit fa9eaa4f82
8 changed files with 117 additions and 6 deletions
+12 -3
View File
@@ -435,9 +435,15 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
"//rsm:ExchangedDocument/ram:IssueDateTime/udt:DateTimeString[@format='102']/text()", "//rsm:ExchangedDocument/ram:IssueDateTime/udt:DateTimeString[@format='102']/text()",
namespaces=NAMESPACES, namespaces=NAMESPACES,
) )
# BT-9 payment due date
due_date = xml_root.xpath( due_date = xml_root.xpath(
"//ram:ApplicableHeaderTradeAgreement/ram:ApplicableTradeDeliveryTerms/" "//ram:ApplicableHeaderTradeSettlement/ram:SpecifiedTradePaymentTerms/"
"ram:Description/text()", "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, namespaces=NAMESPACES,
) )
notes = xml_root.xpath( notes = xml_root.xpath(
@@ -453,7 +459,10 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
return XmlData( return XmlData(
invoice_number=invoice_number[0] if invoice_number else "", invoice_number=invoice_number[0] if invoice_number else "",
invoice_date=_normalize_cii_date(invoice_date[0]) if invoice_date 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), supplier=parse_supplier(xml_root),
buyer=parse_buyer(xml_root), buyer=parse_buyer(xml_root),
line_items=parse_line_items(xml_root), line_items=parse_line_items(xml_root),
+12
View File
@@ -97,6 +97,10 @@ class XmlData(BaseModel):
invoice_number: str = Field(description="Invoice number") invoice_number: str = Field(description="Invoice number")
invoice_date: str = Field(description="Invoice date (YYYY-MM-DD)") invoice_date: str = Field(description="Invoice date (YYYY-MM-DD)")
due_date: str | None = Field(default=None, description="Due 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") supplier: Supplier = Field(description="Supplier information")
buyer: Buyer = Field(description="Buyer information") buyer: Buyer = Field(description="Buyer information")
line_items: list[LineItem] = Field(description="Line items") line_items: list[LineItem] = Field(description="Line items")
@@ -178,6 +182,14 @@ class ValidateRequest(BaseModel):
default=None, description="Extracted PDF text for comparison" default=None, description="Extracted PDF text for comparison"
) )
checks: list[str] = Field(description="List of validation checks to run") 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): class ValidateResponse(BaseModel):
+1
View File
@@ -308,6 +308,7 @@ def parse_ubl_xml(xml_root: etree._Element) -> XmlData:
invoice_number=_text(xml_root, "./cbc:ID") or "", invoice_number=_text(xml_root, "./cbc:ID") or "",
invoice_date=_text(xml_root, "./cbc:IssueDate") or "", invoice_date=_text(xml_root, "./cbc:IssueDate") or "",
due_date=due_date, due_date=due_date,
buyer_reference=_text(xml_root, "./cbc:BuyerReference"),
supplier=parse_ubl_supplier(xml_root), supplier=parse_ubl_supplier(xml_root),
buyer=parse_ubl_buyer(xml_root), buyer=parse_ubl_buyer(xml_root),
line_items=parse_ubl_line_items(xml_root), line_items=parse_ubl_line_items(xml_root),
+38 -3
View File
@@ -15,8 +15,30 @@ from src.models import (
from src.utils import amounts_match from src.utils import amounts_match
def validate_pflichtfelder(xml_data: XmlData) -> list[ErrorDetail]: def is_xrechnung_profile(profile: str | None) -> bool:
"""Check required fields are present.""" """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 = [] errors = []
def add_error(field: str, severity: str, message: str | None = None) -> None: 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(): if not xml_data.buyer.name or not xml_data.buyer.name.strip():
add_error("buyer.name", "critical") 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: if xml_data.totals.net == 0:
add_error("totals.net", "critical") add_error("totals.net", "critical")
@@ -337,7 +372,7 @@ def validate_invoice(request: ValidateRequest) -> ValidationResult:
check_errors: list[ErrorDetail] = [] check_errors: list[ErrorDetail] = []
if check_name == "pflichtfelder": if check_name == "pflichtfelder":
check_errors = validate_pflichtfelder(xml_data) check_errors = validate_pflichtfelder(xml_data, request.profile)
checks_run += 1 checks_run += 1
elif check_name == "betraege": elif check_name == "betraege":
check_errors = validate_betraege(xml_data) check_errors = validate_betraege(xml_data)
+1
View File
@@ -77,6 +77,7 @@ def test_fixture_sweep(filename: str) -> None:
xml_data=result.xml_data.model_dump(), xml_data=result.xml_data.model_dump(),
pdf_text=result.pdf_text, pdf_text=result.pdf_text,
checks=ALL_CHECKS, checks=ALL_CHECKS,
profile=result.zugferd_profil,
) )
validation = validate_invoice(request) validation = validate_invoice(request)
critical_fields = {error.field for error in validation.errors} critical_fields = {error.field for error in validation.errors}
+2
View File
@@ -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. here that locks in the correct behavior.
""" """
import re
from io import BytesIO from io import BytesIO
from pathlib import Path from pathlib import Path
@@ -51,6 +52,7 @@ class TestFcTaxNumberBasisQuantityInvoice:
data = result.xml_data data = result.xml_data
assert data.invoice_number == "4711" 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.tax_number == "1112223334444"
assert data.supplier.vat_id is None assert data.supplier.vat_id is None
assert data.supplier.email == "rechnung@beispielwerkstatt.example" assert data.supplier.email == "rechnung@beispielwerkstatt.example"
+42
View File
@@ -111,6 +111,7 @@ class TestPlainXml:
assert result.extraction_meta.xml_attachment_name is None assert result.extraction_meta.xml_attachment_name is None
assert result.xml_data.invoice_number == "123456XX" assert result.xml_data.invoice_number == "123456XX"
assert result.xml_data.invoice_date == "2016-04-04" 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) assert result.xml_data.totals.gross == pytest.approx(336.9)
def test_ubl_xml(self): def test_ubl_xml(self):
@@ -124,6 +125,7 @@ class TestPlainXml:
data = result.xml_data data = result.xml_data
assert data.invoice_number == "123456XX" assert data.invoice_number == "123456XX"
assert data.invoice_date == "2016-04-04" assert data.invoice_date == "2016-04-04"
assert data.buyer_reference == "04011000-12345-03"
assert data.currency == "EUR" assert data.currency == "EUR"
assert data.supplier.name == "[Seller name]" assert data.supplier.name == "[Seller name]"
assert data.supplier.vat_id == "DE 123456789" assert data.supplier.vat_id == "DE 123456789"
@@ -173,6 +175,46 @@ class TestPlainXml:
assert not result.xml_raw.startswith("") 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: class TestUblCreditNote:
"""UBL CreditNote uses its own line and quantity element names.""" """UBL CreditNote uses its own line and quantity element names."""
+9
View File
@@ -29,6 +29,10 @@
"pattern": "^\\d{4}-\\d{2}-\\d{2}$", "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
"examples": ["2024-02-01", "2025-01-15"] "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": { "due_date": {
"type": ["string", "null"], "type": ["string", "null"],
"description": "Payment due date in ISO 8601 format (YYYY-MM-DD). Optional but recommended.", "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.", "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..."] "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": { "checks": {
"type": "array", "type": "array",
"description": "List of validation checks to run. Each check validates different aspects of the invoice data.", "description": "List of validation checks to run. Each check validates different aspects of the invoice data.",