# FacturForge: Factur-X and CII Invoice Generator (`savagnic/facturforge`) Actor

Generate deterministic Factur-X UN/CEFACT CII invoice XML from structured JSON, optionally embedded in a PDF carrier, with bounded EN 16931 checks. No submission or filing.

- **URL**: https://apify.com/savagnic/facturforge.md
- **Developed by:** [NICHOLAS SAVAGE](https://apify.com/savagnic) (community)
- **Categories:**
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## FacturForge — Factur-X / UN-CEFACT CII invoice generator

Give it structured invoice JSON. It gives you a **byte-reproducible Factur-X
(UN/CEFACT CII) XML document**, optionally embedded in a **PDF carrier**, plus a
machine-readable **EN 16931 rule report** that cites the rule behind every
finding.

The same invoice and profile always produce the same XML bytes: element order
follows the XSD sequence, the VAT breakdown is sorted by (category, rate), and
amounts are computed in fixed-point at scale 2. Pin `pdfTimestamp` and the PDF
is byte-identical too, because the document `/ID` is derived from the XML digest
instead of being generated randomly.

### What it does

| Mode | What you give it | What you get |
|---|---|---|
| generate (default) | an `invoice` object, a `profile` | CII XML as a downloadable record, its digest and byte count, and the rule report |
| generate with `emitPdf` | the same, plus `emitPdf: true` | the above plus a PDF with the XML embedded |
| `validateOnly` | an `invoice` object | the rule report only; no document is produced |

Set `failOn` to decide which findings make the run exit non-zero. The document
and the report are stored either way, so a "failed" run is still readable.

### Input

Full contract in `input_schema.json`. Unknown fields are **rejected**, not
ignored — including anything that looks like a URL, because this Actor performs
no network requests of its own.

| Field | Type | Default | Notes |
|---|---|---|---|
| `invoice` | object | – | required; the invoice payload, supplied inline |
| `profile` | `MINIMUM` | `BASIC_WL` | `BASIC` | `EN16931` | `EXTENDED` | `EN16931` | MINIMUM and BASIC WL are not standalone EN 16931 invoices |
| `emitPdf` | boolean | `false` | also write the PDF carrier; cannot be combined with `validateOnly` |
| `validateOnly` | boolean | `false` | rule check only, no document |
| `businessProcessId` | string | – | BT-23 business process type written into the document context |
| `pdfTimestamp` | string (ISO 8601) | – | pins PDF timestamps for byte-reproducible output |
| `failOn` | `error` | `warning` | `never` | `error` | which findings make the run exit `1` |

### Output

One `facturforge/actor-result/1` object per run, written **identically** to the
default dataset and to the `OUTPUT` key-value record, on success and on failure
alike. The shape is described in `dataset_schema.json` and `output_schema.json`;
a real local run's output is in [`sample-output.json`](./sample-output.json),
produced by

```bash
npm ci && npm run build
mkdir -p storage/key_value_stores/default
## the bundled EN 16931 fixture as the `invoice` field
node products/facturforge/dist/actor/main.js
```

so you can reproduce it apart from the timestamp and the duration.

The generated document is **not** inlined into that JSON. It is stored as its
own key-value record, so you can download it as a file:

| Record | Written when |
|---|---|
| `invoice.xml` | a document was generated |
| `invoice.pdf` | `emitPdf` was set and the carrier was produced |

Exit codes:

| Code | Meaning |
|---|---|
| `0` | ran, result stored, `failOn` policy not tripped |
| `1` | findings at or above the `failOn` threshold (the document and report are still stored) |
| `2` | input missing, invalid, or containing an unknown field |
| `3` | runtime or storage failure |

### Pricing

Pay per event, two events, charged once per run:

| Event | Price | Charged when |
|---|---|---|
| `invoice-document` | **$0.02** | once, after a generated document and its report have been written to both the dataset and `OUTPUT` |
| `invoice-validation` | **$0.01** | once, after a `validateOnly` report has been written to both the dataset and `OUTPUT` |

Nothing else is billable. In particular you are **not** charged for:

- a rejected or invalid input (exit `2`),
- a runtime failure (exit `3`),
- a run whose `failOn` gate tripped (exit `1`) — findings are news you asked
  for, and that run is a failed run,
- a run whose result could not be stored,
- a start, a retry or a resurrect.

The charge is issued once per run, with an idempotency key, only after the
result is durably stored, and the run's exit code never depends on whether the
billing call succeeded. Your maximum cost per run is respected before any charge
is sent.

Those two prices are what this repository's code, tests and ledger agree on.
Whether they are what a published listing charges depends on the Apify Console
configuration, which is not part of this repository.

### Security

- **No network egress.** The run performs no outbound requests except to the
  Apify platform API that stores the result and issues the charge. There is no
  input field naming a URL, host or proxy, and unknown fields are rejected, so
  there is no user-influenced destination and no SSRF surface.
- **No credentials.** No input field is a secret, because the Actor has nothing
  to authenticate to. The platform token it receives is used only for storage
  and charging, and never appears in the dataset, the `OUTPUT` record, an
  artefact or a log line.
- **Hostile XML is expected.** The CII reader used by the internal round-trip
  check rejects DTDs and entity declarations outright (XXE and billion-laughs).
- Input size, JSON depth and line count are capped, and the run executes as an
  unprivileged user in the container.

### Boundaries

- **Not a submission platform.** It transmits nothing. Not a PDP (*plateforme de
  dématérialisation partenaire*), not a PA/PPF connector, not a Peppol access
  point, not a Chorus Pro client, no e-reporting. Producing a file here creates
  no legal filing of any kind.
- **Not a full validator.** It implements a documented *subset* of EN 16931
  business rules — presence rules BR-02..BR-16, arithmetic rules BR-CO-10/13/14
  /15/16 and BR-CO-25, VAT-category rules BR-S-05/09, BR-Z-05/09, BR-E-10,
  BR-AE-03 and BR-CO-26, plus Factur-X profile constraints. It does **not** run
  UN/CEFACT D16B XSD validation, the complete CEN Schematron rule set, or any
  national CIUS. The exact machine-readable scope travels in every result as
  `validationScope`.
- **PDF/A-3 conformance is not asserted.** The structural pieces are written —
  the embedded file with `/AFRelationship /Alternative`, the catalog `/AF`
  array, and XMP carrying `pdfaid:part=3` plus the Factur-X extension schema —
  and the result reports `pdfaConformanceAsserted: false`. A synthesized visual
  page uses non-embedded standard-14 fonts, which are not PDF/A conformant.
  Verify any produced PDF with [veraPDF](https://verapdf.org/).
- **Not tax advice.** VAT treatment is taken from the input exactly as given.
- Not affiliated with or endorsed by FNFE-MPE, CEN, or any tax administration.

### Licence

Apache-2.0.

# Actor input Schema

## `invoice` (type: `object`):

The structured invoice payload. Supplied inline: there is no URL field, because this Actor performs no network requests of its own.

## `profile` (type: `string`):

MINIMUM and BASIC WL are not standalone EN 16931 invoices.

## `emitPdf` (type: `boolean`):

Embeds the XML in a PDF. PDF/A-3 conformance is NOT asserted; verify the file with veraPDF before relying on it. Cannot be combined with validateOnly.

## `validateOnly` (type: `boolean`):

Run the bounded EN 16931 rule check and produce a report without emitting any document.

## `businessProcessId` (type: `string`):

Optional BT-23 business process type, written into the CII document context.

## `pdfTimestamp` (type: `string`):

Optional ISO 8601 instant used for PDF timestamps, so the same input produces the same bytes.

## `failOn` (type: `string`):

Which findings make the run exit non-zero. The document and the report are stored either way.

## Actor input object example

```json
{
  "invoice": {
    "id": "FF-2026-0042",
    "typeCode": "380",
    "issueDate": "2026-03-14",
    "dueDate": "2026-04-13",
    "currency": "EUR",
    "buyerReference": "SERVEXEC-2026",
    "purchaseOrderReference": "PO-91177",
    "deliveryDate": "2026-03-12",
    "paymentTerms": "Net 30 days from invoice date.",
    "payeeIban": "FR7630006000011234567890189",
    "notes": [
      {
        "content": "Services delivered under framework agreement FA-2025-11.",
        "subjectCode": "AAI"
      }
    ],
    "seller": {
      "name": "Atelier Numerique SARL",
      "vatId": "FR40303265045",
      "legalRegistrationId": "30326504500011",
      "address": {
        "line1": "12 rue de la Fonderie",
        "postcode": "31000",
        "city": "Toulouse",
        "countryCode": "FR"
      },
      "contact": {
        "name": "Claire Moreau",
        "email": "billing@atelier-numerique.example",
        "phone": "+33 5 61 00 00 00"
      }
    },
    "buyer": {
      "name": "Nordwind Logistik GmbH",
      "vatId": "DE811907980",
      "address": {
        "line1": "Speicherstrasse 8",
        "postcode": "20457",
        "city": "Hamburg",
        "countryCode": "DE"
      }
    },
    "lines": [
      {
        "id": "1",
        "name": "Integration engineering",
        "description": "API integration sprint, 3 weeks",
        "sellerAssignedId": "SVC-INT",
        "quantity": "112.5",
        "unitCode": "HUR",
        "netPrice": "95.00",
        "vat": {
          "categoryCode": "S",
          "ratePercent": "20.00"
        }
      }
    ]
  },
  "profile": "EN16931",
  "emitPdf": false,
  "validateOnly": false,
  "failOn": "error"
}
```

# Actor output Schema

## `result` (type: `string`):

The single result as a dataset item: the input echo, the library envelope with the validation findings, and references to the stored artefacts.

## `outputRecord` (type: `string`):

The identical result in the default key-value store under the OUTPUT key.

## `invoiceXml` (type: `string`):

The generated UN/CEFACT CII document. Absent on a validate-only run and on a failed run.

## `invoicePdf` (type: `string`):

The PDF with the CII XML embedded, written only when emitPdf was set. PDF/A-3 conformance is not asserted.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "invoice": {
        "id": "FF-2026-0042",
        "typeCode": "380",
        "issueDate": "2026-03-14",
        "dueDate": "2026-04-13",
        "currency": "EUR",
        "buyerReference": "SERVEXEC-2026",
        "purchaseOrderReference": "PO-91177",
        "deliveryDate": "2026-03-12",
        "paymentTerms": "Net 30 days from invoice date.",
        "payeeIban": "FR7630006000011234567890189",
        "notes": [
            {
                "content": "Services delivered under framework agreement FA-2025-11.",
                "subjectCode": "AAI"
            }
        ],
        "seller": {
            "name": "Atelier Numerique SARL",
            "vatId": "FR40303265045",
            "legalRegistrationId": "30326504500011",
            "address": {
                "line1": "12 rue de la Fonderie",
                "postcode": "31000",
                "city": "Toulouse",
                "countryCode": "FR"
            },
            "contact": {
                "name": "Claire Moreau",
                "email": "billing@atelier-numerique.example",
                "phone": "+33 5 61 00 00 00"
            }
        },
        "buyer": {
            "name": "Nordwind Logistik GmbH",
            "vatId": "DE811907980",
            "address": {
                "line1": "Speicherstrasse 8",
                "postcode": "20457",
                "city": "Hamburg",
                "countryCode": "DE"
            }
        },
        "lines": [
            {
                "id": "1",
                "name": "Integration engineering",
                "description": "API integration sprint, 3 weeks",
                "sellerAssignedId": "SVC-INT",
                "quantity": "112.5",
                "unitCode": "HUR",
                "netPrice": "95.00",
                "vat": {
                    "categoryCode": "S",
                    "ratePercent": "20.00"
                }
            }
        ]
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("savagnic/facturforge").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "invoice": {
        "id": "FF-2026-0042",
        "typeCode": "380",
        "issueDate": "2026-03-14",
        "dueDate": "2026-04-13",
        "currency": "EUR",
        "buyerReference": "SERVEXEC-2026",
        "purchaseOrderReference": "PO-91177",
        "deliveryDate": "2026-03-12",
        "paymentTerms": "Net 30 days from invoice date.",
        "payeeIban": "FR7630006000011234567890189",
        "notes": [{
                "content": "Services delivered under framework agreement FA-2025-11.",
                "subjectCode": "AAI",
            }],
        "seller": {
            "name": "Atelier Numerique SARL",
            "vatId": "FR40303265045",
            "legalRegistrationId": "30326504500011",
            "address": {
                "line1": "12 rue de la Fonderie",
                "postcode": "31000",
                "city": "Toulouse",
                "countryCode": "FR",
            },
            "contact": {
                "name": "Claire Moreau",
                "email": "billing@atelier-numerique.example",
                "phone": "+33 5 61 00 00 00",
            },
        },
        "buyer": {
            "name": "Nordwind Logistik GmbH",
            "vatId": "DE811907980",
            "address": {
                "line1": "Speicherstrasse 8",
                "postcode": "20457",
                "city": "Hamburg",
                "countryCode": "DE",
            },
        },
        "lines": [{
                "id": "1",
                "name": "Integration engineering",
                "description": "API integration sprint, 3 weeks",
                "sellerAssignedId": "SVC-INT",
                "quantity": "112.5",
                "unitCode": "HUR",
                "netPrice": "95.00",
                "vat": {
                    "categoryCode": "S",
                    "ratePercent": "20.00",
                },
            }],
    } }

# Run the Actor and wait for it to finish
run = client.actor("savagnic/facturforge").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "invoice": {
    "id": "FF-2026-0042",
    "typeCode": "380",
    "issueDate": "2026-03-14",
    "dueDate": "2026-04-13",
    "currency": "EUR",
    "buyerReference": "SERVEXEC-2026",
    "purchaseOrderReference": "PO-91177",
    "deliveryDate": "2026-03-12",
    "paymentTerms": "Net 30 days from invoice date.",
    "payeeIban": "FR7630006000011234567890189",
    "notes": [
      {
        "content": "Services delivered under framework agreement FA-2025-11.",
        "subjectCode": "AAI"
      }
    ],
    "seller": {
      "name": "Atelier Numerique SARL",
      "vatId": "FR40303265045",
      "legalRegistrationId": "30326504500011",
      "address": {
        "line1": "12 rue de la Fonderie",
        "postcode": "31000",
        "city": "Toulouse",
        "countryCode": "FR"
      },
      "contact": {
        "name": "Claire Moreau",
        "email": "billing@atelier-numerique.example",
        "phone": "+33 5 61 00 00 00"
      }
    },
    "buyer": {
      "name": "Nordwind Logistik GmbH",
      "vatId": "DE811907980",
      "address": {
        "line1": "Speicherstrasse 8",
        "postcode": "20457",
        "city": "Hamburg",
        "countryCode": "DE"
      }
    },
    "lines": [
      {
        "id": "1",
        "name": "Integration engineering",
        "description": "API integration sprint, 3 weeks",
        "sellerAssignedId": "SVC-INT",
        "quantity": "112.5",
        "unitCode": "HUR",
        "netPrice": "95.00",
        "vat": {
          "categoryCode": "S",
          "ratePercent": "20.00"
        }
      }
    ]
  }
}' |
apify call savagnic/facturforge --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,savagnic/facturforge"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/0NyDK4SoDk2QotaFH/builds/rxIc9f7HT4cVgvFbL/openapi.json
