- 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>
843 lines
27 KiB
Python
843 lines
27 KiB
Python
"""E-invoice extractor.
|
|
|
|
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
|
|
import lxml.etree as etree
|
|
from pypdf import PdfReader
|
|
from pypdf.errors import PdfReadError, PyPdfError
|
|
|
|
from src.models import (
|
|
Buyer,
|
|
ExtractionMeta,
|
|
ExtractResponse,
|
|
LineItem,
|
|
PaymentTerms,
|
|
Supplier,
|
|
Totals,
|
|
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",
|
|
"udt": "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100",
|
|
}
|
|
|
|
|
|
class ExtractionError(Exception):
|
|
"""Error during PDF extraction."""
|
|
|
|
def __init__(self, error_code: str, message: str, details: str = ""):
|
|
self.error_code = error_code
|
|
self.message = message
|
|
self.details = details
|
|
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.
|
|
|
|
Args:
|
|
pdf_bytes: Raw PDF file content
|
|
|
|
Returns:
|
|
Extracted text from all pages
|
|
"""
|
|
try:
|
|
pdf_stream = io.BytesIO(pdf_bytes)
|
|
reader = PdfReader(pdf_stream)
|
|
text_parts = []
|
|
for page in reader.pages:
|
|
text = page.extract_text()
|
|
if text:
|
|
text_parts.append(text)
|
|
return "\n".join(text_parts)
|
|
except (PdfReadError, PyPdfError) as e:
|
|
raise ExtractionError(
|
|
error_code="corrupt_pdf", message="Failed to read PDF", details=str(e)
|
|
) from e
|
|
|
|
|
|
def parse_supplier(xml_root: etree._Element) -> Supplier:
|
|
"""Parse supplier information from XML.
|
|
|
|
Args:
|
|
xml_root: XML root element
|
|
|
|
Returns:
|
|
Supplier model
|
|
"""
|
|
name = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/ram:Name/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
street = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/"
|
|
"ram:PostalTradeAddress/ram:LineOne/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
postal_code = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/"
|
|
"ram:PostalTradeAddress/ram:PostcodeCode/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
city = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/"
|
|
"ram:PostalTradeAddress/ram:CityName/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
country = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/"
|
|
"ram:PostalTradeAddress/ram:CountryID/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
vat_id = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/ram:SpecifiedTaxRegistration/"
|
|
"ram:ID[@schemeID='VA']/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
tax_number = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/ram:SpecifiedTaxRegistration/"
|
|
"ram:ID[@schemeID='FC']/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
email = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/"
|
|
"ram:URIUniversalCommunication/ram:URIID/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
# Fallback: email address from the seller's defined trade contact (BT-42)
|
|
if not email:
|
|
email = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:SellerTradeParty/"
|
|
"ram:DefinedTradeContact/ram:EmailURIUniversalCommunication/ram:URIID/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
|
|
return Supplier(
|
|
name=name[0] if name else "",
|
|
street=street[0] if street else None,
|
|
postal_code=postal_code[0] if postal_code else None,
|
|
city=city[0] if city else None,
|
|
country=country[0] if country else None,
|
|
vat_id=vat_id[0] if vat_id else None,
|
|
tax_number=tax_number[0] if tax_number else None,
|
|
email=email[0] if email else None,
|
|
)
|
|
|
|
|
|
def parse_buyer(xml_root: etree._Element) -> Buyer:
|
|
"""Parse buyer information from XML.
|
|
|
|
Args:
|
|
xml_root: XML root element
|
|
|
|
Returns:
|
|
Buyer model
|
|
"""
|
|
name = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:BuyerTradeParty/ram:Name/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
street = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:BuyerTradeParty/"
|
|
"ram:PostalTradeAddress/ram:LineOne/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
postal_code = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:BuyerTradeParty/"
|
|
"ram:PostalTradeAddress/ram:PostcodeCode/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
city = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:BuyerTradeParty/"
|
|
"ram:PostalTradeAddress/ram:CityName/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
country = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:BuyerTradeParty/"
|
|
"ram:PostalTradeAddress/ram:CountryID/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
vat_id = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:BuyerTradeParty/ram:SpecifiedTaxRegistration/"
|
|
"ram:ID[@schemeID='VA']/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
tax_number = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeAgreement/ram:BuyerTradeParty/ram:SpecifiedTaxRegistration/"
|
|
"ram:ID[@schemeID='FC']/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
|
|
return Buyer(
|
|
name=name[0] if name else "",
|
|
street=street[0] if street else None,
|
|
postal_code=postal_code[0] if postal_code else None,
|
|
city=city[0] if city else None,
|
|
country=country[0] if country else None,
|
|
vat_id=vat_id[0] if vat_id else None,
|
|
tax_number=tax_number[0] if tax_number else None,
|
|
)
|
|
|
|
|
|
def parse_line_items(xml_root: etree._Element) -> list[LineItem]:
|
|
"""Parse line items from XML.
|
|
|
|
Args:
|
|
xml_root: XML root element
|
|
|
|
Returns:
|
|
List of LineItem models
|
|
"""
|
|
line_items_nodes = xml_root.xpath(
|
|
"//ram:IncludedSupplyChainTradeLineItem", namespaces=NAMESPACES
|
|
)
|
|
items = []
|
|
|
|
for idx, item_node in enumerate(line_items_nodes, start=1):
|
|
position = idx
|
|
article_number = item_node.xpath(
|
|
"./ram:SpecifiedTradeProduct/ram:SellerAssignedID/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
article_number_buyer = item_node.xpath(
|
|
"./ram:SpecifiedTradeProduct/ram:BuyerAssignedID/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
description = item_node.xpath(
|
|
"./ram:SpecifiedTradeProduct/ram:Name/text()", namespaces=NAMESPACES
|
|
)
|
|
quantity = item_node.xpath(
|
|
"./ram:SpecifiedLineTradeDelivery/ram:BilledQuantity/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
unit_code = item_node.xpath(
|
|
"./ram:SpecifiedLineTradeDelivery/ram:BilledQuantity/@unitCode",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
unit_price = item_node.xpath(
|
|
"./ram:SpecifiedLineTradeAgreement/ram:NetPriceProductTradePrice/ram:ChargeAmount/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
basis_quantity = item_node.xpath(
|
|
"./ram:SpecifiedLineTradeAgreement/ram:NetPriceProductTradePrice/"
|
|
"ram:BasisQuantity/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
line_total = item_node.xpath(
|
|
"./ram:SpecifiedLineTradeSettlement/ram:SpecifiedTradeSettlementLineMonetarySummation/"
|
|
"ram:LineTotalAmount/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
vat_rate = item_node.xpath(
|
|
"./ram:SpecifiedLineTradeSettlement/ram:ApplicableTradeTax/ram:RateApplicablePercent/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
vat_amount = item_node.xpath(
|
|
"./ram:SpecifiedLineTradeSettlement/ram:ApplicableTradeTax/ram:CalculatedAmount/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
|
|
unit = unit_code[0] if unit_code else "Stück"
|
|
|
|
# Basis quantity (BT-149): charge amount applies to N units (e.g. price per 100)
|
|
effective_unit_price = float(unit_price[0]) if unit_price else None
|
|
if effective_unit_price is not None and basis_quantity:
|
|
base = float(basis_quantity[0])
|
|
if base > 0:
|
|
effective_unit_price = effective_unit_price / base
|
|
|
|
items.append(
|
|
LineItem(
|
|
position=position,
|
|
article_number=article_number[0] if article_number else None,
|
|
article_number_buyer=article_number_buyer[0]
|
|
if article_number_buyer
|
|
else None,
|
|
description=description[0] if description else "",
|
|
quantity=float(quantity[0]) if quantity else 0.0,
|
|
unit=unit,
|
|
unit_price=effective_unit_price,
|
|
line_total=float(line_total[0]) if line_total else None,
|
|
vat_rate=float(vat_rate[0]) if vat_rate else None,
|
|
vat_amount=float(vat_amount[0]) if vat_amount else None,
|
|
)
|
|
)
|
|
|
|
return items
|
|
|
|
|
|
def parse_totals(xml_root: etree._Element) -> Totals:
|
|
"""Parse invoice totals from XML.
|
|
|
|
Args:
|
|
xml_root: XML root element
|
|
|
|
Returns:
|
|
Totals model
|
|
"""
|
|
line_total_sum = xml_root.xpath(
|
|
"//ram:SpecifiedTradeSettlementHeaderMonetarySummation/ram:LineTotalAmount/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
net = xml_root.xpath(
|
|
"//ram:SpecifiedTradeSettlementHeaderMonetarySummation/ram:TaxBasisTotalAmount/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
vat_total = xml_root.xpath(
|
|
"//ram:SpecifiedTradeSettlementHeaderMonetarySummation/ram:TaxTotalAmount/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
gross = xml_root.xpath(
|
|
"//ram:SpecifiedTradeSettlementHeaderMonetarySummation/ram:GrandTotalAmount/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
|
|
vat_breakdown_nodes = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeSettlement/ram:ApplicableTradeTax",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
vat_breakdown = []
|
|
|
|
for vat_node in vat_breakdown_nodes:
|
|
rate = vat_node.xpath(
|
|
"./ram:RateApplicablePercent/text()", namespaces=NAMESPACES
|
|
)
|
|
base = vat_node.xpath("./ram:BasisAmount/text()", namespaces=NAMESPACES)
|
|
amount = vat_node.xpath("./ram:CalculatedAmount/text()", namespaces=NAMESPACES)
|
|
|
|
if rate and base and amount:
|
|
vat_breakdown.append(
|
|
VatBreakdown(
|
|
rate=float(rate[0]),
|
|
base=float(base[0]),
|
|
amount=float(amount[0]),
|
|
)
|
|
)
|
|
|
|
return Totals(
|
|
line_total_sum=float(line_total_sum[0]) if line_total_sum else 0.0,
|
|
net=float(net[0]) if net else 0.0,
|
|
vat_total=float(vat_total[0]) if vat_total else 0.0,
|
|
gross=float(gross[0]) if gross else 0.0,
|
|
vat_breakdown=vat_breakdown,
|
|
)
|
|
|
|
|
|
def parse_payment_terms(xml_root: etree._Element) -> PaymentTerms | None:
|
|
"""Parse payment terms from XML.
|
|
|
|
Args:
|
|
xml_root: XML root element
|
|
|
|
Returns:
|
|
PaymentTerms model or None
|
|
"""
|
|
iban = xml_root.xpath(
|
|
"//ram:SpecifiedTradeSettlementPaymentMeans/ram:PayeePartyCreditorFinancialAccount/"
|
|
"ram:IBANID/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
bic = xml_root.xpath(
|
|
"//ram:SpecifiedTradeSettlementPaymentMeans/ram:PayeePartyCreditorFinancialInstitution/"
|
|
"ram:BICID/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
account_holder = xml_root.xpath(
|
|
"//ram:SpecifiedTradeSettlementPaymentMeans/ram:PayeePartyCreditorFinancialAccount/"
|
|
"ram:ProprietaryAccountName/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
|
|
if not (iban or bic or account_holder):
|
|
return None
|
|
|
|
return PaymentTerms(
|
|
iban=iban[0] if iban else None,
|
|
bic=bic[0] if bic else None,
|
|
account_holder=account_holder[0] if account_holder else 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.
|
|
|
|
Args:
|
|
xml_bytes: Raw XML bytes from PDF
|
|
|
|
Returns:
|
|
XmlData model with all invoice fields
|
|
"""
|
|
xml_root = _parse_xml(xml_bytes)
|
|
|
|
invoice_number = xml_root.xpath(
|
|
"//rsm:ExchangedDocument/ram:ID/text()", namespaces=NAMESPACES
|
|
)
|
|
invoice_date = xml_root.xpath(
|
|
"//rsm:ExchangedDocument/ram:IssueDateTime/udt:DateTimeString[@format='102']/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
# BT-9 payment due date
|
|
due_date = xml_root.xpath(
|
|
"//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(
|
|
"//rsm:ExchangedDocument/ram:IncludedNote/ram:Content/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
|
|
currency = xml_root.xpath(
|
|
"//ram:ApplicableHeaderTradeSettlement/ram:InvoiceCurrencyCode/text()",
|
|
namespaces=NAMESPACES,
|
|
)
|
|
|
|
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=_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),
|
|
totals=parse_totals(xml_root),
|
|
currency=currency[0] if currency else "EUR",
|
|
payment_terms=parse_payment_terms(xml_root),
|
|
notes=notes[0] if notes else None,
|
|
)
|
|
|
|
|
|
def get_pdf_page_count(pdf_bytes: bytes) -> int:
|
|
"""Get number of pages in PDF.
|
|
|
|
Args:
|
|
pdf_bytes: Raw PDF file content
|
|
|
|
Returns:
|
|
Number of pages
|
|
"""
|
|
try:
|
|
pdf_stream = io.BytesIO(pdf_bytes)
|
|
reader = PdfReader(pdf_stream)
|
|
return len(reader.pages)
|
|
except (PdfReadError, PyPdfError):
|
|
return 0
|
|
|
|
|
|
def _find_xml_attachment_fallback(pdf_bytes: bytes) -> tuple[str | None, bytes | None]:
|
|
"""Find XML attachment by MIME type or filename extension (fallback mechanism).
|
|
|
|
This handles XRechnung and other XML-based invoices with non-standard
|
|
filenames (e.g., 'xrechnung.xml' instead of 'factur-x.xml') that the
|
|
factur-x library does not recognize.
|
|
|
|
Args:
|
|
pdf_bytes: Raw PDF file content.
|
|
|
|
Returns:
|
|
Tuple of (filename, xml_bytes) or (None, None) if not found.
|
|
"""
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
try:
|
|
pdf_stream = io.BytesIO(pdf_bytes)
|
|
reader = PdfReader(pdf_stream)
|
|
except (PdfReadError, PyPdfError) as e:
|
|
logger.debug(
|
|
"Failed to read PDF for XML attachment fallback search: %s",
|
|
str(e),
|
|
)
|
|
return (None, None)
|
|
except Exception as e:
|
|
raise ExtractionError(
|
|
error_code="fallback_pdf_read_error",
|
|
message="Unexpected error reading PDF for XML attachment fallback",
|
|
details=str(e),
|
|
) from e
|
|
|
|
# First pass: check MIME type via Subtype in Filespec or by content type
|
|
# Common XML MIME types: application/xml, text/xml
|
|
for att in reader.attachment_list:
|
|
if not att.content:
|
|
continue
|
|
|
|
subtype = getattr(att, "subtype", None) or getattr(att, "mediatype", None)
|
|
|
|
if subtype and ("xml" in str(subtype).lower() or "xml" in att.name.lower()):
|
|
try:
|
|
_parse_xml(att.content)
|
|
logger.debug(
|
|
"Found XML attachment via MIME fallback: %s",
|
|
att.name,
|
|
)
|
|
return (att.name, att.content)
|
|
except etree.XMLSyntaxError:
|
|
logger.debug(
|
|
"Attachment '%s' has XML MIME but invalid XML content",
|
|
att.name,
|
|
)
|
|
continue
|
|
|
|
# Second pass: check by filename extension for any XML file
|
|
for att in reader.attachment_list:
|
|
if not att.content:
|
|
continue
|
|
if att.name.lower().endswith(".xml"):
|
|
try:
|
|
_parse_xml(att.content)
|
|
logger.debug(
|
|
"Found XML attachment via extension fallback: %s",
|
|
att.name,
|
|
)
|
|
return (att.name, att.content)
|
|
except etree.XMLSyntaxError:
|
|
logger.debug(
|
|
"Attachment '%s' has .xml extension but invalid XML content",
|
|
att.name,
|
|
)
|
|
continue
|
|
|
|
return (None, None)
|
|
|
|
|
|
def _profile_from_urn(urn: str) -> str:
|
|
"""Extract a short profile name from a Factur-X/ZUGFeRD URN.
|
|
|
|
Falls back to the last segment of the URN after '#', or 'unknown'.
|
|
|
|
Args:
|
|
urn: The full profile URN (e.g.
|
|
'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0')
|
|
|
|
Returns:
|
|
Short profile name (e.g. 'xrechnung_3.0')
|
|
"""
|
|
if not urn:
|
|
return "unknown"
|
|
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 e-invoice data from PDF bytes.
|
|
|
|
Args:
|
|
pdf_bytes: Raw PDF file content as bytes
|
|
|
|
Returns:
|
|
ExtractResponse with is_zugferd, profile, xml_data, pdf_text
|
|
|
|
Raises:
|
|
ExtractionError: For PDF processing errors
|
|
"""
|
|
start_time = time.time()
|
|
_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:
|
|
error_msg = str(e).lower()
|
|
if "password" in error_msg or "encrypted" in error_msg:
|
|
raise ExtractionError(
|
|
error_code="password_protected_pdf",
|
|
message="PDF is password protected",
|
|
details=str(e),
|
|
) from e
|
|
if "pdf" in error_msg or "trailer" in error_msg or "xref" in error_msg:
|
|
raise ExtractionError(
|
|
error_code="invalid_pdf", message="Invalid PDF file", details=str(e)
|
|
) from e
|
|
raise ExtractionError(
|
|
error_code="corrupt_pdf",
|
|
message="Failed to extract XML from PDF",
|
|
details=str(e),
|
|
) from e
|
|
|
|
# Fallback: If factur-x library didn't find XML, check attachments by MIME type
|
|
# This handles XRechnung and other XML attachments with non-standard filenames
|
|
if not xml_bytes:
|
|
xml_filename, xml_bytes = _find_xml_attachment_fallback(pdf_bytes)
|
|
|
|
if not 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)
|
|
|
|
return ExtractResponse(
|
|
is_zugferd=False,
|
|
pdf_text=pdf_text,
|
|
extraction_meta=ExtractionMeta(
|
|
pages=pages,
|
|
xml_attachment_name=None,
|
|
extraction_time_ms=extraction_time_ms,
|
|
),
|
|
)
|
|
|
|
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)
|
|
|
|
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=pdf_text,
|
|
extraction_meta=ExtractionMeta(
|
|
pages=pages,
|
|
xml_attachment_name=xml_filename or "factur-x.xml",
|
|
extraction_time_ms=extraction_time_ms,
|
|
),
|
|
)
|