Checking generated invoices in CI
If your software produces invoices, a template or code change can break them without anyone noticing. Validate a set of generated sample invoices on every build; the build fails when an invoice no longer passes the official rules.
ci-validate.sh
#!/usr/bin/env bash
# Validate every invoice in a folder (XML, ZUGFeRD PDF) and fail on errors — for CI pipelines that
# generate invoices. Usage: ci-validate.sh <folder> [rules-version]
# Needs EINV_KEY (a test key is enough) and optionally EINV_BASE. Exit code 1 when any file fails.
set -euo pipefail
dir="${1:?folder with invoices}"
rules="${2:-latest}"
base="${EINV_BASE:-https://einvoiceengine.com}"
failed=0
checked=0
while IFS= read -r -d '' f; do
case "$f" in *.pdf|*.PDF) ct="application/pdf" ;; *) ct="application/xml" ;; esac
out=$(curl -sS "$base/v1/invoices/validate?store=false&rules=$rules" \
-H "Authorization: Bearer $EINV_KEY" -H "Content-Type: $ct" --data-binary @"$f")
line=$(printf '%s' "$out" | node -e '
let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{
const r=JSON.parse(s);
if(r.error){console.log("ERROR "+r.error.code+" "+r.error.message);return}
const errs=r.findings.filter(f=>f.severity==="error").map(f=>f.ruleId+(f.location&&f.location.line?"@"+f.location.line:""));
console.log((r.status==="valid"?"OK ":"FAIL ")+r.status+" "+(r.detected.profile||r.detected.format||"")+(errs.length?" "+errs.join(","):""))
})')
echo "$line $f"
checked=$((checked + 1))
case "$line" in OK*) ;; *) failed=$((failed + 1)) ;; esac
done < <(find "$dir" -type f \( -iname '*.xml' -o -iname '*.pdf' \) -print0 | sort -z)
echo "$checked checked, $failed failed"
[ "$failed" -eq 0 ]
A test key is enough (sandbox documents are free within your plan's sandbox allowance). Pin the rule set with the second argument (2026-11) to keep builds reproducible; move to a new rule set deliberately when the changelog announces one.
Regression checks with a baseline
einv-ci.mjs (Node 18+, no dependencies) does the same and more: it compares every run with a baseline, so known problems do not block the build but anything that gets worse does.
einv-ci.mjs
#!/usr/bin/env node
// Compliance check for CI: validates every invoice in a folder with the official rules and
// reports regressions against a baseline. Node 18+, no dependencies.
//
// node einv-ci.mjs <folder> [options]
// --rules <version> rule set to validate with (default: latest; pin e.g. 2026-11)
// --baseline <file> known results; only NEW failures fail the build
// --update-baseline write the current results to the baseline file and pass
// --compare-rules <version> also validate with another rule set and report every file whose result changes
// --report <file> write all results as JSON
// --summary <file> write a Markdown summary (default: $GITHUB_STEP_SUMMARY when set)
// --fail-on <error|warning> what counts as a failure (default: error)
//
// node einv-ci.mjs --test-set <id> [--rules <version>] [--compare-rules <version>] [--report file] [--summary file]
// runs a test set stored in your account (dashboard → Test sets, or POST /v1/test-sets): every
// document is checked against its expected result and compared with the previous run
//
// Environment: EINV_KEY (a test key is enough), EINV_BASE (default https://einvoiceengine.com).
// Exit code 1 when a file fails (or, with a baseline, when a file got worse), 2 on usage errors.
import { appendFileSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { join, relative } from "node:path";
const args = process.argv.slice(2);
const opt = (name, def) => {
const i = args.indexOf(`--${name}`);
return i >= 0 ? args[i + 1] : def;
};
const flag = (name) => args.includes(`--${name}`);
const folder = args[0] && !args[0].startsWith("--") ? args[0] : undefined;
const base = (process.env.EINV_BASE ?? "https://einvoiceengine.com").replace(/\/$/, "");
const key = process.env.EINV_KEY;
const rules = opt("rules", "latest");
const compareRules = opt("compare-rules");
const baselineFile = opt("baseline");
const failOn = opt("fail-on", "error");
const testSet = opt("test-set");
if ((testSet ? !/^[0-9a-f-]{36}$/i.test(testSet) : !folder || !existsSync(folder)) || !key) {
console.error("usage: EINV_KEY=… node einv-ci.mjs <folder> [--rules 2026-11] [--baseline file] [--compare-rules latest] [--report file] [--summary file]");
console.error(" EINV_KEY=… node einv-ci.mjs --test-set <id> [--rules 2026-11] [--compare-rules latest] [--report file] [--summary file]");
process.exit(2);
}
if (testSet) process.exit(await runTestSet(testSet));
/** Runs a stored test set on the server; the server keeps the expectations and the run history. */
async function runTestSet(id) {
const headers = { authorization: `Bearer ${key}`, "content-type": "application/json" };
const idem = `einv-ci-${Date.now()}-${Math.random().toString(36).slice(2)}`;
let run;
for (let attempt = 0; ; attempt++) {
const r = await fetch(`${base}/v1/test-sets/${id}/runs`, {
method: "POST",
headers: { ...headers, "idempotency-key": idem },
body: JSON.stringify({ rules, ...(compareRules ? { compareRules } : {}) }),
});
if ((r.status === 429 || r.status >= 500) && attempt < 5) {
await sleep(Number(r.headers.get("retry-after") ?? 2 ** attempt) * 1000);
continue;
}
const j = await r.json().catch(() => ({}));
if (!r.ok) {
console.error(`error ${r.status} ${j.error?.code ?? ""}: ${j.error?.message ?? "request failed"}`);
return 2;
}
run = j;
break;
}
for (const d of run.results) {
const tag = d.outcome === "failed" ? "FAIL" : d.outcome === "passed" ? "OK " : "NEW ";
const extra = [d.missing.length ? `missing ${d.missing.join(",")}` : "", d.unexpected.length ? `unexpected ${d.unexpected.join(",")}` : "", d.diff.change !== "unchanged" ? d.diff.change.replace(/_/g, " ") : ""].filter(Boolean).join("; ");
console.log(`${tag} ${d.actual.status}${d.actual.rules.length ? " " + d.actual.rules.join(",") : ""} ${d.filename}${extra ? ` (${extra})` : ""}`);
}
const s = run.summary;
console.log(`${s.documents} documents, ${s.passed} passed, ${s.failed} failed${s.noExpectation ? `, ${s.noExpectation} without expectation` : ""}; since the previous run: ${s.diff.newFailures} with new failures, ${s.diff.fixed} fixed`);
const mdRes = await fetch(`${base}/v1/test-sets/${id}/runs/${run.id}?format=markdown`, { headers });
const md = mdRes.ok ? await mdRes.text() : `### E-invoice test set: ${run.passed ? "passed" : "failed"} (run ${run.id})`;
const summary = opt("summary", process.env.GITHUB_STEP_SUMMARY);
if (summary) (opt("summary") ? writeFileSync : appendFileSync)(summary, md + "\n");
const report = opt("report");
if (report) writeFileSync(report, JSON.stringify(run, null, 2) + "\n");
return run.passed ? 0 : 1;
}
function files(dir) {
return readdirSync(dir)
.flatMap((f) => {
const p = join(dir, f);
return statSync(p).isDirectory() ? files(p) : /\.(xml|pdf)$/i.test(f) ? [p] : [];
})
.sort();
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function validate(path, ruleSet) {
const body = readFileSync(path);
for (let attempt = 0; ; attempt++) {
const r = await fetch(`${base}/v1/invoices/validate?store=false&rules=${encodeURIComponent(ruleSet)}`, {
method: "POST",
headers: { authorization: `Bearer ${key}`, "content-type": /\.pdf$/i.test(path) ? "application/pdf" : "application/xml" },
body,
});
if (r.status === 429 && attempt < 5) {
await sleep(Number(r.headers.get("retry-after") ?? 2 ** attempt) * 1000);
continue;
}
const j = await r.json().catch(() => ({}));
if (j.error) return { status: "error", profile: "", errors: [`${j.error.code}`], warnings: [], message: j.error.message };
const ids = (sev) => [...new Set(j.findings.filter((f) => f.severity === sev).map((f) => f.ruleId + (f.location?.line ? `@${f.location.line}` : "")))];
return { status: j.status, profile: j.detected?.profile ?? j.detected?.format ?? "", errors: ids("error"), warnings: ids("warning"), ruleset: j.ruleset?.version };
}
}
async function all(list, ruleSet) {
const out = {};
let next = 0;
await Promise.all(
Array.from({ length: Math.min(4, list.length) }, async () => {
while (next < list.length) {
const f = list[next++];
out[relative(folder, f)] = await validate(f, ruleSet);
}
}),
);
return out;
}
const failing = (r) => r.status !== "valid" || (failOn === "warning" && r.warnings.length > 0);
const ruleIds = (r) => new Set([...r.errors, ...(failOn === "warning" ? r.warnings : [])].map((x) => x.split("@")[0]));
const list = files(folder);
const results = await all(list, rules);
const baseline = baselineFile && existsSync(baselineFile) && !flag("update-baseline") ? JSON.parse(readFileSync(baselineFile, "utf8")).results ?? {} : null;
const regressions = [];
for (const [file, r] of Object.entries(results)) {
if (!failing(r)) continue;
if (!baseline) regressions.push({ file, reason: r.errors.join(", ") || r.status });
else {
const was = baseline[file];
const known = was ? ruleIds(was) : new Set();
const fresh = [...ruleIds(r)].filter((id) => !known.has(id));
if (!was || !failing(was) || fresh.length) regressions.push({ file, reason: was ? `new: ${fresh.join(", ") || r.status}` : `new file: ${r.errors.join(", ") || r.status}` });
}
}
const fixed = baseline ? Object.entries(baseline).filter(([f, was]) => failing(was) && results[f] && !failing(results[f])).map(([f]) => f) : [];
let changes = [];
if (compareRules) {
const other = await all(list, compareRules);
changes = Object.keys(results)
.filter((f) => results[f].status !== other[f].status || results[f].errors.join() !== other[f].errors.join())
.map((f) => ({ file: f, [rules]: `${results[f].status} ${results[f].errors.join(", ")}`.trim(), [compareRules]: `${other[f].status} ${other[f].errors.join(", ")}`.trim() }));
}
for (const [file, r] of Object.entries(results)) console.log(`${failing(r) ? "FAIL" : "OK "} ${r.status} ${r.profile}${r.errors.length ? " " + r.errors.join(",") : ""} ${file}`);
const nFail = Object.values(results).filter(failing).length;
console.log(`${list.length} checked, ${nFail} failed${baseline ? `, ${regressions.length} new, ${fixed.length} fixed` : ""}`);
for (const c of changes) console.log(`rule set ${rules} → ${compareRules}: ${c.file}: ${c[rules]} → ${c[compareRules]}`);
const ruleset = Object.values(results).find((r) => r.ruleset)?.ruleset ?? rules;
const md = [
`### E-invoice compliance: ${regressions.length ? "❌" : "✅"} ${list.length} checked, ${nFail} failing${baseline ? `, ${regressions.length} new, ${fixed.length} fixed` : ""}`,
"",
`Rule set: \`${ruleset}\`${baseline ? ` · baseline: \`${baselineFile}\`` : ""}`,
"",
...(regressions.length ? ["| File | Problem |", "|---|---|", ...regressions.map((x) => `| \`${x.file}\` | ${x.reason} |`), ""] : []),
...(fixed.length ? [`Fixed since the baseline: ${fixed.map((f) => `\`${f}\``).join(", ")}`, ""] : []),
...(compareRules
? [`#### Rule set ${rules} → ${compareRules}`, "", changes.length ? ["| File | " + rules + " | " + compareRules + " |", "|---|---|---|", ...changes.map((c) => `| \`${c.file}\` | ${c[rules]} | ${c[compareRules]} |`)].join("\n") : "No file changes its result.", ""]
: []),
].join("\n");
const summary = opt("summary", process.env.GITHUB_STEP_SUMMARY);
if (summary) (opt("summary") ? writeFileSync : appendFileSync)(summary, md + "\n");
const report = opt("report");
if (report) writeFileSync(report, JSON.stringify({ rules: ruleset, checkedAt: new Date().toISOString(), results, regressions, fixed, ruleSetChanges: changes }, null, 2) + "\n");
if (flag("update-baseline") && baselineFile) {
writeFileSync(baselineFile, JSON.stringify({ rules: ruleset, results }, null, 2) + "\n");
console.log(`baseline written: ${baselineFile}`);
process.exit(0);
}
process.exit(regressions.length ? 1 : 0);
--update-baseline --baseline einv-baseline.jsonrecords today's results; commit the file.--baseline einv-baseline.jsonthen fails only on new failures: a file that passed before, a new file that fails, or a new rule id. Files that were fixed are listed.--compare-rules latest(with--rules 2026-11) validates with both rule sets and lists every file whose result would change — check this before you move to a new rule set.--report einv-report.jsonwrites all results;--summary(or$GITHUB_STEP_SUMMARY) writes a Markdown summary.
Create the key with the scopes ci and validate: calls made with a CI key are recorded as CI checks (shown in integration health, and priced as CI checks where a contract sets a CI price). Without a contract they count like any other validation (test keys within the sandbox allowance). The x-einv-client header no longer affects how a call is recorded.
Synthetic test invoices
To test how your own system handles e-invoices — import, validation, error display — you need documents for many cases. POST /v1/testdata with { "target": "xrechnung-ubl" } (or xrechnung-cii, en16931-ubl, en16931-cii, peppol-bis-billing, zugferd-facturx) returns a set of synthetic invoices:
- valid ones: standard rate, mixed rates, zero-rated, exempt, reverse charge, intra-community supply, export, discount and freight, 60 lines, credit note;
- invalid ones that break one known rule each: missing buyer reference (BR-DE-15), wrong amount due (BR-CO-16), wrong line total (BR-CO-10), invalid currency code, missing seller VAT ID, an outdated XRechnung version, cut-off XML.
Each case has filename, document, the expected result and the actual result of the official validation when it was generated, and matches — so the expectations are checked, not assumed. cases: ["reverse-charge", …] limits the set; GET /v1/testdata/cases lists them. Every document says in a note that it is synthetic and uses example.com addresses and test identifiers only. Generating test data is not billed.
Stored test sets
A baseline file lives in your repository. A test set lives in your account instead: a named collection of test invoices, each with the result it should have, and a history of runs. Use it when the documents are not produced by your build (customer samples, rejected invoices, edge cases collected over time) or when several pipelines should share one set.
- Create and fill a set in the dashboard under Test sets, or with
POST /v1/test-sets({ "name": "Templates" }) andPOST /v1/test-sets/{id}/documentswith either uploaded files —{ "documents": [{ "filename": "standard.xml", "document": "<Invoice…>", "expected": "valid" }] }— or synthetic ones from the generator above —{ "generate": { "target": "xrechnung-ubl", "cases": ["reverse-charge"] } }. Up to 100 documents per set and 50 sets per organization. - Expected outcome per document:
"valid", the list of rule ids expected to fail (["BR-DE-15"], short for{ "status": "invalid", "rules": ["BR-DE-15"] }),"unsupported", ornull(not set yet). A document passes when its status is the expected one and the failing rule ids are exactly the expected list;missingandunexpectedshow the difference.invalidwith an empty list accepts any failure. Generated documents get the official result at generation as their expectation. - Take the current result as the expectation in one step:
POST /v1/test-sets/{id}/expectations/accept(all documents of the latest run, ordocumentIds), or the "Accept results" button in the dashboard.PATCH /v1/test-sets/{id}/documents/{documentId}with{ "expected": … }sets one by hand. - Run with
POST /v1/test-sets/{id}/runs({ "rules": "2026-11", "compareRules": "latest" }, both optional). Each document gets its actual status, failing rule ids and findings,outcome(passed,failed,no_expectation) anddiffagainst the previous run of the set:new_failures(rule ids that fail now and did not before),fixed,changed,unchangedornew_document.passedis true when no document failed its expectation; documents without an expectation never fail a run.GET /v1/test-sets/{id}/runslists runs (the last 100 are kept),GET /v1/test-sets/{id}/runs/{runId}returns one, and?format=markdownthe same summary einv-ci writes. - From CI:
node einv-ci.mjs --test-set <id> [--rules 2026-11] [--compare-rules latest] [--report file] [--summary file]runs the set, prints one line per document and exits with 1 when a document fails its expectation. In the GitHub Action, settest-set: <id>instead offolder. The SDK haseinv.testSets.run(id)and the CLIeinv ci --test-set <id>.
Billing: a run validates each document once (twice with compareRules), exactly as if you sent the documents to POST /v1/invoices/validate with the same key: a CI key records them as CI checks, a test key uses the sandbox allowance, and documents the official validator could not check are not billed. Adding generated documents is not billed. Runs started in the dashboard are free, like checks there. Keys need the validate scope (CI keys have it).
Storage: documents in a test set are stored encrypted (AES-256-GCM), like stored invoices. They are kept until you remove them or delete the set — the retention period of your organization does not apply, because a test set exists to be run again. Runs keep the failing rule ids and finding messages, not the documents. "Delete all documents" in the settings deletes all test sets with their runs, and so does closing a partner customer account.
GitHub Actions
Copy einvoice-action.yml to .github/actions/einvoice/action.yml and einv-ci.mjs next to it. The action writes the summary to the job page and, on pull requests, as a comment.
name: e-invoices
on: [push, pull_request]
permissions:
contents: read
pull-requests: write
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Generate sample invoices
run: npm ci && npm run build-sample-invoices # your own step, writes to ./out/invoices
- uses: ./.github/actions/einvoice
with:
folder: out/invoices
rules: 2026-11
baseline: einv-baseline.json
env:
EINV_KEY: ${{ secrets.EINV_TEST_KEY }}
GitLab CI
validate-invoices:
image: node:22
script:
- ./scripts/build-sample-invoices.sh
- curl -fsSL https://einvoiceengine.com/docs-examples/einv-ci.mjs -o einv-ci.mjs
- node einv-ci.mjs out/invoices --rules 2026-11 --baseline einv-baseline.json --summary einv-summary.md
variables:
EINV_KEY: $EINV_TEST_KEY
artifacts:
when: always
paths: [einv-summary.md]
The shell script above prints per file OK or FAIL, the detected profile and the failing rule ids with line numbers, then a summary. The exit code is non-zero when any file fails.
E-Invoicing API