Invoices into accounting
Invoices made in Punchly usually have to reach the books. This recipe exports a period's issued invoices, with what was paid and what is still owed, as a CSV your accounting system can import.
Before you start
A workspace key with invoices:read (the Read-only preset includes it). Amounts are included because a workspace key acts as an admin; with a personal key they're included only when its owner may see money.
The script
js
// Issued invoices for a period, as CSV for an accounting system.
// Node 18 or later; no packages. Usage:
// PUNCHLY_API_KEY=pkw_… node invoices-export.mjs 2026-09-01 2026-09-30 > invoices.csv
// With no dates it exports last month (by issue date). PUNCHLY_INVOICE_STATUSES picks which
// (default: sent, partly paid and paid; drafts are `unsent`).
const API = process.env.PUNCHLY_API_URL ?? 'https://api.punchly.work/v1';
const KEY = process.env.PUNCHLY_API_KEY;
if (!KEY) throw new Error('Set PUNCHLY_API_KEY');
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function punchly(path) {
for (let attempt = 0; ; attempt++) {
const res = await fetch(`${API}${path}`, { headers: { 'X-Api-Key': KEY } });
if (res.status === 429 && attempt < 5) {
await sleep(Number(res.headers.get('retry-after') ?? 5) * 1000);
continue;
}
const text = await res.text();
if (!res.ok) throw new Error(`GET ${path}: ${res.status} ${text}`);
return JSON.parse(text);
}
}
async function workspaceId() {
if (process.env.PUNCHLY_WORKSPACE_ID) return process.env.PUNCHLY_WORKSPACE_ID;
const { items } = await punchly('/me/workspaces');
if (items.length !== 1) throw new Error('Set PUNCHLY_WORKSPACE_ID: the key reaches several');
return items[0].workspaceId;
}
/** Minor units to a decimal string, with the currency's own number of decimals. */
function money(minor, currency) {
const digits = new Intl.NumberFormat('en', { style: 'currency', currency })
.resolvedOptions().maximumFractionDigits;
return (minor / 10 ** digits).toFixed(digits);
}
const csv = (values) => values.map((v) => `"${String(v ?? '').replaceAll('"', '""')}"`).join(',');
const now = new Date();
const lastMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1));
const [
from = lastMonth.toISOString().slice(0, 10),
to = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 0)).toISOString().slice(0, 10),
] = process.argv.slice(2);
const wid = await workspaceId();
console.log(csv(['number', 'client', 'issued', 'due', 'currency', 'total', 'paid', 'balance', 'status']));
let cursor = null;
do {
const query = new URLSearchParams({
from,
to,
statuses: process.env.PUNCHLY_INVOICE_STATUSES ?? 'sent,partially_paid,paid',
limit: '200',
...(cursor && { cursor }),
});
const page = await punchly(`/workspaces/${wid}/invoices?${query}`);
if (!page.amountsVisible) throw new Error('This key may not see amounts: use an owner’s or admin’s');
for (const inv of page.items) {
const c = inv.currencyCode;
console.log(
csv([
inv.number,
inv.clientName,
inv.issueDate,
inv.dueDate,
c,
money(inv.totalMinor, c),
money(inv.paidMinor, c),
money(inv.balanceMinor, c),
inv.status,
]),
);
}
cursor = page.nextCursor;
} while (cursor);bash
PUNCHLY_API_KEY=pkw_… node invoices-export.mjs 2026-09-01 2026-09-30 > invoices.csvtext
"number","client","issued","due","currency","total","paid","balance","status"
"INV-2026-0012","Acme Ltd","2026-09-03","2026-09-17","USD","1840.00","1840.00","0.00","paid"
"INV-2026-0013","Globex","2026-09-15","2026-09-29","EUR","960.00","0.00","960.00","sent"Notes
- Which invoices. By issue date; by default the ones that went out —
sent,partially_paidandpaid. SetPUNCHLY_INVOICE_STATUSES(for exampleunsentfor drafts, or addvoid). - Money. Amounts are integers in the currency's minor unit; the script turns them into decimals with that currency's own number of places (two for USD, none for JPY). See Dates and time zones.
- Lines and payments.
GET /workspaces/{wid}/invoices/{id}has the lines and taxes;/invoices/{id}/paymentsthe payments, if the books need them one by one. - Payments as they happen. A webhook with
invoice.paidandinvoice.senttells the books the moment an invoice goes out or is settled. See Webhooks.