// Turn a legacy export (CSV, Excel .xlsx or custom XML) into validated e-invoices (Node 20+). // Usage: tsx import-export.ts [target] // Each created invoice is written as .xml (or .pdf for zugferd-facturx). import { readFile, writeFile } from "node:fs/promises"; const [file, mappingFile, target = "xrechnung-ubl"] = process.argv.slice(2); if (!file || !mappingFile) throw new Error("Usage: import-export.ts [target]"); const mapping = JSON.parse(await readFile(mappingFile, "utf8")); const content = await readFile(file); // XML exports go to /generate/xml; tables (CSV text, Excel as base64) to /generate/csv const ext = file.toLowerCase().split(".").pop(); const [path, body] = ext === "xml" ? ["/v1/invoices/generate/xml", { xml: content.toString("utf8") }] : ext === "xlsx" ? ["/v1/invoices/generate/csv", { xlsx: content.toString("base64") }] : ["/v1/invoices/generate/csv", { csv: content.toString("utf8") }]; const res = await fetch(`${process.env.EINV_BASE ?? "https://einvoiceengine.com"}${path}`, { method: "POST", headers: { Authorization: `Bearer ${process.env.EINV_KEY}`, "Content-Type": "application/json", "Idempotency-Key": `import-${Date.now()}` }, body: JSON.stringify({ ...body, mapping, target, store: false }), }); const r = await res.json(); if (!res.ok) throw new Error(`${r.error.code}: ${r.error.message}`); for (const x of r.results) { if (x.status === "created") { const pdf = x.target.encoding === "base64"; await writeFile(`${x.key}.${pdf ? "pdf" : "xml"}`, Buffer.from(x.document, pdf ? "base64" : "utf8")); } else { // skipped: values that cannot be read (row = line or sheet row); failed: validation findings console.error(x.key, x.status, JSON.stringify(x.issues ?? x.error)); } } console.log(`${r.summary.created} created, ${r.summary.failed} not created`);