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:
2026-11-11 18:32:46 +01:00
co-authored by Claude Fable 5.2
parent 6126a19bb7
commit 7aa4506dd7
8 changed files with 1229 additions and 42 deletions
+11
View File
@@ -29,6 +29,17 @@ invoice PDFs here.
|-----------|----------|------------|
| extended_fc_steuernummer_basisqty.xml | EXTENDED | FC-only tax registration ignored, unit price with basis quantity 100 misread, spaced VAT ID rejected, contact email dropped (2026-09) |
## Plain XML Invoices - `xml/`
Official KoSIT XRechnung test-suite business case 01.01a, the same invoice
in both syntaxes (source: https://github.com/itplr-kosit/xrechnung-testsuite,
Apache License 2.0).
| Filename | Profile | Syntax |
|-----------|----------|--------|
| xrechnung_01.01a_cii.xml | XRechnung 3.0 | CII |
| xrechnung_01.01a_ubl.xml | XRechnung 3.0 | UBL |
## Profile Coverage
- **MINIMUM**: Not covered (future addition)
+171
View File
@@ -0,0 +1,171 @@
<?xml version="1.0" encoding="UTF-8"?>
<rsm:CrossIndustryInvoice xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100"
xmlns:ram="urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100"
xmlns:qdt="urn:un:unece:uncefact:data:standard:QualifiedDataType:100"
xmlns:udt="urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100">
<rsm:ExchangedDocumentContext>
<ram:BusinessProcessSpecifiedDocumentContextParameter>
<ram:ID>urn:fdc:peppol.eu:2017:poacc:billing:01:1.0</ram:ID>
</ram:BusinessProcessSpecifiedDocumentContextParameter>
<ram:GuidelineSpecifiedDocumentContextParameter>
<ram:ID>urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0</ram:ID>
</ram:GuidelineSpecifiedDocumentContextParameter>
</rsm:ExchangedDocumentContext>
<rsm:ExchangedDocument>
<ram:ID>123456XX</ram:ID>
<ram:TypeCode>380</ram:TypeCode>
<ram:IssueDateTime>
<udt:DateTimeString format="102">20160404</udt:DateTimeString>
</ram:IssueDateTime>
<ram:IncludedNote>
<ram:Content>Es gelten unsere Allgem. Geschäftsbedingungen, die Sie unter […] finden.</ram:Content>
<ram:SubjectCode>ADU</ram:SubjectCode>
</ram:IncludedNote>
</rsm:ExchangedDocument>
<rsm:SupplyChainTradeTransaction>
<ram:IncludedSupplyChainTradeLineItem>
<ram:AssociatedDocumentLineDocument>
<ram:LineID>Zeitschrift [...]</ram:LineID>
<ram:IncludedNote>
<ram:Content>Die letzte Lieferung im Rahmen des abgerechneten Abonnements erfolgt in 12/2016 Lieferung erfolgt / erfolgte direkt vom Verlag</ram:Content>
</ram:IncludedNote>
</ram:AssociatedDocumentLineDocument>
<ram:SpecifiedTradeProduct>
<ram:SellerAssignedID>246</ram:SellerAssignedID>
<ram:Name>Zeitschrift [...]</ram:Name>
<ram:Description>Zeitschrift Inland</ram:Description>
<ram:DesignatedProductClassification>
<ram:ClassCode listID="IB">0721-880X</ram:ClassCode>
</ram:DesignatedProductClassification>
</ram:SpecifiedTradeProduct>
<ram:SpecifiedLineTradeAgreement>
<ram:BuyerOrderReferencedDocument>
<ram:LineID>6171175.1</ram:LineID>
</ram:BuyerOrderReferencedDocument>
<ram:NetPriceProductTradePrice>
<ram:ChargeAmount>288.79</ram:ChargeAmount>
</ram:NetPriceProductTradePrice>
</ram:SpecifiedLineTradeAgreement>
<ram:SpecifiedLineTradeDelivery>
<ram:BilledQuantity unitCode="XPP">1</ram:BilledQuantity>
</ram:SpecifiedLineTradeDelivery>
<ram:SpecifiedLineTradeSettlement>
<ram:ApplicableTradeTax>
<ram:TypeCode>VAT</ram:TypeCode>
<ram:CategoryCode>S</ram:CategoryCode>
<ram:RateApplicablePercent>7</ram:RateApplicablePercent>
</ram:ApplicableTradeTax>
<ram:BillingSpecifiedPeriod>
<ram:StartDateTime>
<udt:DateTimeString format="102">20160101</udt:DateTimeString>
</ram:StartDateTime>
<ram:EndDateTime>
<udt:DateTimeString format="102">20161231</udt:DateTimeString>
</ram:EndDateTime>
</ram:BillingSpecifiedPeriod>
<ram:SpecifiedTradeSettlementLineMonetarySummation>
<ram:LineTotalAmount>288.79</ram:LineTotalAmount>
</ram:SpecifiedTradeSettlementLineMonetarySummation>
</ram:SpecifiedLineTradeSettlement>
</ram:IncludedSupplyChainTradeLineItem>
<ram:IncludedSupplyChainTradeLineItem>
<ram:AssociatedDocumentLineDocument>
<ram:LineID>Porto + Versandkosten</ram:LineID>
</ram:AssociatedDocumentLineDocument>
<ram:SpecifiedTradeProduct>
<ram:Name>Porto + Versandkosten</ram:Name>
</ram:SpecifiedTradeProduct>
<ram:SpecifiedLineTradeAgreement>
<ram:NetPriceProductTradePrice>
<ram:ChargeAmount>26.07</ram:ChargeAmount>
</ram:NetPriceProductTradePrice>
</ram:SpecifiedLineTradeAgreement>
<ram:SpecifiedLineTradeDelivery>
<ram:BilledQuantity unitCode="XPP">1</ram:BilledQuantity>
</ram:SpecifiedLineTradeDelivery>
<ram:SpecifiedLineTradeSettlement>
<ram:ApplicableTradeTax>
<ram:TypeCode>VAT</ram:TypeCode>
<ram:CategoryCode>S</ram:CategoryCode>
<ram:RateApplicablePercent>7</ram:RateApplicablePercent>
</ram:ApplicableTradeTax>
<ram:SpecifiedTradeSettlementLineMonetarySummation>
<ram:LineTotalAmount>26.07</ram:LineTotalAmount>
</ram:SpecifiedTradeSettlementLineMonetarySummation>
</ram:SpecifiedLineTradeSettlement>
</ram:IncludedSupplyChainTradeLineItem>
<ram:ApplicableHeaderTradeAgreement>
<ram:BuyerReference>04011000-12345-03</ram:BuyerReference>
<ram:SellerTradeParty>
<ram:Name>[Seller name]</ram:Name>
<ram:Description>123/456/7890, HRA-Eintrag in […]</ram:Description>
<ram:SpecifiedLegalOrganization>
<ram:ID>[HRA-Eintrag]</ram:ID>
<ram:TradingBusinessName>[Seller trading name]</ram:TradingBusinessName>
</ram:SpecifiedLegalOrganization>
<ram:DefinedTradeContact>
<ram:PersonName>nicht vorhanden</ram:PersonName>
<ram:TelephoneUniversalCommunication>
<ram:CompleteNumber>+49 1234-5678</ram:CompleteNumber>
</ram:TelephoneUniversalCommunication>
<ram:EmailURIUniversalCommunication>
<ram:URIID>seller@email.de</ram:URIID>
</ram:EmailURIUniversalCommunication>
</ram:DefinedTradeContact>
<ram:PostalTradeAddress>
<ram:PostcodeCode>12345</ram:PostcodeCode>
<ram:LineOne>[Seller address line 1]</ram:LineOne>
<ram:CityName>[Seller city]</ram:CityName>
<ram:CountryID>DE</ram:CountryID>
</ram:PostalTradeAddress>
<ram:URIUniversalCommunication>
<ram:URIID schemeID="EM">seller@email.de</ram:URIID>
</ram:URIUniversalCommunication>
<ram:SpecifiedTaxRegistration>
<ram:ID schemeID="VA">DE 123456789</ram:ID>
</ram:SpecifiedTaxRegistration>
</ram:SellerTradeParty>
<ram:BuyerTradeParty>
<ram:ID>[Buyer identifier]</ram:ID>
<ram:Name>[Buyer name]</ram:Name>
<ram:PostalTradeAddress>
<ram:PostcodeCode>12345</ram:PostcodeCode>
<ram:LineOne>[Buyer address line 1]</ram:LineOne>
<ram:CityName>[Buyer city]</ram:CityName>
<ram:CountryID>DE</ram:CountryID>
</ram:PostalTradeAddress>
<ram:URIUniversalCommunication>
<ram:URIID schemeID="EM">buyer@info.de</ram:URIID>
</ram:URIUniversalCommunication>
</ram:BuyerTradeParty>
</ram:ApplicableHeaderTradeAgreement>
<ram:ApplicableHeaderTradeDelivery/>
<ram:ApplicableHeaderTradeSettlement>
<ram:InvoiceCurrencyCode>EUR</ram:InvoiceCurrencyCode>
<ram:SpecifiedTradeSettlementPaymentMeans>
<ram:TypeCode>58</ram:TypeCode>
<ram:PayeePartyCreditorFinancialAccount>
<!-- dies ist eine nicht existerende aber valide IBAN als test dummy -->
<ram:IBANID>DE79000000001234567890</ram:IBANID>
</ram:PayeePartyCreditorFinancialAccount>
</ram:SpecifiedTradeSettlementPaymentMeans>
<ram:ApplicableTradeTax>
<ram:CalculatedAmount>22.04</ram:CalculatedAmount>
<ram:TypeCode>VAT</ram:TypeCode>
<ram:BasisAmount>314.86</ram:BasisAmount>
<ram:CategoryCode>S</ram:CategoryCode>
<ram:RateApplicablePercent>7</ram:RateApplicablePercent>
</ram:ApplicableTradeTax>
<ram:SpecifiedTradePaymentTerms>
<ram:Description>Zahlbar sofort ohne Abzug.</ram:Description>
</ram:SpecifiedTradePaymentTerms>
<ram:SpecifiedTradeSettlementHeaderMonetarySummation>
<ram:LineTotalAmount>314.86</ram:LineTotalAmount>
<ram:TaxBasisTotalAmount>314.86</ram:TaxBasisTotalAmount>
<ram:TaxTotalAmount currencyID="EUR">22.04</ram:TaxTotalAmount>
<ram:GrandTotalAmount>336.9</ram:GrandTotalAmount>
<ram:DuePayableAmount>336.9</ram:DuePayableAmount>
</ram:SpecifiedTradeSettlementHeaderMonetarySummation>
</ram:ApplicableHeaderTradeSettlement>
</rsm:SupplyChainTradeTransaction>
</rsm:CrossIndustryInvoice>
+145
View File
@@ -0,0 +1,145 @@
<?xml version="1.0" encoding="UTF-8"?>
<ubl:Invoice xmlns:ubl="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">
<cbc:CustomizationID>urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0</cbc:CustomizationID>
<cbc:ProfileID>urn:fdc:peppol.eu:2017:poacc:billing:01:1.0</cbc:ProfileID>
<cbc:ID>123456XX</cbc:ID>
<cbc:IssueDate>2016-04-04</cbc:IssueDate>
<cbc:InvoiceTypeCode>380</cbc:InvoiceTypeCode>
<cbc:Note>#ADU#Es gelten unsere Allgem. Geschäftsbedingungen, die Sie unter […] finden.</cbc:Note>
<cbc:DocumentCurrencyCode>EUR</cbc:DocumentCurrencyCode>
<cbc:BuyerReference>04011000-12345-03</cbc:BuyerReference>
<cac:AccountingSupplierParty>
<cac:Party>
<cbc:EndpointID schemeID="EM">seller@email.de</cbc:EndpointID>
<cac:PartyName>
<cbc:Name>[Seller trading name]</cbc:Name>
</cac:PartyName>
<cac:PostalAddress>
<cbc:StreetName>[Seller address line 1]</cbc:StreetName>
<cbc:CityName>[Seller city]</cbc:CityName>
<cbc:PostalZone>12345</cbc:PostalZone>
<cac:Country>
<cbc:IdentificationCode>DE</cbc:IdentificationCode>
</cac:Country>
</cac:PostalAddress>
<cac:PartyTaxScheme>
<cbc:CompanyID>DE 123456789</cbc:CompanyID>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:PartyTaxScheme>
<cac:PartyLegalEntity>
<cbc:RegistrationName>[Seller name]</cbc:RegistrationName>
<cbc:CompanyID>[HRA-Eintrag]</cbc:CompanyID>
<cbc:CompanyLegalForm>123/456/7890, HRA-Eintrag in […]</cbc:CompanyLegalForm>
</cac:PartyLegalEntity>
<cac:Contact>
<cbc:Name>nicht vorhanden</cbc:Name>
<cbc:Telephone>+49 1234-5678</cbc:Telephone>
<cbc:ElectronicMail>seller@email.de</cbc:ElectronicMail>
</cac:Contact>
</cac:Party>
</cac:AccountingSupplierParty>
<cac:AccountingCustomerParty>
<cac:Party>
<cbc:EndpointID schemeID="EM">buyer@info.de</cbc:EndpointID>
<cac:PartyIdentification>
<cbc:ID>[Buyer identifier]</cbc:ID>
</cac:PartyIdentification>
<cac:PostalAddress>
<cbc:StreetName>[Buyer address line 1]</cbc:StreetName>
<cbc:CityName>[Buyer city]</cbc:CityName>
<cbc:PostalZone>12345</cbc:PostalZone>
<cac:Country>
<cbc:IdentificationCode>DE</cbc:IdentificationCode>
</cac:Country>
</cac:PostalAddress>
<cac:PartyLegalEntity>
<cbc:RegistrationName>[Buyer name]</cbc:RegistrationName>
</cac:PartyLegalEntity>
</cac:Party>
</cac:AccountingCustomerParty>
<cac:PaymentMeans>
<cbc:PaymentMeansCode>58</cbc:PaymentMeansCode>
<cac:PayeeFinancialAccount>
<!-- dies ist eine nicht existerende aber valide IBAN als test dummy -->
<cbc:ID>DE79000000001234567890</cbc:ID>
</cac:PayeeFinancialAccount>
</cac:PaymentMeans>
<cac:PaymentTerms>
<cbc:Note>Zahlbar sofort ohne Abzug.</cbc:Note>
</cac:PaymentTerms>
<cac:TaxTotal>
<cbc:TaxAmount currencyID="EUR">22.04</cbc:TaxAmount>
<cac:TaxSubtotal>
<cbc:TaxableAmount currencyID="EUR">314.86</cbc:TaxableAmount>
<cbc:TaxAmount currencyID="EUR">22.04</cbc:TaxAmount>
<cac:TaxCategory>
<cbc:ID>S</cbc:ID>
<cbc:Percent>7</cbc:Percent>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:TaxCategory>
</cac:TaxSubtotal>
</cac:TaxTotal>
<cac:LegalMonetaryTotal>
<cbc:LineExtensionAmount currencyID="EUR">314.86</cbc:LineExtensionAmount>
<cbc:TaxExclusiveAmount currencyID="EUR">314.86</cbc:TaxExclusiveAmount>
<cbc:TaxInclusiveAmount currencyID="EUR">336.9</cbc:TaxInclusiveAmount>
<cbc:PayableAmount currencyID="EUR">336.9</cbc:PayableAmount>
</cac:LegalMonetaryTotal>
<cac:InvoiceLine>
<cbc:ID>Zeitschrift [...]</cbc:ID>
<cbc:Note>Die letzte Lieferung im Rahmen des abgerechneten Abonnements erfolgt in 12/2016 Lieferung erfolgt / erfolgte direkt vom Verlag</cbc:Note>
<cbc:InvoicedQuantity unitCode="XPP">1</cbc:InvoicedQuantity>
<cbc:LineExtensionAmount currencyID="EUR">288.79</cbc:LineExtensionAmount>
<cac:InvoicePeriod>
<cbc:StartDate>2016-01-01</cbc:StartDate>
<cbc:EndDate>2016-12-31</cbc:EndDate>
</cac:InvoicePeriod>
<cac:OrderLineReference>
<cbc:LineID>6171175.1</cbc:LineID>
</cac:OrderLineReference>
<cac:Item>
<cbc:Description>Zeitschrift Inland</cbc:Description>
<cbc:Name>Zeitschrift [...]</cbc:Name>
<cac:SellersItemIdentification>
<cbc:ID>246</cbc:ID>
</cac:SellersItemIdentification>
<cac:CommodityClassification>
<cbc:ItemClassificationCode listID="IB">0721-880X</cbc:ItemClassificationCode>
</cac:CommodityClassification>
<cac:ClassifiedTaxCategory>
<cbc:ID>S</cbc:ID>
<cbc:Percent>7</cbc:Percent>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:ClassifiedTaxCategory>
</cac:Item>
<cac:Price>
<cbc:PriceAmount currencyID="EUR">288.79</cbc:PriceAmount>
</cac:Price>
</cac:InvoiceLine>
<cac:InvoiceLine>
<cbc:ID>Porto + Versandkosten</cbc:ID>
<cbc:InvoicedQuantity unitCode="XPP">1</cbc:InvoicedQuantity>
<cbc:LineExtensionAmount currencyID="EUR">26.07</cbc:LineExtensionAmount>
<cac:Item>
<cbc:Name>Porto + Versandkosten</cbc:Name>
<cac:ClassifiedTaxCategory>
<cbc:ID>S</cbc:ID>
<cbc:Percent>7</cbc:Percent>
<cac:TaxScheme>
<cbc:ID>VAT</cbc:ID>
</cac:TaxScheme>
</cac:ClassifiedTaxCategory>
</cac:Item>
<cac:Price>
<cbc:PriceAmount currencyID="EUR">26.07</cbc:PriceAmount>
</cac:Price>
</cac:InvoiceLine>
</ubl:Invoice>
+313
View File
@@ -0,0 +1,313 @@
"""Tests for plain-XML e-invoices and UBL syntax.
Fixtures in tests/fixtures/xml/ are official KoSIT XRechnung test-suite
business cases: the same invoice once in CII and once in UBL syntax.
"""
import base64
import re
from io import BytesIO
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from pypdf import PdfWriter
from src.extractor import (
ExtractionError,
extract_from_xml,
extract_invoice,
extract_zugferd,
)
from src.main import app
from src.models import ValidateRequest
from src.validator import validate_invoice
XML_FIXTURES = Path(__file__).parent / "fixtures" / "xml"
CII_XML = XML_FIXTURES / "xrechnung_01.01a_cii.xml"
UBL_XML = XML_FIXTURES / "xrechnung_01.01a_ubl.xml"
ALL_CHECKS = ["pflichtfelder", "betraege", "ustid", "pdf_abgleich"]
CREDIT_NOTE_XML = b"""<?xml version="1.0" encoding="UTF-8"?>
<CreditNote xmlns="urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2"
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">
<cbc:CustomizationID>urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0</cbc:CustomizationID>
<cbc:ID>GS-0815</cbc:ID>
<cbc:IssueDate>2026-03-01</cbc:IssueDate>
<cbc:CreditNoteTypeCode>381</cbc:CreditNoteTypeCode>
<cbc:DocumentCurrencyCode>EUR</cbc:DocumentCurrencyCode>
<cac:AccountingSupplierParty><cac:Party>
<cac:PartyName><cbc:Name>Beispiel Handel</cbc:Name></cac:PartyName>
<cac:PartyTaxScheme>
<cbc:CompanyID>123/456/78901</cbc:CompanyID>
<cac:TaxScheme><cbc:ID>FC</cbc:ID></cac:TaxScheme>
</cac:PartyTaxScheme>
</cac:Party></cac:AccountingSupplierParty>
<cac:AccountingCustomerParty><cac:Party>
<cac:PartyLegalEntity>
<cbc:RegistrationName>Muster Kunde GmbH</cbc:RegistrationName>
</cac:PartyLegalEntity>
</cac:Party></cac:AccountingCustomerParty>
<cac:PaymentMeans>
<cbc:PaymentMeansCode>58</cbc:PaymentMeansCode>
<cbc:PaymentDueDate>2026-03-15</cbc:PaymentDueDate>
</cac:PaymentMeans>
<cac:TaxTotal>
<cbc:TaxAmount currencyID="EUR">3.80</cbc:TaxAmount>
<cac:TaxSubtotal>
<cbc:TaxableAmount currencyID="EUR">20.00</cbc:TaxableAmount>
<cbc:TaxAmount currencyID="EUR">3.80</cbc:TaxAmount>
<cac:TaxCategory><cbc:ID>S</cbc:ID><cbc:Percent>19</cbc:Percent></cac:TaxCategory>
</cac:TaxSubtotal>
</cac:TaxTotal>
<cac:LegalMonetaryTotal>
<cbc:LineExtensionAmount currencyID="EUR">20.00</cbc:LineExtensionAmount>
<cbc:TaxExclusiveAmount currencyID="EUR">20.00</cbc:TaxExclusiveAmount>
<cbc:TaxInclusiveAmount currencyID="EUR">23.80</cbc:TaxInclusiveAmount>
<cbc:PayableAmount currencyID="EUR">23.80</cbc:PayableAmount>
</cac:LegalMonetaryTotal>
<cac:CreditNoteLine>
<cbc:ID>1</cbc:ID>
<cbc:CreditedQuantity unitCode="H87">200</cbc:CreditedQuantity>
<cbc:LineExtensionAmount currencyID="EUR">20.00</cbc:LineExtensionAmount>
<cac:Item>
<cbc:Name>Schrauben M6</cbc:Name>
<cac:BuyersItemIdentification><cbc:ID>K-77</cbc:ID></cac:BuyersItemIdentification>
<cac:ClassifiedTaxCategory><cbc:ID>S</cbc:ID><cbc:Percent>19</cbc:Percent></cac:ClassifiedTaxCategory>
</cac:Item>
<cac:Price>
<cbc:PriceAmount currencyID="EUR">10.00</cbc:PriceAmount>
<cbc:BaseQuantity unitCode="H87">100</cbc:BaseQuantity>
</cac:Price>
</cac:CreditNoteLine>
</CreditNote>
"""
@pytest.fixture
def client():
return TestClient(app)
def _validate(xml_data):
request = ValidateRequest(
xml_data=xml_data.model_dump(), pdf_text=None, checks=ALL_CHECKS
)
return validate_invoice(request)
class TestPlainXml:
"""Plain XML files (no PDF container) in both syntaxes."""
def test_cii_xml(self):
result = extract_invoice(CII_XML.read_bytes())
assert result.is_zugferd is True
assert result.xml_syntax == "CII"
assert result.zugferd_profil == "XRECHNUNG_3.0"
assert result.pdf_text is None
assert result.extraction_meta.pages == 0
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.totals.gross == pytest.approx(336.9)
def test_ubl_xml(self):
result = extract_invoice(UBL_XML.read_bytes())
assert result.is_zugferd is True
assert result.xml_syntax == "UBL"
assert result.zugferd_profil == "XRECHNUNG_3.0"
assert result.xml_raw.lstrip().startswith("<")
data = result.xml_data
assert data.invoice_number == "123456XX"
assert data.invoice_date == "2016-04-04"
assert data.currency == "EUR"
assert data.supplier.name == "[Seller name]"
assert data.supplier.vat_id == "DE 123456789"
assert data.supplier.postal_code == "12345"
assert data.supplier.country == "DE"
assert data.supplier.email == "seller@email.de"
assert data.buyer.name == "[Buyer name]"
assert data.payment_terms.iban == "DE79000000001234567890"
assert len(data.line_items) == 2
first = data.line_items[0]
assert first.article_number == "246"
assert first.quantity == 1
assert first.unit == "XPP"
assert first.unit_price == pytest.approx(288.79)
assert first.line_total == pytest.approx(288.79)
assert first.vat_rate == 7
assert data.totals.line_total_sum == pytest.approx(314.86)
assert data.totals.net == pytest.approx(314.86)
assert data.totals.vat_total == pytest.approx(22.04)
assert data.totals.gross == pytest.approx(336.9)
assert len(data.totals.vat_breakdown) == 1
assert data.totals.vat_breakdown[0].rate == 7
def test_ubl_and_cii_yield_same_invoice(self):
"""The same business case must parse identically from both syntaxes."""
cii = extract_invoice(CII_XML.read_bytes()).xml_data.model_dump()
ubl = extract_invoice(UBL_XML.read_bytes()).xml_data.model_dump()
# The note's subject-code prefix is carried differently by syntax
cii.pop("notes")
ubl.pop("notes")
assert ubl == cii
@pytest.mark.parametrize("path", [CII_XML, UBL_XML])
def test_validation_passes(self, path):
validation = _validate(extract_invoice(path.read_bytes()).xml_data)
assert validation.errors == []
assert validation.is_valid is True
def test_utf8_bom_is_accepted(self):
result = extract_invoice(b"\xef\xbb\xbf" + UBL_XML.read_bytes())
assert result.xml_syntax == "UBL"
assert not result.xml_raw.startswith("")
class TestUblCreditNote:
"""UBL CreditNote uses its own line and quantity element names."""
def test_credit_note(self):
result = extract_invoice(CREDIT_NOTE_XML)
assert result.xml_syntax == "UBL"
assert result.zugferd_profil == "PEPPOL_BIS_BILLING_3.0"
data = result.xml_data
assert data.invoice_number == "GS-0815"
assert data.due_date == "2026-03-15"
assert data.supplier.name == "Beispiel Handel"
assert data.supplier.vat_id is None
assert data.supplier.tax_number == "123/456/78901"
assert data.buyer.name == "Muster Kunde GmbH"
assert data.payment_terms is None
assert len(data.line_items) == 1
line = data.line_items[0]
assert line.article_number_buyer == "K-77"
assert line.quantity == 200
# Price 10.00 per base quantity 100
assert line.unit_price == pytest.approx(0.10)
assert line.line_total == pytest.approx(20.0)
def test_credit_note_validation_passes(self):
validation = _validate(extract_invoice(CREDIT_NOTE_XML).xml_data)
assert validation.errors == []
class TestUblInPdf:
"""A PDF may carry a UBL invoice as attachment."""
def test_ubl_attachment(self):
writer = PdfWriter()
writer.add_blank_page(width=72, height=72)
writer.add_attachment("xrechnung.xml", UBL_XML.read_bytes())
output = BytesIO()
writer.write(output)
result = extract_invoice(output.getvalue())
assert result.is_zugferd is True
assert result.xml_syntax == "UBL"
assert result.extraction_meta.xml_attachment_name == "xrechnung.xml"
assert result.extraction_meta.pages == 1
assert result.xml_data.invoice_number == "123456XX"
def test_xrechnung_pdf_reports_xrechnung_profile(self):
"""Must hold for every factur-x version (6.x maps it to EN16931)."""
pdf_bytes = Path("tests/fixtures/validXRechnung.pdf").read_bytes()
assert extract_invoice(pdf_bytes).zugferd_profil.startswith("XRECHNUNG_")
def test_zugferd_pdf_reports_cii(self):
pdf_bytes = Path("tests/fixtures/EN16931_Einfach.pdf").read_bytes()
result = extract_zugferd(pdf_bytes)
assert result.xml_syntax == "CII"
# CII dates (format 102, YYYYMMDD) are normalized to ISO notation
assert re.fullmatch(r"\d{4}-\d{2}-\d{2}", result.xml_data.invoice_date)
assert extract_invoice(pdf_bytes).zugferd_profil == "EN16931"
class TestXmlErrors:
"""Malformed, foreign and hostile XML."""
def test_malformed_xml(self):
with pytest.raises(ExtractionError) as exc_info:
extract_invoice(b"<?xml version='1.0'?><Invoice><unclosed>")
assert exc_info.value.error_code == "invalid_xml"
def test_foreign_xml(self):
with pytest.raises(ExtractionError) as exc_info:
extract_invoice(b"<html><body>no invoice</body></html>")
assert exc_info.value.error_code == "unsupported_xml_format"
def test_external_entities_are_not_resolved(self, tmp_path):
secret = tmp_path / "secret.txt"
secret.write_text("TOP-SECRET-CONTENT")
doctype = f'<!DOCTYPE x [<!ENTITY xxe SYSTEM "file://{secret}">]>'.encode()
xml = UBL_XML.read_bytes()
declaration_end = xml.index(b"?>") + 2
xml = xml[:declaration_end] + doctype + xml[declaration_end:]
xml = xml.replace(b"<cbc:ID>123456XX</cbc:ID>", b"<cbc:ID>&xxe;</cbc:ID>", 1)
result = extract_from_xml(xml)
assert "TOP-SECRET-CONTENT" not in result.model_dump_json()
def test_file_too_large(self):
with pytest.raises(ExtractionError) as exc_info:
extract_invoice(b"<a>" + b" " * (10 * 1024 * 1024) + b"</a>")
assert exc_info.value.error_code == "file_too_large"
class TestExtractEndpointXml:
"""POST /extract with plain XML."""
def test_xml_base64(self, client):
payload = {"xml_base64": base64.b64encode(UBL_XML.read_bytes()).decode()}
response = client.post("/extract", json=payload)
assert response.status_code == 200
data = response.json()
assert data["is_zugferd"] is True
assert data["xml_syntax"] == "UBL"
assert data["zugferd_profil"] == "XRECHNUNG_3.0"
assert data["xml_data"]["invoice_number"] == "123456XX"
def test_xml_in_pdf_field_is_detected(self, client):
"""Clients that only know pdf_base64 can send XML through it."""
payload = {"pdf_base64": base64.b64encode(CII_XML.read_bytes()).decode()}
response = client.post("/extract", json=payload)
assert response.status_code == 200
assert response.json()["xml_syntax"] == "CII"
def test_pdf_in_xml_field_is_rejected(self, client):
pdf_bytes = Path("tests/fixtures/EN16931_Einfach.pdf").read_bytes()
payload = {"xml_base64": base64.b64encode(pdf_bytes).decode()}
response = client.post("/extract", json=payload)
assert response.status_code == 400
assert response.json()["error"] == "invalid_xml"
def test_no_file(self, client):
assert client.post("/extract", json={}).status_code == 422
def test_both_files(self, client):
payload = {"pdf_base64": "QQ==", "xml_base64": "QQ=="}
assert client.post("/extract", json=payload).status_code == 422