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.
|
Extracts structured invoice data from EN 16931 e-invoices in both syntaxes:
|
||||||
Supports ZUGFeRD 2.x profiles: MINIMUM, BASIC, BASIC WL, EN16931, EXTENDED.
|
|
||||||
|
- 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 io
|
||||||
|
import re
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from facturx import get_flavor, get_level, get_xml_from_pdf
|
from facturx import get_flavor, get_level, get_xml_from_pdf
|
||||||
@@ -23,8 +29,16 @@ from src.models import (
|
|||||||
VatBreakdown,
|
VatBreakdown,
|
||||||
XmlData,
|
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 = {
|
NAMESPACES = {
|
||||||
"rsm": "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100",
|
"rsm": "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100",
|
||||||
"ram": "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100",
|
"ram": "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100",
|
||||||
@@ -42,6 +56,25 @@ class ExtractionError(Exception):
|
|||||||
super().__init__(message)
|
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:
|
def extract_text_from_pdf(pdf_bytes: bytes) -> str:
|
||||||
"""Extract text from PDF using pypdf.
|
"""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:
|
def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
|
||||||
"""Parse ZUGFeRD XML bytes to structured XmlData.
|
"""Parse ZUGFeRD XML bytes to structured XmlData.
|
||||||
|
|
||||||
@@ -377,7 +426,7 @@ def parse_zugferd_xml(xml_bytes: bytes) -> XmlData:
|
|||||||
Returns:
|
Returns:
|
||||||
XmlData model with all invoice fields
|
XmlData model with all invoice fields
|
||||||
"""
|
"""
|
||||||
xml_root = etree.fromstring(xml_bytes)
|
xml_root = _parse_xml(xml_bytes)
|
||||||
|
|
||||||
invoice_number = xml_root.xpath(
|
invoice_number = xml_root.xpath(
|
||||||
"//rsm:ExchangedDocument/ram:ID/text()", namespaces=NAMESPACES
|
"//rsm:ExchangedDocument/ram:ID/text()", namespaces=NAMESPACES
|
||||||
@@ -403,7 +452,7 @@ 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=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=due_date[0] if due_date else None,
|
||||||
supplier=parse_supplier(xml_root),
|
supplier=parse_supplier(xml_root),
|
||||||
buyer=parse_buyer(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()):
|
if subtype and ("xml" in str(subtype).lower() or "xml" in att.name.lower()):
|
||||||
try:
|
try:
|
||||||
etree.fromstring(att.content)
|
_parse_xml(att.content)
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Found XML attachment via MIME fallback: %s",
|
"Found XML attachment via MIME fallback: %s",
|
||||||
att.name,
|
att.name,
|
||||||
@@ -494,7 +543,7 @@ def _find_xml_attachment_fallback(pdf_bytes: bytes) -> tuple[str | None, bytes |
|
|||||||
continue
|
continue
|
||||||
if att.name.lower().endswith(".xml"):
|
if att.name.lower().endswith(".xml"):
|
||||||
try:
|
try:
|
||||||
etree.fromstring(att.content)
|
_parse_xml(att.content)
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Found XML attachment via extension fallback: %s",
|
"Found XML attachment via extension fallback: %s",
|
||||||
att.name,
|
att.name,
|
||||||
@@ -527,8 +576,188 @@ def _profile_from_urn(urn: str) -> str:
|
|||||||
return urn.rsplit("#", maxsplit=1)[-1].rsplit(":", maxsplit=1)[-1]
|
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:
|
def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
||||||
"""Extract ZUGFeRD data from PDF bytes.
|
"""Extract e-invoice data from PDF bytes.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
pdf_bytes: Raw PDF file content as bytes
|
pdf_bytes: Raw PDF file content as bytes
|
||||||
@@ -540,17 +769,10 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
|||||||
ExtractionError: For PDF processing errors
|
ExtractionError: For PDF processing errors
|
||||||
"""
|
"""
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
_check_file_size(pdf_bytes)
|
||||||
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",
|
|
||||||
)
|
|
||||||
|
|
||||||
xml_filename = None
|
xml_filename = None
|
||||||
xml_bytes = None
|
xml_bytes = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
xml_filename, xml_bytes = get_xml_from_pdf(pdf_bytes, check_xsd=False)
|
xml_filename, xml_bytes = get_xml_from_pdf(pdf_bytes, check_xsd=False)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -591,22 +813,7 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
xml_root = etree.fromstring(xml_bytes)
|
syntax, level, xml_data = _interpret_invoice_xml(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)
|
|
||||||
pdf_text = extract_text_from_pdf(pdf_bytes)
|
pdf_text = extract_text_from_pdf(pdf_bytes)
|
||||||
pages = get_pdf_page_count(pdf_bytes)
|
pages = get_pdf_page_count(pdf_bytes)
|
||||||
extraction_time_ms = int((time.time() - start_time) * 1000)
|
extraction_time_ms = int((time.time() - start_time) * 1000)
|
||||||
@@ -614,7 +821,8 @@ def extract_zugferd(pdf_bytes: bytes) -> ExtractResponse:
|
|||||||
return ExtractResponse(
|
return ExtractResponse(
|
||||||
is_zugferd=True,
|
is_zugferd=True,
|
||||||
zugferd_profil=level.upper(),
|
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,
|
xml_data=xml_data,
|
||||||
pdf_text=pdf_text,
|
pdf_text=pdf_text,
|
||||||
extraction_meta=ExtractionMeta(
|
extraction_meta=ExtractionMeta(
|
||||||
|
|||||||
+7
-5
@@ -12,7 +12,7 @@ from fastapi import FastAPI, HTTPException, Request
|
|||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import JSONResponse
|
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 (
|
from src.models import (
|
||||||
ExtractRequest,
|
ExtractRequest,
|
||||||
ExtractResponse,
|
ExtractResponse,
|
||||||
@@ -113,23 +113,25 @@ async def health_check() -> HealthResponse:
|
|||||||
|
|
||||||
@app.post("/extract", response_model=ExtractResponse)
|
@app.post("/extract", response_model=ExtractResponse)
|
||||||
async def extract_pdf(request: ExtractRequest) -> 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:
|
Args:
|
||||||
request: ExtractRequest with pdf_base64 field
|
request: ExtractRequest with pdf_base64 or xml_base64 field
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
ExtractResponse with extraction results
|
ExtractResponse with extraction results
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
pdf_bytes = base64.b64decode(request.pdf_base64)
|
file_bytes = base64.b64decode(request.xml_base64 or request.pdf_base64 or "")
|
||||||
except Exception:
|
except Exception:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400,
|
status_code=400,
|
||||||
detail={"error": "invalid_base64", "message": "Invalid base64 encoding"},
|
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)
|
@app.post("/validate", response_model=ValidateResponse)
|
||||||
|
|||||||
+23
-4
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field, model_validator
|
||||||
|
|
||||||
|
|
||||||
class ExtractionMeta(BaseModel):
|
class ExtractionMeta(BaseModel):
|
||||||
@@ -111,15 +111,34 @@ class XmlData(BaseModel):
|
|||||||
class ExtractRequest(BaseModel):
|
class ExtractRequest(BaseModel):
|
||||||
"""Request body for /extract endpoint."""
|
"""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):
|
class ExtractResponse(BaseModel):
|
||||||
"""Response from /extract endpoint."""
|
"""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(
|
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_raw: str | None = Field(default=None, description="Raw XML string")
|
||||||
xml_data: XmlData | None = Field(default=None, description="Parsed XML data")
|
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"),
|
||||||
|
)
|
||||||
Vendored
+11
@@ -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) |
|
| 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
|
## Profile Coverage
|
||||||
|
|
||||||
- **MINIMUM**: Not covered (future addition)
|
- **MINIMUM**: Not covered (future addition)
|
||||||
|
|||||||
+171
@@ -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
@@ -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>
|
||||||
@@ -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
|
||||||
Reference in New Issue
Block a user