docs: bring README and agent guides in line with the code
- 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>
This commit is contained in:
@@ -245,7 +245,9 @@ Four validation checks supported:
|
||||
1. **pflichtfelder** - Required fields present and non-empty
|
||||
2. **betraege** - Amount calculations correct (tolerance: 0.01)
|
||||
3. **ustid** - VAT ID format (DE, AT, CH)
|
||||
4. **pdf_abgleich** - XML vs PDF text comparison (currently only matches the English patterns `Invoice <nr>` and `Total:`; passes without comparing otherwise)
|
||||
4. **pdf_abgleich** - invoice number and net/VAT/gross totals of the XML must appear in the PDF text (`find_pdf_text_mismatches`; warnings only)
|
||||
|
||||
`ValidateRequest.profile` (the `zugferd_profil` from `/extract`) enables profile-specific rules; on `XRECHNUNG_*` the buyer reference (BT-10) is required.
|
||||
|
||||
## Environment Variables
|
||||
- `HOST` (default: `0.0.0.0`)
|
||||
@@ -257,7 +259,9 @@ Four validation checks supported:
|
||||
- No type suppression (`# type: ignore`) allowed
|
||||
- File size limit: 10MB for PDF and XML uploads
|
||||
- Parse untrusted XML only via `_parse_xml` in `src/extractor.py` (no entity/DTD resolution)
|
||||
- CI runs `uv sync --extra dev --frozen` and `uv run --extra dev pytest -q` (lockfile: factur-x 6.8; the Nix dev shell still packages factur-x 3.8)
|
||||
- CI runs `uv sync --extra dev --frozen` and `uv run --extra dev pytest -q`
|
||||
- `flake.nix` packages factur-x itself; keep its version in sync with `uv.lock` (both 6.8)
|
||||
- New files must be `git add`ed before `nix build` sees them (flake source = git tree)
|
||||
- Returns warnings (not errors) for non-critical issues
|
||||
- Uses Decimal rounding with ROUND_HALF_UP for monetary values
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Project Instructions for AI Agents
|
||||
|
||||
This file provides instructions and context for AI coding agents working on this project.
|
||||
Project conventions live in [AGENTS.md](AGENTS.md); this file only adds the issue-tracker integration.
|
||||
|
||||
<!-- BEGIN BEADS INTEGRATION v:1 profile:minimal hash:ca08a54f -->
|
||||
## Beads Issue Tracker
|
||||
@@ -49,21 +49,7 @@ bd close <id> # Complete work
|
||||
- If push fails, resolve and retry until it succeeds
|
||||
<!-- END BEADS INTEGRATION -->
|
||||
|
||||
## Project Guide
|
||||
|
||||
## Build & Test
|
||||
|
||||
_Add your build and test commands here_
|
||||
|
||||
```bash
|
||||
# Example:
|
||||
# npm install
|
||||
# npm test
|
||||
```
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
_Add a brief overview of your project architecture_
|
||||
|
||||
## Conventions & Patterns
|
||||
|
||||
_Add your project-specific conventions here_
|
||||
Commands, code style, file structure and validation rules are documented in
|
||||
[AGENTS.md](AGENTS.md). Read it before working on this repository.
|
||||
|
||||
@@ -1,15 +1,29 @@
|
||||
# ZUGFeRD-Service
|
||||
|
||||
A REST API service for extracting and validating ZUGFeRD/Factur-X invoice data from PDF files. Built with FastAPI and Python 3.11+.
|
||||
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 ZUGFeRD-enabled PDFs
|
||||
- Detect and identify ZUGFeRD profiles (MINIMUM, BASIC, BASIC WL, EN16931, EXTENDED)
|
||||
- Validate invoice data against business rules and regulatory requirements
|
||||
- Compare XML data against PDF text content
|
||||
- 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).
|
||||
|
||||
@@ -83,25 +97,40 @@ curl http://localhost:5000/health
|
||||
|
||||
### POST /extract
|
||||
|
||||
Extract ZUGFeRD data from a base64-encoded PDF file.
|
||||
Extract invoice data from a base64-encoded PDF or XML file.
|
||||
|
||||
**Request:**
|
||||
**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",
|
||||
@@ -118,7 +147,8 @@ Extract ZUGFeRD data from a base64-encoded PDF file.
|
||||
"postal_code": "54321",
|
||||
"city": "Hamburg",
|
||||
"country": "DE",
|
||||
"vat_id": "DE987654321"
|
||||
"vat_id": "DE987654321",
|
||||
"tax_number": null
|
||||
},
|
||||
"line_items": [
|
||||
{
|
||||
@@ -169,6 +199,7 @@ Extract ZUGFeRD data from a base64-encoded PDF file.
|
||||
{
|
||||
"is_zugferd": false,
|
||||
"zugferd_profil": null,
|
||||
"xml_syntax": null,
|
||||
"xml_raw": null,
|
||||
"xml_data": null,
|
||||
"pdf_text": "Regular PDF content...",
|
||||
@@ -188,6 +219,11 @@ 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
|
||||
@@ -235,11 +271,14 @@ Validate invoice data against business rules and regulatory requirements.
|
||||
},
|
||||
"currency": "EUR"
|
||||
},
|
||||
"pdf_text": "Invoice RE-2024-001\nTotal: 1190.00 EUR",
|
||||
"checks": ["pflichtfelder", "betraege", "ustid", "pdf_abgleich"]
|
||||
"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
|
||||
{
|
||||
@@ -277,8 +316,11 @@ The service supports four validation checks:
|
||||
|
||||
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, line_items array, line item fields
|
||||
- **Warnings:** due_date, payment_terms.iban
|
||||
- **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)
|
||||
|
||||
@@ -302,15 +344,18 @@ Validates VAT ID format for supported countries:
|
||||
|
||||
### 4. pdf_abgleich (PDF Comparison)
|
||||
|
||||
Compares XML data against extracted PDF text:
|
||||
Checks that the key values of the XML are also visible in the PDF, using the text passed in `pdf_text`:
|
||||
|
||||
- Invoice number exact match
|
||||
- Totals (net, gross, vat_total) within tolerance
|
||||
- Returns warnings (not errors) for mismatches
|
||||
- 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)
|
||||
|
||||
## ZUGFeRD Profiles
|
||||
Every value that appears nowhere in the PDF text is returned as a warning (`pdf_mismatch`), never as an error.
|
||||
|
||||
The service detects and reports the following ZUGFeRD 2.x profiles:
|
||||
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 |
|
||||
|---------|-------------|
|
||||
@@ -320,7 +365,14 @@ The service detects and reports the following ZUGFeRD 2.x profiles:
|
||||
| EN16931 | Full profile compliant with EN 16931 standard |
|
||||
| EXTENDED | Extended profile with additional optional fields |
|
||||
|
||||
The profile is automatically detected from the embedded XML metadata.
|
||||
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
|
||||
|
||||
@@ -332,7 +384,9 @@ The service supports the following environment variables:
|
||||
|----------|---------|-------------|
|
||||
| `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) |
|
||||
| `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
|
||||
|
||||
@@ -349,43 +403,29 @@ The flake provides:
|
||||
|
||||
- `packages.zugferd-service`: Production build
|
||||
- `devShells.default`: Development shell with all dependencies
|
||||
- `nixosModules.default`: NixOS module (see below)
|
||||
|
||||
## NixOS Deployment
|
||||
|
||||
Example NixOS module configuration:
|
||||
The flake ships a NixOS module (`nix/module.nix`). Add the flake as input and enable the service:
|
||||
|
||||
```nix
|
||||
{ config, pkgs, ... }:
|
||||
{ inputs, pkgs, ... }:
|
||||
|
||||
let
|
||||
zugferd-service = (import ./zugferd-service {}).packages.zugferd-service;
|
||||
in {
|
||||
systemd.services.zugferd-service = {
|
||||
{
|
||||
imports = [ inputs.zugferd-service.nixosModules.default ];
|
||||
|
||||
services.zugferd-service = {
|
||||
enable = true;
|
||||
description = "ZUGFeRD Invoice Service";
|
||||
after = [ "network.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
||||
serviceConfig = {
|
||||
ExecStart = "${zugferd-service}/bin/zugferd-service";
|
||||
Restart = "always";
|
||||
RestartSec = "10";
|
||||
DynamicUser = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
PrivateTmp = true;
|
||||
NoNewPrivileges = true;
|
||||
};
|
||||
|
||||
environment = {
|
||||
HOST = "127.0.0.1";
|
||||
PORT = "5000";
|
||||
LOG_LEVEL = "INFO";
|
||||
};
|
||||
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
|
||||
@@ -405,9 +445,18 @@ pytest
|
||||
pytest --cov=src
|
||||
|
||||
# Run specific test file
|
||||
pytest tests/test_extract.py
|
||||
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
|
||||
|
||||
```
|
||||
@@ -416,15 +465,24 @@ zugferd-service/
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py # FastAPI application and endpoints
|
||||
│ ├── models.py # Pydantic models for requests/responses
|
||||
│ ├── extractor.py # ZUGFeRD XML extraction logic
|
||||
│ ├── 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_extract.py
|
||||
│ ├── test_validate.py
|
||||
│ └── fixtures/ # Test PDF files
|
||||
│ ├── 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
|
||||
@@ -436,7 +494,7 @@ zugferd-service/
|
||||
- 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
|
||||
- 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
|
||||
|
||||
@@ -462,7 +520,7 @@ PORT=8000 python -m src.main
|
||||
|
||||
**Extraction returns "is_zugferd: false"**
|
||||
|
||||
- Verify the PDF contains ZUGFeRD/Factur-X XML attachment
|
||||
- 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)
|
||||
|
||||
@@ -474,7 +532,7 @@ Check that all required fields are present:
|
||||
- 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, quantity, and unit_price
|
||||
- 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**
|
||||
|
||||
@@ -495,29 +553,29 @@ DOCKER_BUILDKIT=1 docker build -t zugferd-service .
|
||||
| Error Code | Description |
|
||||
|------------|-------------|
|
||||
| `invalid_base64` | Invalid base64 encoding in request |
|
||||
| `file_too_large` | PDF exceeds 10MB limit |
|
||||
| `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` | Embedded XML is malformed |
|
||||
| `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
|
||||
|
||||
The service outputs structured JSON logs:
|
||||
Service modules log structured JSON at the level set by `LOG_LEVEL`:
|
||||
|
||||
```json
|
||||
{
|
||||
"timestamp": "2024-02-01T10:30:00Z",
|
||||
"level": "INFO",
|
||||
"message": "Extraction completed",
|
||||
"data": {
|
||||
"is_zugferd": true,
|
||||
"profile": "EN16931",
|
||||
"extraction_time_ms": 45
|
||||
}
|
||||
"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
|
||||
|
||||
Reference in New Issue
Block a user