- supported formats, xml_base64, xml_syntax, buyer_reference, profile - profile table, error codes and required-field rules match the code - pdf_abgleich and logging sections describe the actual behavior - NixOS section uses the shipped module instead of a hand-written unit - test files, CI commands, uv.lock and validator_schema.json listed - CLAUDE.md points to AGENTS.md instead of template placeholders Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
586 lines
17 KiB
Markdown
586 lines
17 KiB
Markdown
# ZUGFeRD-Service
|
||
|
||
A REST API service for extracting and validating e-invoices (ZUGFeRD/Factur-X, XRechnung, Peppol BIS Billing) from PDF and XML files. Built with FastAPI and Python 3.11+.
|
||
|
||
## Overview
|
||
|
||
ZUGFeRD-Service provides a simple HTTP API to:
|
||
|
||
- Extract structured invoice data from e-invoices: PDFs with embedded XML and plain XML files
|
||
- Detect the XML syntax (CII or UBL) and the invoice profile (ZUGFeRD profiles, XRechnung, Peppol BIS Billing)
|
||
- Validate invoice data with four plausibility checks (required fields, amounts, VAT ID format, PDF comparison)
|
||
|
||
The validation checks are plausibility checks of this service. They do not replace an official conformance validation against the EN 16931 / XRechnung schemas and Schematron rules (e.g. with the KoSIT validator).
|
||
|
||
### Supported formats
|
||
|
||
All formats of the European e-invoice standard EN 16931 are supported, in both XML syntaxes:
|
||
|
||
| Format | Syntax | Container |
|
||
|--------|--------|-----------|
|
||
| ZUGFeRD 2.x / Factur-X | CII | PDF with embedded XML |
|
||
| XRechnung | CII or UBL | plain XML, or embedded in a PDF |
|
||
| Peppol BIS Billing 3.0 | UBL | plain XML |
|
||
| Other EN 16931 invoices | CII or UBL | plain XML, or embedded in a PDF |
|
||
|
||
UBL covers both `Invoice` and `CreditNote` documents. Not supported: ZUGFeRD 1.0 (older namespace), and non-EN-16931 formats such as FatturaPA, ebInterface or EDIFACT.
|
||
|
||
ZUGFeRD (Zentraler User Guide der Forums Elektronische Rechnung Deutschland) is a German standard for electronic invoices, using the Cross Industry Invoice (CII) XML format embedded in PDF files (also known as Factur-X in France).
|
||
|
||
## Quick Start
|
||
|
||
### Docker
|
||
|
||
The quickest way to get started is using Docker:
|
||
|
||
```bash
|
||
# Build the image
|
||
docker build -t zugferd-service .
|
||
|
||
# Run the service
|
||
docker run -p 5000:5000 zugferd-service
|
||
|
||
# Or use Docker Compose
|
||
docker-compose up -d
|
||
```
|
||
|
||
### Nix
|
||
|
||
If you're using Nix, build and run with:
|
||
|
||
```bash
|
||
# Build the package
|
||
nix build .#zugferd-service
|
||
|
||
# Run the service
|
||
nix run .#zugferd-service
|
||
|
||
# Enter development shell
|
||
nix develop
|
||
```
|
||
|
||
### Python (Development)
|
||
|
||
For local development:
|
||
|
||
```bash
|
||
# Install dependencies
|
||
pip install -e .
|
||
|
||
# Run directly
|
||
python -m src.main
|
||
|
||
# Or use the installed script
|
||
zugferd-service
|
||
```
|
||
|
||
The service starts on `http://0.0.0.0:5000` by default.
|
||
|
||
## API Reference
|
||
|
||
### GET /health
|
||
|
||
Check if the service is running.
|
||
|
||
**Response:**
|
||
```json
|
||
{
|
||
"status": "healthy",
|
||
"version": "1.0.0"
|
||
}
|
||
```
|
||
|
||
**Example:**
|
||
```bash
|
||
curl http://localhost:5000/health
|
||
```
|
||
|
||
### POST /extract
|
||
|
||
Extract invoice data from a base64-encoded PDF or XML file.
|
||
|
||
**Request (PDF):**
|
||
```json
|
||
{
|
||
"pdf_base64": "JVBERi0xLjQKJeLjz9MK..."
|
||
}
|
||
```
|
||
|
||
**Request (plain XML, e.g. XRechnung):**
|
||
```json
|
||
{
|
||
"xml_base64": "PD94bWwgdmVyc2lvbj0iMS4wIi..."
|
||
}
|
||
```
|
||
|
||
Send exactly one of the two fields. The file type is detected from the content, so an XML file sent as `pdf_base64` works as well.
|
||
|
||
The response field `xml_syntax` tells which syntax was found (`"CII"` or `"UBL"`). `is_zugferd` is `true` whenever structured invoice data was found, regardless of format. For plain XML input, `pdf_text` is `null` and `extraction_meta.pages` is `0`.
|
||
|
||
`invoice_date` and `due_date` are always returned as `YYYY-MM-DD`, regardless of the source syntax. `buyer_reference` holds the buyer reference (BT-10), which is the Leitweg-ID on XRechnung invoices.
|
||
|
||
**Response (ZUGFeRD PDF):**
|
||
```json
|
||
{
|
||
"is_zugferd": true,
|
||
"zugferd_profil": "EN16931",
|
||
"xml_syntax": "CII",
|
||
"xml_raw": "<?xml version=\"1.0\"...?>",
|
||
"xml_data": {
|
||
"invoice_number": "RE-2024-001",
|
||
"invoice_date": "2024-02-01",
|
||
"due_date": "2024-02-28",
|
||
"buyer_reference": null,
|
||
"supplier": {
|
||
"name": "Acme Corp",
|
||
"street": "Main Street 123",
|
||
"postal_code": "12345",
|
||
"city": "Berlin",
|
||
"country": "DE",
|
||
"vat_id": "DE123456789",
|
||
"tax_number": null,
|
||
"email": "billing@acme-corp.de"
|
||
},
|
||
"buyer": {
|
||
"name": "Customer GmbH",
|
||
"street": "Market Square 5",
|
||
"postal_code": "54321",
|
||
"city": "Hamburg",
|
||
"country": "DE",
|
||
"vat_id": "DE987654321",
|
||
"tax_number": null
|
||
},
|
||
"line_items": [
|
||
{
|
||
"position": 1,
|
||
"article_number": "ART-001",
|
||
"article_number_buyer": null,
|
||
"description": "Consulting Services",
|
||
"quantity": 10.0,
|
||
"unit": "HUR",
|
||
"unit_price": 100.0,
|
||
"line_total": 1000.0,
|
||
"vat_rate": 19.0,
|
||
"vat_amount": 190.0
|
||
}
|
||
],
|
||
"totals": {
|
||
"line_total_sum": 1000.0,
|
||
"net": 1000.0,
|
||
"vat_total": 190.0,
|
||
"gross": 1190.0,
|
||
"vat_breakdown": [
|
||
{
|
||
"rate": 19.0,
|
||
"base": 1000.0,
|
||
"amount": 190.0
|
||
}
|
||
]
|
||
},
|
||
"currency": "EUR",
|
||
"payment_terms": {
|
||
"iban": "DE89370400440532013000",
|
||
"bic": "COBADEFFXXX",
|
||
"account_holder": "Acme Corp"
|
||
},
|
||
"notes": "Payment due within 30 days"
|
||
},
|
||
"pdf_text": "Invoice RE-2024-001\nAcme Corp...",
|
||
"extraction_meta": {
|
||
"pages": 2,
|
||
"xml_attachment_name": "factur-x.xml",
|
||
"extraction_time_ms": 45
|
||
}
|
||
}
|
||
```
|
||
|
||
**Response (Non-ZUGFeRD PDF):**
|
||
```json
|
||
{
|
||
"is_zugferd": false,
|
||
"zugferd_profil": null,
|
||
"xml_syntax": null,
|
||
"xml_raw": null,
|
||
"xml_data": null,
|
||
"pdf_text": "Regular PDF content...",
|
||
"extraction_meta": {
|
||
"pages": 1,
|
||
"xml_attachment_name": null,
|
||
"extraction_time_ms": 20
|
||
}
|
||
}
|
||
```
|
||
|
||
**Example:**
|
||
```bash
|
||
# Convert PDF to base64 and extract
|
||
PDF_BASE64=$(base64 -w 0 invoice.pdf)
|
||
|
||
curl -X POST http://localhost:5000/extract \
|
||
-H "Content-Type: application/json" \
|
||
-d "{\"pdf_base64\": \"$PDF_BASE64\"}"
|
||
|
||
# Plain XRechnung XML
|
||
curl -X POST http://localhost:5000/extract \
|
||
-H "Content-Type: application/json" \
|
||
-d "{\"xml_base64\": \"$(base64 -w 0 xrechnung.xml)\"}"
|
||
```
|
||
|
||
### POST /validate
|
||
|
||
Validate invoice data against business rules and regulatory requirements.
|
||
|
||
**Request:**
|
||
```json
|
||
{
|
||
"xml_data": {
|
||
"invoice_number": "RE-2024-001",
|
||
"invoice_date": "2024-02-01",
|
||
"due_date": "2024-02-28",
|
||
"supplier": {
|
||
"name": "Acme Corp",
|
||
"vat_id": "DE123456789"
|
||
},
|
||
"buyer": {
|
||
"name": "Customer GmbH",
|
||
"vat_id": "DE987654321"
|
||
},
|
||
"line_items": [
|
||
{
|
||
"position": 1,
|
||
"description": "Consulting Services",
|
||
"quantity": 10.0,
|
||
"unit": "HUR",
|
||
"unit_price": 100.0,
|
||
"line_total": 1000.0,
|
||
"vat_rate": 19.0
|
||
}
|
||
],
|
||
"totals": {
|
||
"line_total_sum": 1000.0,
|
||
"net": 1000.0,
|
||
"vat_total": 190.0,
|
||
"gross": 1190.0,
|
||
"vat_breakdown": [
|
||
{
|
||
"rate": 19.0,
|
||
"base": 1000.0,
|
||
"amount": 190.0
|
||
}
|
||
]
|
||
},
|
||
"currency": "EUR"
|
||
},
|
||
"pdf_text": "Invoice RE-2024-001\nNet 1000.00 VAT 190.00 Total: 1190.00 EUR",
|
||
"checks": ["pflichtfelder", "betraege", "ustid", "pdf_abgleich"],
|
||
"profile": "EN16931"
|
||
}
|
||
```
|
||
|
||
`profile` is optional. Pass the `zugferd_profil` value from `/extract` to enable profile-specific rules (currently: the mandatory buyer reference on XRechnung invoices).
|
||
|
||
**Response:**
|
||
```json
|
||
{
|
||
"result": {
|
||
"is_valid": true,
|
||
"errors": [],
|
||
"warnings": [],
|
||
"summary": {
|
||
"total_checks": 4,
|
||
"checks_passed": 4,
|
||
"checks_failed": 0,
|
||
"critical_errors": 0,
|
||
"warnings": 0
|
||
},
|
||
"validation_time_ms": 12
|
||
}
|
||
}
|
||
```
|
||
|
||
**Example:**
|
||
```bash
|
||
curl -X POST http://localhost:5000/validate \
|
||
-H "Content-Type: application/json" \
|
||
-d '{
|
||
"xml_data": {"invoice_number": "RE-001", ...},
|
||
"checks": ["pflichtfelder", "betraege"]
|
||
}'
|
||
```
|
||
|
||
## Validation Checks
|
||
|
||
The service supports four validation checks:
|
||
|
||
### 1. pflichtfelder (Required Fields)
|
||
|
||
Validates that all critical invoice fields are present and non-empty:
|
||
|
||
- **Critical errors:** invoice_number, invoice_date, supplier.name, supplier.vat_id (or supplier.tax_number), buyer.name, totals.net, totals.gross, totals.vat_total (each must be non-zero), line_items array, and per line item: description, quantity, unit_price, line_total
|
||
- **Critical on XRechnung only:** buyer_reference (BT-10, the Leitweg-ID), when `profile` is an `XRECHNUNG_*` profile
|
||
- **Warnings:** due_date or payment_terms.iban present but empty, line item without vat_rate
|
||
|
||
A line item quantity of 0 is accepted on text-only positions whose line total is 0 (e.g. a delivery note reference). It is an error only when the line bills an amount.
|
||
|
||
### 2. betraege (Amount Calculations)
|
||
|
||
Verifies all monetary calculations are correct:
|
||
|
||
- Line total = quantity × unit_price (for each line item)
|
||
- totals.net = sum of all line totals
|
||
- VAT breakdown amount = base × (rate/100) (for each VAT entry)
|
||
- totals.vat_total = sum of VAT breakdown amounts
|
||
- totals.gross = totals.net + totals.vat_total
|
||
|
||
Uses a tolerance of 0.01 for floating-point comparison.
|
||
|
||
### 3. ustid (VAT ID Format)
|
||
|
||
Validates VAT ID format for supported countries:
|
||
|
||
- **Germany (DE):** DE followed by 9 digits (e.g., `DE123456789`)
|
||
- **Austria (AT):** ATU followed by 8 digits (e.g., `ATU12345678`)
|
||
- **Switzerland (CH):** CHE followed by 9 digits and MWST/TVA/IVA suffix (e.g., `CHE123456789MWST`)
|
||
|
||
### 4. pdf_abgleich (PDF Comparison)
|
||
|
||
Checks that the key values of the XML are also visible in the PDF, using the text passed in `pdf_text`:
|
||
|
||
- Invoice number (whitespace and case are ignored)
|
||
- Net total, VAT total and gross total, in the usual notations (`1234.56`, `1234,56`, `1.234,56`, `1,234.56`, space or apostrophe as thousands separator)
|
||
|
||
Every value that appears nowhere in the PDF text is returned as a warning (`pdf_mismatch`), never as an error.
|
||
|
||
The check searches the whole text and does not locate labelled fields, because PDF text extraction loses the layout. It therefore detects values that are missing from the PDF, but not a value that is printed under the wrong label. It is skipped when `pdf_text` is empty, as with plain XML input or scanned PDFs without a text layer.
|
||
|
||
## Invoice Profiles
|
||
|
||
The detected profile is returned in `zugferd_profil`. ZUGFeRD 2.x / Factur-X profiles:
|
||
|
||
| Profile | Description |
|
||
|---------|-------------|
|
||
| MINIMUM | Minimal profile with basic invoice data |
|
||
| BASIC | Basic profile for simple B2B invoicing |
|
||
| BASIC WL | Basic profile with additional buyer data |
|
||
| EN16931 | Full profile compliant with EN 16931 standard |
|
||
| EXTENDED | Extended profile with additional optional fields |
|
||
|
||
Other profiles are derived from the specification identifier (BT-24) in the XML:
|
||
|
||
| Value | Meaning |
|
||
|-------|---------|
|
||
| `XRECHNUNG_<version>` | XRechnung, e.g. `XRECHNUNG_3.0` (CII or UBL) |
|
||
| `PEPPOL_BIS_BILLING_<version>` | Peppol BIS Billing, e.g. `PEPPOL_BIS_BILLING_3.0` |
|
||
| `EN16931` | Plain EN 16931 invoice in UBL syntax |
|
||
| `UNKNOWN` | No specification identifier found |
|
||
|
||
## Configuration
|
||
|
||
### Environment Variables
|
||
|
||
The service supports the following environment variables:
|
||
|
||
| Variable | Default | Description |
|
||
|----------|---------|-------------|
|
||
| `HOST` | `0.0.0.0` | Host address to bind to |
|
||
| `PORT` | `5000` | Port to listen on |
|
||
| `LOG_LEVEL` | `INFO` | Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL); invalid values fall back to INFO |
|
||
|
||
`HOST` and `PORT` apply when the service is started via `python -m src.main` or the `zugferd-service` script (also available as `--host` / `--port` arguments). The Docker image starts uvicorn directly on `0.0.0.0:5000`.
|
||
|
||
### Docker Compose
|
||
|
||
The provided `docker-compose.yml` includes:
|
||
|
||
- Port mapping: `5000:5000`
|
||
- Health check endpoint
|
||
- Read-only source mount for development
|
||
- Restart policy: `unless-stopped`
|
||
|
||
### Nix
|
||
|
||
The flake provides:
|
||
|
||
- `packages.zugferd-service`: Production build
|
||
- `devShells.default`: Development shell with all dependencies
|
||
- `nixosModules.default`: NixOS module (see below)
|
||
|
||
## NixOS Deployment
|
||
|
||
The flake ships a NixOS module (`nix/module.nix`). Add the flake as input and enable the service:
|
||
|
||
```nix
|
||
{ inputs, pkgs, ... }:
|
||
|
||
{
|
||
imports = [ inputs.zugferd-service.nixosModules.default ];
|
||
|
||
services.zugferd-service = {
|
||
enable = true;
|
||
host = "127.0.0.1"; # default
|
||
port = 5000; # default
|
||
package = inputs.zugferd-service.packages.${pkgs.system}.zugferd-service;
|
||
};
|
||
}
|
||
```
|
||
|
||
The module runs the service as a hardened systemd unit (`DynamicUser`, `ProtectSystem=strict`, `ProtectHome`, `NoNewPrivileges`). `package` defaults to `pkgs.zugferd-service`, which only exists if you provide it through an overlay — otherwise set it as shown.
|
||
|
||
For production, consider adding:
|
||
|
||
- Reverse proxy (nginx/caddy) with HTTPS
|
||
- Authentication middleware
|
||
- Rate limiting
|
||
- Logging aggregation
|
||
|
||
## Development
|
||
|
||
### Running Tests
|
||
|
||
```bash
|
||
# Run all tests
|
||
pytest
|
||
|
||
# Run with coverage
|
||
pytest --cov=src
|
||
|
||
# Run specific test file
|
||
pytest tests/test_extractor.py
|
||
```
|
||
|
||
CI (`.github/workflows/ci.yml`) runs the tests from the committed lockfile and builds the Docker image:
|
||
|
||
```bash
|
||
uv sync --extra dev --frozen
|
||
uv run --extra dev pytest -q
|
||
```
|
||
|
||
The test suite includes a regression sweep over all fixture invoices (`tests/test_fixture_sweep.py`) with an explicit catalogue of known gaps, and regression tests from anonymized real invoices (`tests/test_real_invoice_regressions.py`). See `tests/fixtures/MANIFEST.md` for the fixtures.
|
||
|
||
### Project Structure
|
||
|
||
```
|
||
zugferd-service/
|
||
├── src/
|
||
│ ├── __init__.py
|
||
│ ├── main.py # FastAPI application and endpoints
|
||
│ ├── models.py # Pydantic models for requests/responses
|
||
│ ├── extractor.py # File detection, CII/ZUGFeRD XML extraction
|
||
│ ├── ubl_parser.py # UBL invoice/credit note parsing
|
||
│ ├── validator.py # Invoice validation logic
|
||
│ ├── pdf_parser.py # PDF text extraction
|
||
│ └── utils.py # Utility functions
|
||
├── tests/
|
||
│ ├── test_api.py # API endpoints
|
||
│ ├── test_extractor.py # PDF/CII extraction
|
||
│ ├── test_xml_formats.py # Plain XML, UBL, credit notes
|
||
│ ├── test_validator.py # Validation checks
|
||
│ ├── test_fixture_sweep.py # Sweep over all fixture PDFs
|
||
│ ├── test_real_invoice_regressions.py # Anonymized real invoices
|
||
│ ├── test_integration.py, test_models.py, test_pdf_parser.py, test_utils.py
|
||
│ └── fixtures/ # Test PDFs and XML files (see MANIFEST.md)
|
||
├── nix/module.nix # NixOS module
|
||
├── validator_schema.json # JSON schema of the /validate request (for LLM/OCR pipelines)
|
||
├── pyproject.toml # Project metadata and dependencies
|
||
├── uv.lock # Locked dependency versions (used by CI)
|
||
├── Dockerfile # Multi-stage Docker build
|
||
├── docker-compose.yml # Docker Compose configuration
|
||
└── flake.nix # Nix flake for reproducible builds
|
||
```
|
||
|
||
### Dependencies
|
||
|
||
**Core:**
|
||
- fastapi>=0.109.0 - Web framework
|
||
- uvicorn>=0.27.0 - ASGI server
|
||
- pydantic>=2.5.0 - Data validation
|
||
- factur-x>=2.5 - ZUGFeRD/Factur-X library (lockfile pins 6.8)
|
||
- pypdf>=4.0.0 - PDF text extraction
|
||
- lxml>=5.0.0 - XML processing
|
||
|
||
**Development:**
|
||
- pytest>=8.0.0 - Testing framework
|
||
- pytest-asyncio>=0.23.0 - Async test support
|
||
- httpx>=0.27.0 - HTTP client for testing
|
||
|
||
## Troubleshooting
|
||
|
||
### Common Issues
|
||
|
||
**Service fails to start with "Address already in use"**
|
||
|
||
Change the port:
|
||
```bash
|
||
# Docker
|
||
docker run -p 8000:5000 zugferd-service
|
||
|
||
# Nix/Python
|
||
PORT=8000 python -m src.main
|
||
```
|
||
|
||
**Extraction returns "is_zugferd: false"**
|
||
|
||
- Verify the PDF contains an embedded invoice XML attachment
|
||
- Check that the file is not password-protected
|
||
- Ensure the file is a valid PDF (not corrupt)
|
||
|
||
**Validation fails with "missing_required" errors**
|
||
|
||
Check that all required fields are present:
|
||
- invoice_number
|
||
- invoice_date (YYYY-MM-DD format)
|
||
- supplier.name and supplier.vat_id (or supplier.tax_number — EN 16931 BR-CO-26 requires one of both)
|
||
- buyer.name
|
||
- Non-zero totals (net, gross, vat_total)
|
||
- At least one line item with description, unit_price and line_total; quantity may only be 0 when the line total is 0
|
||
|
||
**VAT ID validation fails**
|
||
|
||
Verify the VAT ID format:
|
||
- German: `DE` + 9 digits
|
||
- Austrian: `ATU` + 8 digits
|
||
- Swiss: `CHE` + 9 digits + `MWST`/`TVA`/`IVA`
|
||
|
||
**Docker build is slow**
|
||
|
||
Use BuildKit for faster builds:
|
||
```bash
|
||
DOCKER_BUILDKIT=1 docker build -t zugferd-service .
|
||
```
|
||
|
||
### Error Codes
|
||
|
||
| Error Code | Description |
|
||
|------------|-------------|
|
||
| `invalid_base64` | Invalid base64 encoding in request |
|
||
| `file_too_large` | File (PDF or XML) exceeds 10MB limit |
|
||
| `password_protected_pdf` | PDF is password-protected |
|
||
| `invalid_pdf` | File is not a valid PDF |
|
||
| `corrupt_pdf` | PDF file is corrupted or unreadable |
|
||
| `invalid_xml` | Plain XML input is not well-formed |
|
||
| `unsupported_xml_format` | XML is well-formed but not a CII or UBL invoice |
|
||
|
||
Extraction errors are returned with HTTP 400. A request without a file, or with both `pdf_base64` and `xml_base64`, is rejected with HTTP 422.
|
||
|
||
### Logs
|
||
|
||
Service modules log structured JSON at the level set by `LOG_LEVEL`:
|
||
|
||
```json
|
||
{
|
||
"timestamp": "2024-02-01T10:30:00Z",
|
||
"level": "ERROR",
|
||
"message": "Internal error: ..."
|
||
}
|
||
```
|
||
|
||
Currently only internal errors (HTTP 500) are logged at the default level; `DEBUG` adds details about how an embedded XML attachment was found. Requests are logged by uvicorn in its own format.
|
||
|
||
## License
|
||
|
||
MIT
|
||
|
||
## Support
|
||
|
||
For issues, questions, or contributions, please refer to the project repository.
|