feat(extract): support plain XML invoices and UBL syntax
/extract now accepts all EN 16931 e-invoices, not only ZUGFeRD PDFs:
- plain XML files via the new xml_base64 field; XML sent as pdf_base64
is detected from the content
- UBL 2.1 Invoice and CreditNote (XRechnung UBL, Peppol BIS Billing) via
the new src/ubl_parser.py, also when embedded in a PDF
- new response field xml_syntax ("CII" or "UBL")
- CII invoice dates are normalized to YYYY-MM-DD, matching UBL
- XRechnung profiles are detected from the specification identifier,
independent of the factur-x version (6.x reports them as EN16931)
- untrusted XML is parsed without entity or DTD resolution (XXE)
Fixtures: KoSIT XRechnung test-suite case 01.01a in CII and UBL.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
+241
-33
@@ -1,10 +1,16 @@
|
||||
"""ZUGFeRD/Factur-X extractor.
|
||||
"""E-invoice extractor.
|
||||
|
||||
Extracts structured invoice data from PDF files using the factur-x library.
|
||||
Supports ZUGFeRD 2.x profiles: MINIMUM, BASIC, BASIC WL, EN16931, EXTENDED.
|
||||
Extracts structured invoice data from EN 16931 e-invoices in both syntaxes:
|
||||
|
||||
- CII (UN/CEFACT Cross Industry Invoice): ZUGFeRD 2.x / Factur-X profiles
|
||||
MINIMUM, BASIC, BASIC WL, EN16931, EXTENDED and XRechnung CII
|
||||
- UBL 2.1 (Invoice and CreditNote): XRechnung UBL, Peppol BIS Billing
|
||||
|
||||
Input is either a hybrid PDF with embedded XML or the plain XML file.
|
||||
"""
|
||||
|
||||
import io
|
||||
import re
|
||||
import time
|
||||
|
||||
from facturx import get_flavor, get_level, get_xml_from_pdf
|
||||
@@ -23,8 +29,16 @@ from src.models import (
|
||||
VatBreakdown,
|
||||
XmlData,
|
||||
)
|
||||
from src.ubl_parser import UBL_NAMESPACES, is_ubl_root, parse_ubl_xml
|
||||
|
||||
|
||||
MAX_FILE_SIZE = 10 * 1024 * 1024
|
||||
|
||||
CII_ROOT_TAG = (
|
||||
"{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}"
|
||||
"CrossIndustryInvoice"
|
||||
)
|
||||
|
||||
NAMESPACES = {
|
||||
"rsm": "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100",
|
||||
"ram": "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100",
|
||||
@@ -42,6 +56,25 @@ class ExtractionError(Exception):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
def _parse_xml(xml_bytes: bytes) -> etree._Element:
|
||||
"""Parse untrusted invoice XML without resolving entities or DTDs.
|
||||
|
||||
Invoice XML arrives from outside (API upload or PDF attachment), so
|
||||
external entities and network access are disabled (XXE protection).
|
||||
|
||||
Args:
|
||||
xml_bytes: Raw XML content
|
||||
|
||||
Returns:
|
||||
XML root element
|
||||
|
||||
Raises:
|
||||
etree.XMLSyntaxError: If the content is not well-formed XML
|
||||
"""
|
||||
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
|
||||
return etree.fromstring(xml_bytes, parser=parser)
|
||||
|
||||
|
||||
def extract_text_from_pdf(pdf_bytes: bytes) -> str:
|
||||
"""Extract text from PDF using pypdf.
|
||||
|
||||
@@ -368,6 +401,22 @@ def parse_payment_terms(xml_root: etree._Element) -> PaymentTerms | None:
|
||||
)
|
||||
|
||||
|
||||
def _normalize_cii_date(value: str) -> str:
|
||||
"""Convert a CII date in format 102 (YYYYMMDD) to ISO notation.
|
||||
|
||||
Args:
|
||||
value: Date string from a udt:DateTimeString element
|
||||
|
||||
Returns:
|
||||
Date as YYYY-MM-DD; values that are not eight digits are returned
|
||||
stripped but otherwise unchanged
|
||||
"""
|
||||
value = value.strip()
|
||||
if re.fullmatch(r"\d{8}", value):
|
||||
return f"{value[:4]}-{value[4:6]}-{value[6:]}"
|
||||
return value
|
||||
|
||||
|
||||
def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
|
||||
"""Parse ZUGFeRD XML bytes to structured XmlData.
|
||||
|
||||
@@ -377,7 +426,7 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
|
||||
Returns:
|
||||
XmlData model with all invoice fields
|
||||
"""
|
||||
xml_root = etree.fromstring(xml_bytes)
|
||||
xml_root = _parse_xml(xml_bytes)
|
||||
|
||||
invoice_number = xml_root.xpath(
|
||||
"//rsm:ExchangedDocument/ram:ID/text()", namespaces=NAMESPACES
|
||||
@@ -403,7 +452,7 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
|
||||
|
||||
return XmlData(
|
||||
invoice_number=invoice_number[0] if invoice_number else "",
|
||||
invoice_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,
|
||||
supplier=parse_supplier(xml_root),
|
||||
buyer=parse_buyer(xml_root),
|
||||
@@ -475,7 +524,7 @@ def _find_xml_attachment_fallback(pdf_bytes: bytes) -> tuple[str | None, bytes |
|
||||
|
||||
if subtype and ("xml" in str(subtype).lower() or "xml" in att.name.lower()):
|
||||
try:
|
||||
etree.fromstring(att.content)
|
||||
_parse_xml(att.content)
|
||||
logger.debug(
|
||||
"Found XML attachment via MIME fallback: %s",
|
||||
att.name,
|
||||
@@ -494,7 +543,7 @@ def _find_xml_attachment_fallback(pdf_bytes: bytes) -> tuple[str | None, bytes |
|
||||
continue
|
||||
if att.name.lower().endswith(".xml"):
|
||||
try:
|
||||
etree.fromstring(att.content)
|
||||
_parse_xml(att.content)
|
||||
logger.debug(
|
||||
"Found XML attachment via extension fallback: %s",
|
||||
att.name,
|
||||
@@ -527,8 +576,188 @@ def _profile_from_urn(urn: str) -> str:
|
||||
return urn.rsplit("#", maxsplit=1)[-1].rsplit(":", maxsplit=1)[-1]
|
||||
|
||||
|
||||
def _profile_from_customization_id(urn: str) -> str:
|
||||
"""Derive a readable profile name from a UBL CustomizationID (BT-24).
|
||||
|
||||
Args:
|
||||
urn: The specification identifier (e.g.
|
||||
'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0')
|
||||
|
||||
Returns:
|
||||
Short profile name (e.g. 'xrechnung_3.0', 'peppol_bis_billing_3.0',
|
||||
'en16931'), or 'unknown'
|
||||
"""
|
||||
lowered = urn.strip().lower()
|
||||
|
||||
xrechnung = re.search(r"xrechnung_(\d+(?:\.\d+)*)", lowered)
|
||||
if xrechnung:
|
||||
return f"xrechnung_{xrechnung.group(1)}"
|
||||
|
||||
peppol = re.search(r"peppol.*billing:(\d+(?:\.\d+)*)", lowered)
|
||||
if peppol:
|
||||
return f"peppol_bis_billing_{peppol.group(1)}"
|
||||
|
||||
if lowered == "urn:cen.eu:en16931:2017":
|
||||
return "en16931"
|
||||
|
||||
return _profile_from_urn(lowered)
|
||||
|
||||
|
||||
def _interpret_invoice_xml(xml_bytes: bytes) -> tuple[str, str, XmlData]:
|
||||
"""Detect syntax and profile of invoice XML and parse it.
|
||||
|
||||
Args:
|
||||
xml_bytes: Raw invoice XML (CII or UBL)
|
||||
|
||||
Returns:
|
||||
Tuple of (syntax, profile, parsed data); syntax is 'CII' or 'UBL'
|
||||
"""
|
||||
xml_root = _parse_xml(xml_bytes)
|
||||
|
||||
if is_ubl_root(xml_root):
|
||||
urn_nodes = xml_root.xpath(
|
||||
"./cbc:CustomizationID/text()", namespaces=UBL_NAMESPACES
|
||||
)
|
||||
urn = urn_nodes[0] if urn_nodes else ""
|
||||
return "UBL", _profile_from_customization_id(urn), parse_ubl_xml(xml_root)
|
||||
|
||||
# GuidelineSpecifiedDocumentContextParameter uses ram: namespace
|
||||
urn_nodes = xml_root.xpath(
|
||||
"//rsm:ExchangedDocumentContext/"
|
||||
"ram:GuidelineSpecifiedDocumentContextParameter/ram:ID/text()",
|
||||
namespaces=NAMESPACES,
|
||||
)
|
||||
urn = urn_nodes[0] if urn_nodes else ""
|
||||
|
||||
# XRechnung first: depending on its version, factur-x either rejects the
|
||||
# XRechnung URN or reports it as plain EN16931.
|
||||
xrechnung = re.search(r"xrechnung_(\d+(?:\.\d+)*)", urn.lower())
|
||||
if xrechnung:
|
||||
level = f"xrechnung_{xrechnung.group(1)}"
|
||||
else:
|
||||
flavor = get_flavor(xml_root)
|
||||
try:
|
||||
level = get_level(xml_root, flavor)
|
||||
except ValueError:
|
||||
level = _profile_from_urn(urn)
|
||||
|
||||
return "CII", level, parse_zugferd_xml(xml_bytes)
|
||||
|
||||
|
||||
def _xml_to_text(xml_bytes: bytes) -> str:
|
||||
"""Decode raw XML bytes to a string for the xml_raw response field.
|
||||
|
||||
Args:
|
||||
xml_bytes: Raw XML content in any encoding XML allows
|
||||
|
||||
Returns:
|
||||
XML document as string
|
||||
"""
|
||||
try:
|
||||
return xml_bytes.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
return etree.tostring(_parse_xml(xml_bytes), encoding="unicode")
|
||||
|
||||
|
||||
def _check_file_size(data: bytes) -> None:
|
||||
"""Reject uploads above the size limit.
|
||||
|
||||
Args:
|
||||
data: Raw file content
|
||||
|
||||
Raises:
|
||||
ExtractionError: If the file exceeds 10MB
|
||||
"""
|
||||
if len(data) > MAX_FILE_SIZE:
|
||||
raise ExtractionError(
|
||||
error_code="file_too_large",
|
||||
message="File exceeds 10MB limit",
|
||||
details=f"Size: {len(data)} bytes",
|
||||
)
|
||||
|
||||
|
||||
def extract_from_xml(xml_bytes: bytes) -> ExtractResponse:
|
||||
"""Extract invoice data from a plain e-invoice XML file.
|
||||
|
||||
Handles XRechnung and other EN 16931 invoices delivered without a PDF,
|
||||
in CII or UBL syntax.
|
||||
|
||||
Args:
|
||||
xml_bytes: Raw XML file content
|
||||
|
||||
Returns:
|
||||
ExtractResponse with is_zugferd, profile, xml_syntax and xml_data
|
||||
|
||||
Raises:
|
||||
ExtractionError: For malformed XML or unsupported document types
|
||||
"""
|
||||
start_time = time.time()
|
||||
_check_file_size(xml_bytes)
|
||||
|
||||
try:
|
||||
xml_root = _parse_xml(xml_bytes)
|
||||
except etree.XMLSyntaxError as e:
|
||||
raise ExtractionError(
|
||||
error_code="invalid_xml", message="Invalid XML file", details=str(e)
|
||||
) from e
|
||||
|
||||
if not is_ubl_root(xml_root) and xml_root.tag != CII_ROOT_TAG:
|
||||
raise ExtractionError(
|
||||
error_code="unsupported_xml_format",
|
||||
message="XML is not a supported e-invoice (CII or UBL)",
|
||||
details=f"Root element: {xml_root.tag}",
|
||||
)
|
||||
|
||||
syntax, level, xml_data = _interpret_invoice_xml(xml_bytes)
|
||||
|
||||
return ExtractResponse(
|
||||
is_zugferd=True,
|
||||
zugferd_profil=level.upper(),
|
||||
xml_syntax=syntax,
|
||||
xml_raw=_xml_to_text(xml_bytes),
|
||||
xml_data=xml_data,
|
||||
pdf_text=None,
|
||||
extraction_meta=ExtractionMeta(
|
||||
pages=0,
|
||||
xml_attachment_name=None,
|
||||
extraction_time_ms=int((time.time() - start_time) * 1000),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def extract_invoice(data: bytes) -> ExtractResponse:
|
||||
"""Extract invoice data from any supported e-invoice file.
|
||||
|
||||
The file type is detected from the content: PDFs (ZUGFeRD/Factur-X or
|
||||
any PDF with an embedded invoice XML) and plain XML files (CII or UBL).
|
||||
|
||||
Args:
|
||||
data: Raw file content (PDF or XML)
|
||||
|
||||
Returns:
|
||||
ExtractResponse with extraction results
|
||||
|
||||
Raises:
|
||||
ExtractionError: For unreadable or unsupported files
|
||||
"""
|
||||
_check_file_size(data)
|
||||
|
||||
if b"%PDF-" in data[:1024]:
|
||||
return extract_zugferd(data)
|
||||
|
||||
try:
|
||||
_parse_xml(data)
|
||||
except etree.XMLSyntaxError:
|
||||
if b"<" in data[:200]:
|
||||
return extract_from_xml(data)
|
||||
# Neither PDF nor XML: let the PDF path report the error
|
||||
return extract_zugferd(data)
|
||||
|
||||
return extract_from_xml(data)
|
||||
|
||||
|
||||
def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||
"""Extract ZUGFeRD data from PDF bytes.
|
||||
"""Extract e-invoice data from PDF bytes.
|
||||
|
||||
Args:
|
||||
pdf_bytes: Raw PDF file content as bytes
|
||||
@@ -540,17 +769,10 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||
ExtractionError: For PDF processing errors
|
||||
"""
|
||||
start_time = time.time()
|
||||
|
||||
if len(pdf_bytes) > 10 * 1024 * 1024:
|
||||
raise ExtractionError(
|
||||
error_code="file_too_large",
|
||||
message="File exceeds 10MB limit",
|
||||
details=f"Size: {len(pdf_bytes)} bytes",
|
||||
)
|
||||
_check_file_size(pdf_bytes)
|
||||
|
||||
xml_filename = None
|
||||
xml_bytes = None
|
||||
|
||||
try:
|
||||
xml_filename, xml_bytes = get_xml_from_pdf(pdf_bytes, check_xsd=False)
|
||||
except Exception as e:
|
||||
@@ -591,22 +813,7 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||
),
|
||||
)
|
||||
|
||||
xml_root = etree.fromstring(xml_bytes)
|
||||
flavor = get_flavor(xml_root)
|
||||
|
||||
try:
|
||||
level = get_level(xml_root, flavor)
|
||||
except ValueError:
|
||||
# GuidelineSpecifiedDocumentContextParameter uses ram: namespace
|
||||
urn_nodes = xml_root.xpath(
|
||||
"//rsm:ExchangedDocumentContext/"
|
||||
"ram:GuidelineSpecifiedDocumentContextParameter/ram:ID/text()",
|
||||
namespaces=NAMESPACES,
|
||||
)
|
||||
urn = urn_nodes[0] if urn_nodes else ""
|
||||
level = _profile_from_urn(urn)
|
||||
|
||||
xml_data = parse_zugferd_xml(xml_bytes)
|
||||
syntax, level, xml_data = _interpret_invoice_xml(xml_bytes)
|
||||
pdf_text = extract_text_from_pdf(pdf_bytes)
|
||||
pages = get_pdf_page_count(pdf_bytes)
|
||||
extraction_time_ms = int((time.time() - start_time) * 1000)
|
||||
@@ -614,7 +821,8 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||
return ExtractResponse(
|
||||
is_zugferd=True,
|
||||
zugferd_profil=level.upper(),
|
||||
xml_raw=xml_bytes.decode("utf-8"),
|
||||
xml_syntax=syntax,
|
||||
xml_raw=_xml_to_text(xml_bytes),
|
||||
xml_data=xml_data,
|
||||
pdf_text=pdf_text,
|
||||
extraction_meta=ExtractionMeta(
|
||||
|
||||
+7
-5
@@ -12,7 +12,7 @@ from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from src.extractor import ExtractionError, extract_zugferd
|
||||
from src.extractor import ExtractionError, extract_from_xml, extract_invoice
|
||||
from src.models import (
|
||||
ExtractRequest,
|
||||
ExtractResponse,
|
||||
@@ -113,23 +113,25 @@ async def health_check() -> HealthResponse:
|
||||
|
||||
@app.post("/extract", response_model=ExtractResponse)
|
||||
async def extract_pdf(request: ExtractRequest) -> ExtractResponse:
|
||||
"""Extract ZUGFeRD data from PDF.
|
||||
"""Extract e-invoice data from a PDF or a plain invoice XML.
|
||||
|
||||
Args:
|
||||
request: ExtractRequest with pdf_base64 field
|
||||
request: ExtractRequest with pdf_base64 or xml_base64 field
|
||||
|
||||
Returns:
|
||||
ExtractResponse with extraction results
|
||||
"""
|
||||
try:
|
||||
pdf_bytes = base64.b64decode(request.pdf_base64)
|
||||
file_bytes = base64.b64decode(request.xml_base64 or request.pdf_base64 or "")
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={"error": "invalid_base64", "message": "Invalid base64 encoding"},
|
||||
)
|
||||
|
||||
return extract_zugferd(pdf_bytes)
|
||||
if request.xml_base64 is not None:
|
||||
return extract_from_xml(file_bytes)
|
||||
return extract_invoice(file_bytes)
|
||||
|
||||
|
||||
@app.post("/validate", response_model=ValidateResponse)
|
||||
|
||||
+23
-4
@@ -2,7 +2,7 @@
|
||||
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
|
||||
class ExtractionMeta(BaseModel):
|
||||
@@ -111,15 +111,34 @@ class XmlData(BaseModel):
|
||||
class ExtractRequest(BaseModel):
|
||||
"""Request body for /extract endpoint."""
|
||||
|
||||
pdf_base64: str = Field(description="Base64-encoded PDF file")
|
||||
pdf_base64: str | None = Field(
|
||||
default=None,
|
||||
description="Base64-encoded invoice file (PDF, or plain invoice XML)",
|
||||
)
|
||||
xml_base64: str | None = Field(
|
||||
default=None,
|
||||
description="Base64-encoded plain invoice XML (XRechnung, CII or UBL)",
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _exactly_one_file(self) -> "ExtractRequest":
|
||||
if (self.pdf_base64 is None) == (self.xml_base64 is None):
|
||||
raise ValueError("Provide exactly one of 'pdf_base64' or 'xml_base64'")
|
||||
return self
|
||||
|
||||
|
||||
class ExtractResponse(BaseModel):
|
||||
"""Response from /extract endpoint."""
|
||||
|
||||
is_zugferd: bool = Field(description="Whether PDF contains ZUGFeRD data")
|
||||
is_zugferd: bool = Field(
|
||||
description="Whether the file contains structured e-invoice data"
|
||||
)
|
||||
zugferd_profil: str | None = Field(
|
||||
default=None, description="ZUGFeRD profile (e.g., EN16931)"
|
||||
default=None,
|
||||
description="Invoice profile (e.g., EN16931, XRECHNUNG_3.0)",
|
||||
)
|
||||
xml_syntax: str | None = Field(
|
||||
default=None, description="XML syntax of the invoice: 'CII' or 'UBL'"
|
||||
)
|
||||
xml_raw: str | None = Field(default=None, description="Raw XML string")
|
||||
xml_data: XmlData | None = Field(default=None, description="Parsed XML data")
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
"""UBL 2.1 invoice parser.
|
||||
|
||||
Maps EN 16931 invoices in UBL syntax (XRechnung UBL, Peppol BIS Billing)
|
||||
to the same XmlData structure the CII/ZUGFeRD parser produces. Supports the
|
||||
Invoice and CreditNote document types.
|
||||
"""
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from src.models import (
|
||||
Buyer,
|
||||
LineItem,
|
||||
PaymentTerms,
|
||||
Supplier,
|
||||
Totals,
|
||||
VatBreakdown,
|
||||
XmlData,
|
||||
)
|
||||
|
||||
|
||||
UBL_INVOICE_NS = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
|
||||
UBL_CREDIT_NOTE_NS = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"
|
||||
|
||||
UBL_ROOT_TAGS = {
|
||||
f"{{{UBL_INVOICE_NS}}}Invoice",
|
||||
f"{{{UBL_CREDIT_NOTE_NS}}}CreditNote",
|
||||
}
|
||||
|
||||
UBL_NAMESPACES = {
|
||||
"cac": "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2",
|
||||
"cbc": "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2",
|
||||
}
|
||||
|
||||
|
||||
def is_ubl_root(xml_root: etree._Element) -> bool:
|
||||
"""Check whether an XML root element is a UBL Invoice or CreditNote.
|
||||
|
||||
Args:
|
||||
xml_root: XML root element
|
||||
|
||||
Returns:
|
||||
True for UBL Invoice-2 / CreditNote-2 documents
|
||||
"""
|
||||
return xml_root.tag in UBL_ROOT_TAGS
|
||||
|
||||
|
||||
def _text(node: etree._Element, path: str) -> str | None:
|
||||
"""Return the stripped text of the first XPath match, or None.
|
||||
|
||||
Args:
|
||||
node: Context element
|
||||
path: XPath expression using the cac/cbc prefixes
|
||||
|
||||
Returns:
|
||||
Stripped text, or None when absent or empty
|
||||
"""
|
||||
result = node.xpath(path, namespaces=UBL_NAMESPACES)
|
||||
if not result:
|
||||
return None
|
||||
first = result[0]
|
||||
value = first if isinstance(first, str) else (first.text or "")
|
||||
value = value.strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def _number(node: etree._Element, path: str) -> float | None:
|
||||
"""Return the first XPath match as float, or None.
|
||||
|
||||
Args:
|
||||
node: Context element
|
||||
path: XPath expression using the cac/cbc prefixes
|
||||
|
||||
Returns:
|
||||
Parsed number, or None when absent or not numeric
|
||||
"""
|
||||
value = _text(node, path)
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _party_fields(party: etree._Element | None) -> dict[str, str | None]:
|
||||
"""Extract the fields shared by seller and buyer from a cac:Party.
|
||||
|
||||
Args:
|
||||
party: cac:Party element, or None when the party is missing
|
||||
|
||||
Returns:
|
||||
Dict with name, address, VAT ID, tax number and email
|
||||
"""
|
||||
if party is None:
|
||||
return {
|
||||
"name": "",
|
||||
"street": None,
|
||||
"postal_code": None,
|
||||
"city": None,
|
||||
"country": None,
|
||||
"vat_id": None,
|
||||
"tax_number": None,
|
||||
"email": None,
|
||||
}
|
||||
|
||||
# BT-27/BT-44 legal name; trading name (BT-28/BT-45) as fallback
|
||||
name = _text(party, "./cac:PartyLegalEntity/cbc:RegistrationName") or _text(
|
||||
party, "./cac:PartyName/cbc:Name"
|
||||
)
|
||||
email = _text(party, "./cac:Contact/cbc:ElectronicMail") or _text(
|
||||
party, "./cbc:EndpointID[@schemeID='EM']"
|
||||
)
|
||||
|
||||
return {
|
||||
"name": name or "",
|
||||
"street": _text(party, "./cac:PostalAddress/cbc:StreetName"),
|
||||
"postal_code": _text(party, "./cac:PostalAddress/cbc:PostalZone"),
|
||||
"city": _text(party, "./cac:PostalAddress/cbc:CityName"),
|
||||
"country": _text(
|
||||
party, "./cac:PostalAddress/cac:Country/cbc:IdentificationCode"
|
||||
),
|
||||
# BT-31/BT-48: tax scheme 'VAT'; BT-32: any other scheme (e.g. 'FC')
|
||||
"vat_id": _text(
|
||||
party, "./cac:PartyTaxScheme[cac:TaxScheme/cbc:ID='VAT']/cbc:CompanyID"
|
||||
),
|
||||
"tax_number": _text(
|
||||
party,
|
||||
"./cac:PartyTaxScheme[not(cac:TaxScheme/cbc:ID='VAT')]/cbc:CompanyID",
|
||||
),
|
||||
"email": email,
|
||||
}
|
||||
|
||||
|
||||
def _first(node: etree._Element, path: str) -> etree._Element | None:
|
||||
"""Return the first element matching an XPath, or None.
|
||||
|
||||
Args:
|
||||
node: Context element
|
||||
path: XPath expression using the cac/cbc prefixes
|
||||
|
||||
Returns:
|
||||
First matching element, or None
|
||||
"""
|
||||
result = node.xpath(path, namespaces=UBL_NAMESPACES)
|
||||
return result[0] if result else None
|
||||
|
||||
|
||||
def parse_ubl_supplier(xml_root: etree._Element) -> Supplier:
|
||||
"""Parse the seller (cac:AccountingSupplierParty) from a UBL document.
|
||||
|
||||
Args:
|
||||
xml_root: UBL Invoice or CreditNote root element
|
||||
|
||||
Returns:
|
||||
Supplier model
|
||||
"""
|
||||
party = _first(xml_root, "./cac:AccountingSupplierParty/cac:Party")
|
||||
return Supplier(**_party_fields(party))
|
||||
|
||||
|
||||
def parse_ubl_buyer(xml_root: etree._Element) -> Buyer:
|
||||
"""Parse the buyer (cac:AccountingCustomerParty) from a UBL document.
|
||||
|
||||
Args:
|
||||
xml_root: UBL Invoice or CreditNote root element
|
||||
|
||||
Returns:
|
||||
Buyer model
|
||||
"""
|
||||
party = _first(xml_root, "./cac:AccountingCustomerParty/cac:Party")
|
||||
fields = _party_fields(party)
|
||||
fields.pop("email")
|
||||
return Buyer(**fields)
|
||||
|
||||
|
||||
def parse_ubl_line_items(xml_root: etree._Element) -> list[LineItem]:
|
||||
"""Parse invoice lines from a UBL document.
|
||||
|
||||
Only top-level lines are returned; nested sub-lines (XRechnung extension)
|
||||
are already contained in their parent's amounts.
|
||||
|
||||
Args:
|
||||
xml_root: UBL Invoice or CreditNote root element
|
||||
|
||||
Returns:
|
||||
List of LineItem models
|
||||
"""
|
||||
line_nodes = xml_root.xpath(
|
||||
"./cac:InvoiceLine | ./cac:CreditNoteLine", namespaces=UBL_NAMESPACES
|
||||
)
|
||||
items = []
|
||||
|
||||
for idx, line in enumerate(line_nodes, start=1):
|
||||
quantity_path = "./cbc:InvoicedQuantity | ./cbc:CreditedQuantity"
|
||||
quantity_node = _first(line, quantity_path)
|
||||
unit = quantity_node.get("unitCode") if quantity_node is not None else None
|
||||
|
||||
# Base quantity (BT-149): price amount applies to N units
|
||||
unit_price = _number(line, "./cac:Price/cbc:PriceAmount")
|
||||
base_quantity = _number(line, "./cac:Price/cbc:BaseQuantity")
|
||||
if unit_price is not None and base_quantity is not None and base_quantity > 0:
|
||||
unit_price = unit_price / base_quantity
|
||||
|
||||
items.append(
|
||||
LineItem(
|
||||
position=idx,
|
||||
article_number=_text(
|
||||
line, "./cac:Item/cac:SellersItemIdentification/cbc:ID"
|
||||
),
|
||||
article_number_buyer=_text(
|
||||
line, "./cac:Item/cac:BuyersItemIdentification/cbc:ID"
|
||||
),
|
||||
description=_text(line, "./cac:Item/cbc:Name") or "",
|
||||
quantity=_number(line, quantity_path) or 0.0,
|
||||
unit=unit or "Stück",
|
||||
unit_price=unit_price,
|
||||
line_total=_number(line, "./cbc:LineExtensionAmount"),
|
||||
vat_rate=_number(
|
||||
line, "./cac:Item/cac:ClassifiedTaxCategory/cbc:Percent"
|
||||
),
|
||||
vat_amount=None,
|
||||
)
|
||||
)
|
||||
|
||||
return items
|
||||
|
||||
|
||||
def parse_ubl_totals(xml_root: etree._Element, currency: str | None) -> Totals:
|
||||
"""Parse document totals and the VAT breakdown from a UBL document.
|
||||
|
||||
Args:
|
||||
xml_root: UBL Invoice or CreditNote root element
|
||||
currency: Document currency code, used to pick the right cac:TaxTotal
|
||||
when a second one in the tax accounting currency is present
|
||||
|
||||
Returns:
|
||||
Totals model
|
||||
"""
|
||||
tax_totals = xml_root.xpath("./cac:TaxTotal", namespaces=UBL_NAMESPACES)
|
||||
tax_total = None
|
||||
for candidate in tax_totals:
|
||||
amount_node = _first(candidate, "./cbc:TaxAmount")
|
||||
if amount_node is not None and amount_node.get("currencyID") == currency:
|
||||
tax_total = candidate
|
||||
break
|
||||
if tax_total is None and tax_totals:
|
||||
tax_total = tax_totals[0]
|
||||
|
||||
vat_total = None
|
||||
vat_breakdown = []
|
||||
if tax_total is not None:
|
||||
vat_total = _number(tax_total, "./cbc:TaxAmount")
|
||||
for subtotal in tax_total.xpath("./cac:TaxSubtotal", namespaces=UBL_NAMESPACES):
|
||||
base = _number(subtotal, "./cbc:TaxableAmount")
|
||||
amount = _number(subtotal, "./cbc:TaxAmount")
|
||||
if base is None or amount is None:
|
||||
continue
|
||||
# Percent is omitted for categories without a rate (e.g. 'O')
|
||||
rate = _number(subtotal, "./cac:TaxCategory/cbc:Percent") or 0.0
|
||||
vat_breakdown.append(VatBreakdown(rate=rate, base=base, amount=amount))
|
||||
|
||||
monetary = "./cac:LegalMonetaryTotal"
|
||||
return Totals(
|
||||
line_total_sum=_number(xml_root, f"{monetary}/cbc:LineExtensionAmount") or 0.0,
|
||||
net=_number(xml_root, f"{monetary}/cbc:TaxExclusiveAmount") or 0.0,
|
||||
vat_total=vat_total or 0.0,
|
||||
gross=_number(xml_root, f"{monetary}/cbc:TaxInclusiveAmount") or 0.0,
|
||||
vat_breakdown=vat_breakdown,
|
||||
)
|
||||
|
||||
|
||||
def parse_ubl_payment_terms(xml_root: etree._Element) -> PaymentTerms | None:
|
||||
"""Parse credit transfer details from a UBL document.
|
||||
|
||||
Args:
|
||||
xml_root: UBL Invoice or CreditNote root element
|
||||
|
||||
Returns:
|
||||
PaymentTerms model, or None when no account data is present
|
||||
"""
|
||||
account = "./cac:PaymentMeans/cac:PayeeFinancialAccount"
|
||||
iban = _text(xml_root, f"{account}/cbc:ID")
|
||||
bic = _text(xml_root, f"{account}/cac:FinancialInstitutionBranch/cbc:ID")
|
||||
account_holder = _text(xml_root, f"{account}/cbc:Name")
|
||||
|
||||
if not (iban or bic or account_holder):
|
||||
return None
|
||||
|
||||
return PaymentTerms(iban=iban, bic=bic, account_holder=account_holder)
|
||||
|
||||
|
||||
def parse_ubl_xml(xml_root: etree._Element) -> XmlData:
|
||||
"""Parse a UBL Invoice or CreditNote to structured XmlData.
|
||||
|
||||
Args:
|
||||
xml_root: UBL Invoice or CreditNote root element
|
||||
|
||||
Returns:
|
||||
XmlData model with all invoice fields
|
||||
"""
|
||||
currency = _text(xml_root, "./cbc:DocumentCurrencyCode")
|
||||
# BT-9: cbc:DueDate on invoices, PaymentMeans/PaymentDueDate on credit notes
|
||||
due_date = _text(xml_root, "./cbc:DueDate") or _text(
|
||||
xml_root, "./cac:PaymentMeans/cbc:PaymentDueDate"
|
||||
)
|
||||
|
||||
return XmlData(
|
||||
invoice_number=_text(xml_root, "./cbc:ID") or "",
|
||||
invoice_date=_text(xml_root, "./cbc:IssueDate") or "",
|
||||
due_date=due_date,
|
||||
supplier=parse_ubl_supplier(xml_root),
|
||||
buyer=parse_ubl_buyer(xml_root),
|
||||
line_items=parse_ubl_line_items(xml_root),
|
||||
totals=parse_ubl_totals(xml_root, currency),
|
||||
currency=currency or "EUR",
|
||||
payment_terms=parse_ubl_payment_terms(xml_root),
|
||||
notes=_text(xml_root, "./cbc:Note"),
|
||||
)
|
||||
Reference in New Issue
Block a user