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:
+12
-3
@@ -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),
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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),
|
||||
|
||||
+38
-3
@@ -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)
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -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.",
|
||||
|
||||
Reference in New Issue
Block a user