Skip to content

Sprawdzanie generowanych faktur w CI

Jeśli Twoje oprogramowanie tworzy faktury, zmiana szablonu lub kodu może je zepsuć, zanim ktokolwiek to zauważy. Waliduj zestaw wygenerowanych przykładowych faktur przy każdym buildzie; build kończy się niepowodzeniem, gdy faktura przestaje przechodzić oficjalne reguły.

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 ]

Wystarczy klucz testowy (dokumenty sandbox są bezpłatne w ramach limitu sandbox Twojego planu). Przypnij zestaw reguł drugim argumentem (2026-11), aby buildy były powtarzalne; przechodź na nowy zestaw reguł świadomie, gdy changelog go zapowie.

Kontrole regresji z plikiem bazowym

einv-ci.mjs (Node 18+, bez zależności) robi to samo i więcej: porównuje każde uruchomienie z plikiem bazowym, więc znane problemy nie blokują buildu, ale wszystko, co się pogorszy — tak.

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.json zapisuje dzisiejsze wyniki; zacommituj ten plik.
  • --baseline einv-baseline.json kończy się wtedy niepowodzeniem tylko przy nowych błędach: plik, który wcześniej przechodził, nowy plik, który nie przechodzi, lub nowy identyfikator reguły. Poprawione pliki są wymienione.
  • --compare-rules latest (z --rules 2026-11) waliduje oboma zestawami reguł i wymienia każdy plik, którego wynik by się zmienił — sprawdź to, zanim przejdziesz na nowy zestaw reguł.
  • --report einv-report.json zapisuje wszystkie wyniki; --summary (lub $GITHUB_STEP_SUMMARY) zapisuje podsumowanie w Markdown.

Utwórz klucz z zakresami ci i validate: wywołania wykonane kluczem CI są rejestrowane jako kontrole CI (widoczne w stanie integracji i rozliczane jako kontrole CI, jeśli umowa określa cenę CI). Bez umowy liczą się jak każda inna walidacja (klucze testowe w ramach limitu sandbox). Nagłówek x-einv-client nie ma już wpływu na to, jak wywołanie jest rejestrowane.

Syntetyczne faktury testowe

Aby sprawdzić, jak Twój własny system obsługuje e-faktury — import, walidację, wyświetlanie błędów — potrzebujesz dokumentów dla wielu przypadków. POST /v1/testdata z { "target": "xrechnung-ubl" } (lub xrechnung-cii, en16931-ubl, en16931-cii, peppol-bis-billing, zugferd-facturx) zwraca zestaw syntetycznych faktur:

  • poprawne: stawka podstawowa, stawki mieszane, stawka zerowa, zwolnienie, odwrotne obciążenie, dostawa wewnątrzwspólnotowa, eksport, rabat i fracht, 60 pozycji, faktura korygująca;
  • niepoprawne, z których każda narusza jedną znaną regułę: brak referencji nabywcy (BR-DE-15), błędna kwota do zapłaty (BR-CO-16), błędna suma pozycji (BR-CO-10), nieprawidłowy kod waluty, brak numeru VAT sprzedawcy, przestarzała wersja XRechnung, ucięty XML.

Każdy przypadek ma filename, document, oczekiwany wynik expected i rzeczywisty wynik actual oficjalnej walidacji z chwili wygenerowania oraz matches — oczekiwania są więc sprawdzone, a nie założone. cases: ["reverse-charge", …] ogranicza zestaw; GET /v1/testdata/cases wymienia przypadki. Każdy dokument zawiera notatkę, że jest syntetyczny, i używa wyłącznie adresów example.com oraz testowych identyfikatorów. Generowanie danych testowych nie jest rozliczane.

Zapisane zestawy testowe

