diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..b695499 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Billing: CSV export of invoices (`GET /billing/invoices.csv`), filterable by tenant, date range and currency. ## 3.2.0 - Returns: partial refunds. diff --git a/src/lib/csv.js b/src/lib/csv.js new file mode 100644 index 0000000..9e1d6fa --- /dev/null +++ b/src/lib/csv.js @@ -0,0 +1,8 @@ +export function csvField(value) { + const s = String(value); + return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +export function toCsv(header, rows) { + return [header, ...rows].map((r) => r.map(csvField).join(',')).join('\n') + '\n'; +} diff --git a/src/lib/validate.js b/src/lib/validate.js index 0fe84c3..d2c6f59 100644 --- a/src/lib/validate.js +++ b/src/lib/validate.js @@ -14,6 +14,16 @@ export function optionalInt(obj, key, { min = 0, max = Number.MAX_SAFE_INTEGER } return v; } +export function optionalDate(obj, key) { + const v = obj?.[key]; + if (v === undefined || v === null || v === '') return undefined; + const d = typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) ? new Date(v) : null; + if (!d || Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v) { + throw new ValidationError(`${key} must be a date (YYYY-MM-DD)`); + } + return v; +} + export function oneOf(obj, key, allowed) { const v = obj?.[key]; if (!allowed.includes(v)) throw new ValidationError(`${key} must be one of ${allowed.join(', ')}`); diff --git a/src/modules/billing/formatters.js b/src/modules/billing/formatters.js index f64ce28..38d911c 100644 --- a/src/modules/billing/formatters.js +++ b/src/modules/billing/formatters.js @@ -1,5 +1,17 @@ import { formatCents } from '../../lib/money.js'; +import { toCsv } from '../../lib/csv.js'; +import { isoDate } from '../../lib/time.js'; export function formatInvoice(inv) { return { ...inv, total: formatCents(inv.total) }; } + +export const INVOICE_CSV_COLUMNS = ['id', 'date', 'customer', 'subtotal', 'discount', 'tax', 'total', 'currency']; + +export function invoicesToCsv(invoices) { + return toCsv(INVOICE_CSV_COLUMNS, invoices.map((i) => [ + i.id, isoDate(i.date), i.customer, + formatCents(i.subtotal), formatCents(i.discount), formatCents(i.tax), formatCents(i.total), + i.currency, + ])); +} diff --git a/src/modules/billing/routes.js b/src/modules/billing/routes.js index 0ac3d5c..45904bc 100644 --- a/src/modules/billing/routes.js +++ b/src/modules/billing/routes.js @@ -1,8 +1,17 @@ -import { ok, wrap } from '../../lib/http.js'; -import { getInvoice, listInvoices } from './service.js'; -import { formatInvoice } from './formatters.js'; +import { ok, text, wrap } from '../../lib/http.js'; +import { optionalDate, requireString } from '../../lib/validate.js'; +import { exportInvoices, getInvoice, listInvoices } from './service.js'; +import { formatInvoice, invoicesToCsv } from './formatters.js'; +import { validateCurrency } from './validators.js'; export const routes = [ ['GET', '/billing/invoices', wrap(async (req) => ok(listInvoices(req.query).map(formatInvoice)))], + ['GET', '/billing/invoices.csv', wrap(async (req) => { + const tenantId = requireString(req.query, 'tenant'); + const from = optionalDate(req.query, 'from'); + const to = optionalDate(req.query, 'to'); + const currency = req.query.currency === undefined ? undefined : validateCurrency(req.query); + return text(invoicesToCsv(exportInvoices({ tenantId, from, to, currency })), 'text/csv'); + })], ['GET', '/billing/invoices/:id', wrap(async (req) => ok(formatInvoice(getInvoice(req.params.id))))], ]; diff --git a/src/modules/billing/service.js b/src/modules/billing/service.js index d84492f..2da6a37 100644 --- a/src/modules/billing/service.js +++ b/src/modules/billing/service.js @@ -1,4 +1,5 @@ import { NotFoundError } from '../../lib/errors.js'; +import { inRange } from '../../lib/time.js'; import { discountFor } from './discounts.js'; import { taxFor } from './tax.js'; import { TAX_REGION } from './constants.js'; @@ -21,3 +22,13 @@ export function getInvoice(id) { export function listInvoices({ tenantId } = {}) { return allInvoices().filter((i) => !tenantId || i.tenantId === tenantId); } + +// Invoices for one tenant within the inclusive [from, to] range, ordered by date then id. +export function exportInvoices({ tenantId, from, to, currency }) { + const all = listInvoices({ tenantId }); + if (all.length === 0) throw new NotFoundError('invoices for tenant ' + tenantId); + const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + return all + .filter((i) => inRange(i.date, from, to) && (!currency || i.currency === currency)) + .sort((a, b) => cmp(a.date, b.date) || cmp(a.id, b.id)); +} diff --git a/tests/lib.test.js b/tests/lib.test.js index a03e86e..f9cea9d 100644 --- a/tests/lib.test.js +++ b/tests/lib.test.js @@ -2,6 +2,24 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { formatCents, percentOf } from '../src/lib/money.js'; import { inRange, isoDate } from '../src/lib/time.js'; +import { toCsv } from '../src/lib/csv.js'; +import { optionalDate } from '../src/lib/validate.js'; + +test('lib: csv escaping', () => { + assert.equal(toCsv(['a', 'b'], []), 'a,b\n'); + assert.equal( + toCsv(['a', 'b'], [['plain', 'x,y'], ['The "Quick" Shop', 'two\nlines']]), + 'a,b\nplain,"x,y"\n"The ""Quick"" Shop","two\nlines"\n', + ); +}); + +test('lib: optionalDate', () => { + assert.equal(optionalDate({}, 'from'), undefined); + assert.equal(optionalDate({ from: '2026-09-15' }, 'from'), '2026-09-15'); + assert.throws(() => optionalDate({ from: '2026-13-01' }, 'from'), /from must be a date/); + assert.throws(() => optionalDate({ from: '2026-02-30' }, 'from'), /from must be a date/); + assert.throws(() => optionalDate({ from: 'garbage' }, 'from'), /from must be a date/); +}); test('lib: money', () => { assert.equal(formatCents(105), '1.05'); diff --git a/tests/server.test.js b/tests/server.test.js index e836eaa..19162e6 100644 --- a/tests/server.test.js +++ b/tests/server.test.js @@ -9,6 +9,41 @@ test('server: every module registers routes', () => { assert.ok(app.router.routes().length >= 40); }); +test('server: invoices csv', async () => { + const app = createApp(); + const HEADER = 'id,date,customer,subtotal,discount,tax,total,currency'; + const r = await app.handle('GET', '/billing/invoices.csv?tenant=acme'); + assert.equal(r.status, 200); + assert.equal(r.headers['content-type'], 'text/csv'); + assert.equal(r.body, [ + HEADER, + 'inv_0006,2026-08-31,Blue Fern Ltd,30.00,0.00,2.10,32.10,USD', + 'inv_0001,2026-09-02,Blue Fern Ltd,120.00,12.00,7.56,115.56,USD', + 'inv_0002,2026-09-15,"Smith, Jones & Co",49.99,0.00,3.50,53.49,USD', + 'inv_0003,2026-09-15,"The ""Quick"" Shop",200.00,5.00,39.00,234.00,EUR', + 'inv_0004,2026-10-01,Ortega Freight,1.05,0.00,0.07,1.12,USD', + '', + ].join('\n')); + + const day = await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=2026-09-15&to=2026-09-15'); + assert.deepEqual(day.body.split('\n').map((l) => l.slice(0, 8)), [HEADER.slice(0, 8), 'inv_0002', 'inv_0003', '']); + + const none = await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=2027-01-01'); + assert.equal(none.status, 200); + assert.equal(none.body, HEADER + '\n'); + + const eur = await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=EUR'); + assert.deepEqual(eur.body.split('\n').map((l) => l.slice(0, 8)), [HEADER.slice(0, 8), 'inv_0003', '']); + const gbp = await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=GBP'); + assert.equal(gbp.status, 200); + assert.equal(gbp.body, HEADER + '\n'); + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=JPY')).status, 400); + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=')).status, 400); + assert.equal((await app.handle('GET', '/billing/invoices.csv')).status, 400); + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=nobody')).status, 404); + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=bad')).status, 400); +}); + test('server: invoice route and 404s', async () => { const app = createApp(); const r = await app.handle('GET', '/billing/invoices/inv_0004');