Since 1 September 2026, every company in France has to be able to receive electronic invoices. Large companies and mid-size ones (ETI) must also issue them from that date. Small and medium businesses and micro-companies follow on 1 September 2027, always through an approved platform. I build Nolvi, an AGPL app for freelancers and agencies, and its invoices needed to be valid Factur-X files. Here is how that part works, and where it hurt.
Why a second language
Nolvi is TypeScript end to end, except one directory: services/facturx/, a FastAPI service outside the pnpm workspace. The reason is practical. The factur-x library (Akretion) and WeasyPrint, which can write PDF/A-3b directly, are Python. Using them means a second runtime and a second Docker image.
A Factur-X file is a PDF/A-3 whose attachment is a structured invoice. The FNFE-MPE page lists five profiles (MINIMUM, BASIC WL, BASIC, EN 16931, EXTENDED) and says Factur-X is technically the same standard as ZUGFeRD. I target EN 16931 only, and the test suite asserts that the XMP says EN 16931 and never one of the others. The embedded XML is CII, the UN/CEFACT syntax.
The contract: no arithmetic in Python
The NestJS side computes every amount once, with decimal.js, freezes it in a snapshot at issue time, and sends strings. The Python side never adds anything, and a test parses cii.py to check that it contains no money arithmetic. The Pydantic model types money as a string with a regex:
Money = Annotated[str, StringConstraints(strict=True, pattern=r"^-?\d+\.\d{2}$")] cii.py copies those strings into business terms: the per-rate base into BT-116, the HT total into BT-109, and so on. If the totals are wrong, the service does not repair them, it fails. A service that quietly recomputes can end up with an XML that disagrees with the PDF the customer reads.
The tricky part is rounding. EN 16931 wants the sum of line totals to equal the HT total (rule BR-CO-10), and with several VAT rates and fractional unit prices, rounding each line on its own drifts by a cent. The fix is on the TypeScript side: each line receives the difference between two rounded running totals per rate group.
const exact = group.exact.plus(new Decimal(l.unitPrice).mul(new Decimal(l.quantity))); const rounded = exact.toDecimalPlaces(MONEY_SCALE, Decimal.ROUND_HALF_UP); groups.set(key, { exact, rounded }); return rounded.minus(group.rounded).toFixed(MONEY_SCALE); Every line stays within a cent of its exact product and each group sums to its base. I found this out the hard way: an early version froze HT at 16.67 while the bases summed to 16.66.
The pipeline
build_facturx runs three steps: build the CII, render the base PDF, embed.
- The base PDF comes from WeasyPrint 69 with
pdf_variant="pdf/a-3b"and no attachment. A Ghostscript fallback exists behindFACTURX_BASE_ENGINE=ghostscript, in case WeasyPrint output ever fails the validator. - The schematron runs on the XML before anything is embedded.
-
factur-x7.10 embeds the XML:
facturx_pdf = generate_from_binary( base_pdfa, cii_xml, flavor="factur-x", level="en16931", afrelationship="Alternative", check_xsd=True, check_schematron=False, ) The library defaults to Data for the relationship, so Alternative is explicit.
The schematron that the library stopped running
check_schematron=False is deliberate. As the comment in schematron.py explains, from factur-x 6 on the library posts the XML to an external Saxon HTTP server, and when none answers it logs a warning and carries on. A green build could mean the business rules never ran. So I run the XSLT schematron files shipped inside the package myself, in process, with saxonche, and the gate fails closed: a Saxon error, a timeout, an empty report, or a report where no rule fired all raise.
if root.tag != f"{{{SVRL_NAMESPACE}}}schematron-output" or root.find(f".//{{{SVRL_NAMESPACE}}}fired-rule") is None: raise SchematronError(f"Schematron '{check_type}' returned a report in which no rule fired") Threading cost me the most time. SaxonC aborts the whole process when it is entered from a thread that did not initialise it, and FastAPI runs the build in a thread pool. All Saxon work therefore goes through one dedicated single-thread executor, and every Saxon object is created and released inside one call. A test fires eight calls from four threads at it. The service has to stay a single uvicorn process for this to hold.
What CI checks, and what runs in production
A GitHub Actions job builds the Docker image (WeasyPrint libraries, Ghostscript, a Temurin 17 JRE, veraPDF 1.26.2 with a pinned SHA-256) and runs the whole pytest suite inside it. Debian's own OpenJDK crashed the veraPDF installer, hence Temurin.
The suite generates 17 fixture documents (deposit invoices, final invoices after a deposit, credit notes, public-sector and foreign buyers) plus four VAT regime fixtures. For each file, the tests check that:
-
verapdf -f 3breports the file compliant; - the XML extracted back from the PDF passes the EN 16931 schematron;
- the XMP declares
EN 16931.
The documents with a French buyer also go through the French CTC schematron.
None of this runs on a customer's invoice. At runtime the service runs the XSD check and the base schematron, and nothing else. veraPDF never sees a real invoice: it is a CI check on fixtures, like the French CTC rules. So a template regression would show up in CI, not in the service.
The XMP was the other pain point. After the bump to factur-x 7.10, veraPDF rejected the metadata: rdf:Description lacked rdf:about="", and rdf:RDF carried no attribute at all, the namespace being declared only on its parent. embed.py now rewrites the XMP packet with pypdf and lxml, and raises if the packet does not have the shape it expects. It is a workaround for a specific library version, which is pinned in pyproject.toml for that reason.
Numbering
Invoices are numbered FA-2026-0001, credit notes AV-2026-0001, one counter per organisation, year and series. The number is allocated when the invoice moves from draft to issued, never at draft time, inside the same transaction:
await tx.$executeRaw`INSERT INTO "InvoiceCounter" ("id", "orgId", "year", "series", "last") VALUES (gen_random_uuid(), ${orgId}, ${year}, ${series}::"InvoiceSeries", 0) ON CONFLICT ("orgId", "year", "series") DO NOTHING`; const rows = await tx.$queryRaw<{ last: number }[]>`SELECT "last" FROM "InvoiceCounter" WHERE "orgId" = ${orgId} AND "year" = ${year} AND "series" = ${series}::"InvoiceSeries" FOR UPDATE`; I chose a row lock over a Postgres SEQUENCE because nextval never rolls back, so a failed issue would leave a hole. One spec issues ten numbers in parallel and expects exactly 1 to 10. Another rolls a transaction back and expects the next call to return the same number. A gap-free chronological series is a requirement of my own design here; I did not cite the legal text, so check the rule with your accountant before relying on it.
The orgId in those raw queries is written out by hand, because the tenant wrapper does not scope raw SQL. Forgetting it would lock another tenant's counter.
Failure handling
The service is best effort. NestJS calls it after the issue transaction has committed, with a 10 second default timeout, so a timeout can never cancel a legally allocated number. A failure sets facturxStatus to FAILED with a fixed or local message, never the service's raw response. Regeneration replays the frozen snapshot, so it fixes outages, not bad data.
The code is at https://github.com/nolvihq/nolvi