Plik bazowy znajduje się w Twoim repozytorium. Zestaw testowy znajduje się natomiast na Twoim koncie: to nazwany zbiór faktur testowych, z których każda ma wynik, jaki powinna mieć, wraz z historią uruchomień. Używaj go, gdy dokumenty nie powstają w Twoim buildzie (próbki od klientów, odrzucone faktury, przypadki brzegowe zbierane z czasem) albo gdy kilka pipeline'ów ma korzystać z jednego zestawu.

  • Utwórz i wypełnij zestaw w panelu w sekcji Zestawy testowe albo za pomocą POST /v1/test-sets ({ "name": "Templates" }) i POST /v1/test-sets/{id}/documents z przesłanymi plikami — { "documents": [{ "filename": "standard.xml", "document": "<Invoice…>", "expected": "valid" }] } — lub z syntetycznymi z opisanego wyżej generatora — { "generate": { "target": "xrechnung-ubl", "cases": ["reverse-charge"] } }. Do 100 dokumentów w zestawie i 50 zestawów na organizację.
  • Oczekiwany wynik dla każdego dokumentu: "valid", lista identyfikatorów reguł, które powinny być niespełnione (["BR-DE-15"], skrót od { "status": "invalid", "rules": ["BR-DE-15"] }), "unsupported" lub null (jeszcze nieustawiony). Dokument przechodzi, gdy jego status jest oczekiwany, a identyfikatory niespełnionych reguł dokładnie odpowiadają oczekiwanej liście; missing i unexpected pokazują różnicę. invalid z pustą listą akceptuje dowolny błąd. Wygenerowane dokumenty otrzymują jako oczekiwanie oficjalny wynik z chwili wygenerowania.
  • Przyjmij bieżący wynik jako oczekiwanie w jednym kroku: POST /v1/test-sets/{id}/expectations/accept (wszystkie dokumenty ostatniego uruchomienia lub documentIds) albo przycisk „Zaakceptuj wyniki” w panelu. PATCH /v1/test-sets/{id}/documents/{documentId} z { "expected": … } ustawia jedno oczekiwanie ręcznie.
  • Uruchom za pomocą POST /v1/test-sets/{id}/runs ({ "rules": "2026-11", "compareRules": "latest" }, oba opcjonalne). Każdy dokument otrzymuje rzeczywisty status, identyfikatory niespełnionych reguł i znaleziska, outcome (passed, failed, no_expectation) oraz diff względem poprzedniego uruchomienia zestawu: new_failures (identyfikatory reguł, które są niespełnione teraz, a wcześniej nie były), fixed, changed, unchanged lub new_document. passed ma wartość true, gdy żaden dokument nie odbiegł od oczekiwania; dokumenty bez oczekiwania nigdy nie powodują niepowodzenia uruchomienia. GET /v1/test-sets/{id}/runs wymienia uruchomienia (przechowywanych jest ostatnie 100), GET /v1/test-sets/{id}/runs/{runId} zwraca jedno z nich, a ?format=markdown — to samo podsumowanie, które zapisuje einv-ci.
  • Z CI: node einv-ci.mjs --test-set <id> [--rules 2026-11] [--compare-rules latest] [--report file] [--summary file] uruchamia zestaw, wypisuje jeden wiersz na dokument i kończy się kodem 1, gdy któryś dokument odbiega od oczekiwania. W GitHub Action ustaw test-set: <id> zamiast folder. SDK ma einv.testSets.run(id), a CLI einv ci --test-set <id>.

Rozliczanie: uruchomienie waliduje każdy dokument raz (dwa razy z compareRules), dokładnie tak, jakby dokumenty zostały wysłane do POST /v1/invoices/validate tym samym kluczem: klucz CI zapisuje je jako kontrole CI, klucz testowy korzysta z limitu sandboxa, a dokumenty, których oficjalny walidator nie mógł sprawdzić, nie są rozliczane. Dodawanie wygenerowanych dokumentów nie jest rozliczane. Uruchomienia rozpoczęte w panelu są bezpłatne, tak jak kontrole w panelu. Klucze potrzebują zakresu validate (klucze CI go mają).

Przechowywanie: dokumenty w zestawie testowym są przechowywane w postaci zaszyfrowanej (AES-256-GCM), tak jak zapisane faktury. Są zachowywane, dopóki ich nie usuniesz lub nie usuniesz zestawu — okres przechowywania Twojej organizacji nie ma zastosowania, bo zestaw testowy istnieje po to, by uruchamiać go ponownie. Uruchomienia zachowują identyfikatory niespełnionych reguł i komunikaty znalezisk, a nie dokumenty. „Usuń wszystkie dokumenty” w ustawieniach usuwa wszystkie zestawy testowe wraz z ich uruchomieniami; tak samo działa zamknięcie konta klienta partnera.

GitHub Actions

Skopiuj einvoice-action.yml do .github/actions/einvoice/action.yml, a einv-ci.mjs obok niego. Akcja zapisuje podsumowanie na stronie joba, a w pull requestach — jako komentarz.

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]

Powyższy skrypt powłoki wypisuje dla każdego pliku OK lub FAIL, wykryty profil i identyfikatory niespełnionych reguł z numerami wierszy, a na końcu podsumowanie. Kod wyjścia jest niezerowy, gdy którykolwiek plik nie przejdzie.