Verifica delle fatture generate in CI
Se il Suo software produce fatture, una modifica a un modello o al codice può comprometterle senza che nessuno se ne accorga. Validi un insieme di fatture di esempio generate a ogni build; la build fallisce quando una fattura non supera più le regole ufficiali.
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 ]
Basta una chiave di test (i documenti sandbox sono gratuiti entro la quota sandbox del Suo piano). Fissi il set di regole con il secondo argomento (2026-11) per mantenere le build riproducibili; passi a un nuovo set di regole in modo deliberato quando il changelog ne annuncia uno.
Verifiche di regressione con una baseline
einv-ci.mjs (Node 18+, senza dipendenze) fa lo stesso e anche di più: confronta ogni esecuzione con una baseline, in modo che i problemi noti non blocchino la build, mentre qualsiasi peggioramento sì.
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.jsonregistra i risultati attuali; esegua il commit del file.--baseline einv-baseline.jsonfa quindi fallire la build solo per i nuovi errori: un file che in precedenza superava la verifica, un nuovo file che non la supera o un nuovo id di regola. I file corretti vengono elencati.--compare-rules latest(con--rules 2026-11) valida con entrambi i set di regole ed elenca ogni file il cui risultato cambierebbe — lo verifichi prima di passare a un nuovo set di regole.--report einv-report.jsonscrive tutti i risultati;--summary(oppure$GITHUB_STEP_SUMMARY) scrive un riepilogo Markdown.
Crei la chiave con gli scope ci e validate: le chiamate effettuate con una chiave CI vengono registrate come verifiche CI (visibili nello stato delle integrazioni e tariffate come verifiche CI quando un contratto stabilisce un prezzo CI). Senza contratto vengono conteggiate come qualsiasi altra validazione (chiavi di test entro la quota sandbox). L'header x-einv-client non influisce più sul modo in cui una chiamata viene registrata.
Fatture di test sintetiche
Per verificare come il Suo sistema gestisce le fatture elettroniche — importazione, validazione, visualizzazione degli errori — servono documenti per molti casi. POST /v1/testdata con { "target": "xrechnung-ubl" } (oppure xrechnung-cii, en16931-ubl, en16931-cii, peppol-bis-billing, zugferd-facturx) restituisce un insieme di fatture sintetiche:
- valide: aliquota ordinaria, aliquote miste, aliquota zero, esente, inversione contabile, cessione intracomunitaria, esportazione, sconto e spese di trasporto, 60 righe, nota di credito;
- non valide, ciascuna delle quali viola una regola nota: riferimento dell'acquirente mancante (BR-DE-15), importo dovuto errato (BR-CO-16), totale di riga errato (BR-CO-10), codice valuta non valido, partita IVA del venditore mancante, una versione XRechnung obsoleta, XML troncato.
Ogni caso contiene filename, document, il risultato atteso expected e il risultato effettivo actual della validazione ufficiale al momento della generazione, e matches — così le aspettative sono verificate, non presunte. cases: ["reverse-charge", …] limita l'insieme; GET /v1/testdata/cases li elenca. Ogni documento indica in una nota di essere sintetico e usa solo indirizzi example.com e identificativi di test. La generazione dei dati di test non viene fatturata.
Set di test archiviati
Un file di baseline risiede nel Suo repository. Un set di test risiede invece nel Suo account: una raccolta con nome di fatture di test, ciascuna con il risultato che dovrebbe avere, e una cronologia delle esecuzioni. Lo usi quando i documenti non sono prodotti dalla Sua build (campioni dei clienti, fatture respinte, casi limite raccolti nel tempo) o quando più pipeline devono condividere un unico set.
- Creare e riempire un set nella dashboard in Set di test, oppure con
POST /v1/test-sets({ "name": "Templates" }) ePOST /v1/test-sets/{id}/documentscon file caricati —{ "documents": [{ "filename": "standard.xml", "document": "<Invoice…>", "expected": "valid" }] }— o con file sintetici del generatore descritto sopra —{ "generate": { "target": "xrechnung-ubl", "cases": ["reverse-charge"] } }. Fino a 100 documenti per set e 50 set per organizzazione. - Risultato atteso per documento:
"valid", l'elenco degli id di regola che devono risultare violati (["BR-DE-15"], forma breve di{ "status": "invalid", "rules": ["BR-DE-15"] }),"unsupported"oppurenull(non ancora impostato). Un documento supera la verifica quando il suo stato è quello atteso e gli id di regola violati corrispondono esattamente all'elenco atteso;missingeunexpectedmostrano la differenza.invalidcon un elenco vuoto accetta qualsiasi violazione. I documenti generati ricevono come aspettativa il risultato ufficiale al momento della generazione. - Adottare il risultato attuale come aspettativa in un solo passaggio:
POST /v1/test-sets/{id}/expectations/accept(tutti i documenti dell'ultima esecuzione, oppuredocumentIds), o il pulsante "Accetta i risultati" nella dashboard.PATCH /v1/test-sets/{id}/documents/{documentId}con{ "expected": … }ne imposta una a mano. - Eseguire con
POST /v1/test-sets/{id}/runs({ "rules": "2026-11", "compareRules": "latest" }, entrambi facoltativi). Ogni documento riceve il suo stato effettivo, gli id di regola violati e i rilievi,outcome(passed,failed,no_expectation) ediffrispetto all'esecuzione precedente del set:new_failures(id di regola violati ora e non prima),fixed,changed,unchangedonew_document.passedè true quando nessun documento ha mancato la propria aspettativa; i documenti senza aspettativa non fanno mai fallire un'esecuzione.GET /v1/test-sets/{id}/runselenca le esecuzioni (vengono conservate le ultime 100),GET /v1/test-sets/{id}/runs/{runId}ne restituisce una e?format=markdownlo stesso riepilogo che scrive einv-ci. - Dalla CI:
node einv-ci.mjs --test-set <id> [--rules 2026-11] [--compare-rules latest] [--report file] [--summary file]esegue il set, stampa una riga per documento ed esce con 1 quando un documento manca la propria aspettativa. Nella GitHub Action impostitest-set: <id>al posto difolder. L'SDK offreeinv.testSets.run(id)e la CLIeinv ci --test-set <id>.
Fatturazione: un'esecuzione valida ogni documento una volta (due con compareRules), esattamente come se inviasse i documenti a POST /v1/invoices/validate con la stessa chiave: una chiave CI li registra come verifiche CI, una chiave di test usa la quota sandbox, e i documenti che il validatore ufficiale non ha potuto verificare non vengono fatturati. L'aggiunta di documenti generati non viene fatturata. Le esecuzioni avviate nella dashboard sono gratuite, come le verifiche lì. Le chiavi richiedono lo scope validate (le chiavi CI lo hanno).
Archiviazione: i documenti di un set di test sono archiviati cifrati (AES-256-GCM), come le fatture archiviate. Vengono conservati finché non li rimuove o elimina il set — il periodo di conservazione della Sua organizzazione non si applica, perché un set di test esiste per essere eseguito di nuovo. Le esecuzioni conservano gli id di regola violati e i messaggi dei rilievi, non i documenti. "Elimina tutti i documenti" nelle impostazioni elimina tutti i set di test con le loro esecuzioni, così come la chiusura di un account cliente di un partner.
GitHub Actions
Copi einvoice-action.yml in .github/actions/einvoice/action.yml e einv-ci.mjs accanto a esso. L'action scrive il riepilogo nella pagina del job e, nelle pull request, come commento.
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]
Lo script shell sopra riportato stampa per ogni file OK o FAIL, il profilo rilevato e gli id delle regole non superate con i numeri di riga, quindi un riepilogo. Il codice di uscita è diverso da zero quando un file non supera la verifica.
E-Invoicing API