diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..010b6d9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Billing: CSV export of a tenant's invoices (`GET /billing/invoices.csv`), with optional `from`, `to` and `currency` filters. ## 3.2.0 - Returns: partial refunds. diff --git a/src/lib/csv.js b/src/lib/csv.js new file mode 100644 index 0000000..3832bd2 --- /dev/null +++ b/src/lib/csv.js @@ -0,0 +1,10 @@ +// Minimal RFC 4180 writer. Fields are quoted only when they need to be. +export function csvField(value) { + const s = String(value ?? ''); + return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +// Lines are joined with "\n" and the output always ends with one. +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..6dc6157 100644 --- a/src/lib/validate.js +++ b/src/lib/validate.js @@ -1,4 +1,5 @@ import { ValidationError } from './errors.js'; +import { isoDate } from './time.js'; export function requireString(obj, key, { max = 200 } = {}) { const v = obj?.[key]; @@ -19,3 +20,12 @@ export function oneOf(obj, key, allowed) { if (!allowed.includes(v)) throw new ValidationError(`${key} must be one of ${allowed.join(', ')}`); return v; } + +// Optional strict YYYY-MM-DD date. Absent or blank -> undefined. +export function optionalIsoDate(obj, key) { + const v = obj?.[key]; + if (v === undefined || v === null || v === '') return undefined; + const ok = typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(v)) && isoDate(v) === v; + if (!ok) throw new ValidationError(`${key} must be a date in YYYY-MM-DD format`); + return v; +} diff --git a/src/modules/billing/formatters.js b/src/modules/billing/formatters.js index f64ce28..a6399a0 100644 --- a/src/modules/billing/formatters.js +++ b/src/modules/billing/formatters.js @@ -1,5 +1,22 @@ import { formatCents } from '../../lib/money.js'; +import { isoDate } from '../../lib/time.js'; +import { toCsv } from '../../lib/csv.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 formatInvoicesCsv(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..79a950d 100644 --- a/src/modules/billing/routes.js +++ b/src/modules/billing/routes.js @@ -1,8 +1,10 @@ -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 { getInvoice, listInvoices, exportInvoices } from './service.js'; +import { formatInvoice, formatInvoicesCsv } from './formatters.js'; +import { validateInvoiceExport } 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) => text(formatInvoicesCsv(exportInvoices(validateInvoiceExport(req.query))), '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..b550ee0 100644 --- a/src/modules/billing/service.js +++ b/src/modules/billing/service.js @@ -1,4 +1,5 @@ -import { NotFoundError } from '../../lib/errors.js'; +import { NotFoundError, ValidationError } 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,16 @@ 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, optionally limited to one +// currency, sorted by date then id. 404 only when the tenant has no invoices at all; an empty +// date range or currency yields []. +export function exportInvoices({ tenantId, from, to, currency }) { + if (!tenantId) throw new ValidationError('tenant is required'); + 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/src/modules/billing/validators.js b/src/modules/billing/validators.js index 501b848..c98435d 100644 --- a/src/modules/billing/validators.js +++ b/src/modules/billing/validators.js @@ -1,6 +1,16 @@ -import { oneOf } from '../../lib/validate.js'; +import { oneOf, requireString, optionalIsoDate } from '../../lib/validate.js'; import { CURRENCIES } from './constants.js'; export function validateCurrency(input) { return oneOf(input, 'currency', CURRENCIES); } + +export function validateInvoiceExport(query) { + return { + tenantId: requireString(query, 'tenant'), + from: optionalIsoDate(query, 'from'), + to: optionalIsoDate(query, 'to'), + // Optional, but if present it must be exactly one of CURRENCIES (even if blank or lowercase). + currency: query?.currency === undefined ? undefined : validateCurrency(query), + }; +} diff --git a/tests/billing.test.js b/tests/billing.test.js index 445b393..a0f823e 100644 --- a/tests/billing.test.js +++ b/tests/billing.test.js @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { priceLines, getInvoice, listInvoices, discountFor } from '../src/modules/billing/index.js'; +import { priceLines, getInvoice, listInvoices, discountFor, exportInvoices, formatInvoicesCsv } from '../src/modules/billing/index.js'; test('billing: prices lines with discount and tax', () => { const p = priceLines([{ unitCents: 1000, qty: 2 }], { discountCode: 'save10', region: 'US' }); @@ -17,3 +17,44 @@ test('billing: invoices', () => { assert.equal(listInvoices({ tenantId: 'globex' }).length, 1); assert.throws(() => getInvoice('inv_9999'), /not found/); }); + +test('billing: export sorts by date then id', () => { + const ids = exportInvoices({ tenantId: 'acme' }).map((i) => i.id); + assert.deepEqual(ids, ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0003', 'inv_0004']); +}); + +test('billing: export range is inclusive and optional', () => { + const ids = (q) => exportInvoices({ tenantId: 'acme', ...q }).map((i) => i.id); + assert.deepEqual(ids({ from: '2026-09-15', to: '2026-09-15' }), ['inv_0002', 'inv_0003']); + assert.deepEqual(ids({ from: '2026-09-15' }), ['inv_0002', 'inv_0003', 'inv_0004']); + assert.deepEqual(ids({ to: '2026-09-02' }), ['inv_0006', 'inv_0001']); + assert.deepEqual(ids({ from: '2030-01-01' }), []); +}); + +test('billing: export can filter by currency', () => { + const ids = (q) => exportInvoices({ tenantId: 'acme', ...q }).map((i) => i.id); + assert.deepEqual(ids({ currency: 'USD' }), ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0004']); + assert.deepEqual(ids({ currency: 'EUR' }), ['inv_0003']); + assert.deepEqual(ids({ currency: 'GBP' }), []); + assert.deepEqual(ids({ currency: 'USD', from: '2026-09-15' }), ['inv_0002', 'inv_0004']); +}); + +test('billing: export is scoped to the tenant; unknown tenant is 404', () => { + assert.deepEqual(exportInvoices({ tenantId: 'globex' }).map((i) => i.id), ['inv_0005']); + assert.throws(() => exportInvoices({ tenantId: 'nobody' }), (e) => e.status === 404); + assert.throws(() => exportInvoices({}), (e) => e.status === 400); +}); + +test('billing: csv formatting', () => { + const csv = formatInvoicesCsv(exportInvoices({ tenantId: 'acme' })); + assert.equal(csv, [ + 'id,date,customer,subtotal,discount,tax,total,currency', + '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')); + assert.equal(formatInvoicesCsv([]), 'id,date,customer,subtotal,discount,tax,total,currency\n'); +}); diff --git a/tests/lib.test.js b/tests/lib.test.js index a03e86e..6834d64 100644 --- a/tests/lib.test.js +++ b/tests/lib.test.js @@ -2,6 +2,8 @@ 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 { csvField, toCsv } from '../src/lib/csv.js'; +import { optionalIsoDate } from '../src/lib/validate.js'; test('lib: money', () => { assert.equal(formatCents(105), '1.05'); @@ -14,3 +16,27 @@ test('lib: time', () => { assert.equal(inRange('2026-09-15', '2026-09-15', '2026-09-30'), true); assert.equal(inRange('2026-10-01', undefined, '2026-09-30'), false); }); + +test('lib: csv field quoting', () => { + assert.equal(csvField('plain'), 'plain'); + assert.equal(csvField(12), '12'); + assert.equal(csvField(''), ''); + assert.equal(csvField('a,b'), '"a,b"'); + assert.equal(csvField('say "hi"'), '"say ""hi"""'); + assert.equal(csvField('two\nlines'), '"two\nlines"'); + assert.equal(csvField('cr\rhere'), '"cr\rhere"'); +}); + +test('lib: csv rows end with a newline', () => { + assert.equal(toCsv(['a', 'b'], []), 'a,b\n'); + assert.equal(toCsv(['a', 'b'], [['1', 'x,y']]), 'a,b\n1,"x,y"\n'); +}); + +test('lib: optionalIsoDate is strict', () => { + assert.equal(optionalIsoDate({}, 'from'), undefined); + assert.equal(optionalIsoDate({ from: '' }, 'from'), undefined); + assert.equal(optionalIsoDate({ from: '2026-09-15' }, 'from'), '2026-09-15'); + for (const bad of ['2026-02-30', '2026-9-1', '20260901', 'abc', '2026-13-01', '2026-09-15T00:00:00Z']) { + assert.throws(() => optionalIsoDate({ from: bad }, 'from'), (e) => e.status === 400, bad); + } +}); diff --git a/tests/server.test.js b/tests/server.test.js index e836eaa..a66efb9 100644 --- a/tests/server.test.js +++ b/tests/server.test.js @@ -17,3 +17,50 @@ test('server: invoice route and 404s', async () => { assert.equal((await app.handle('GET', '/billing/invoices/nope')).status, 404); assert.equal((await app.handle('GET', '/nothing')).status, 404); }); + +const CSV_HEADER = 'id,date,customer,subtotal,discount,tax,total,currency\n'; + +test('server: invoices csv export', async () => { + const app = createApp(); + const r = await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=2026-09-15&to=2026-10-01'); + assert.equal(r.status, 200); + assert.equal(r.headers['content-type'], 'text/csv'); + assert.equal(r.body, CSV_HEADER + + 'inv_0002,2026-09-15,"Smith, Jones & Co",49.99,0.00,3.50,53.49,USD\n' + + 'inv_0003,2026-09-15,"The ""Quick"" Shop",200.00,5.00,39.00,234.00,EUR\n' + + 'inv_0004,2026-10-01,Ortega Freight,1.05,0.00,0.07,1.12,USD\n'); + const all = await app.handle('GET', '/billing/invoices.csv?tenant=acme'); + assert.equal(all.body.split('\n').length, 7); // header + 5 rows + trailing empty + assert.ok(!all.body.includes('inv_0005')); +}); + +test('server: invoices csv export filters by currency', async () => { + const app = createApp(); + const get = (q) => app.handle('GET', '/billing/invoices.csv' + q); + const eur = await get('?tenant=acme¤cy=EUR'); + assert.equal(eur.status, 200); + assert.equal(eur.body, CSV_HEADER + 'inv_0003,2026-09-15,"The ""Quick"" Shop",200.00,5.00,39.00,234.00,EUR\n'); + const gbp = await get('?tenant=acme¤cy=GBP'); + assert.equal(gbp.status, 200); + assert.equal(gbp.body, CSV_HEADER); + for (const bad of ['JPY', 'usd', '']) { + assert.equal((await get('?tenant=acme¤cy=' + bad)).status, 400, bad); + } + assert.equal((await get('?tenant=nobody¤cy=USD')).status, 404); + assert.equal((await get('?tenant=nobody¤cy=JPY')).status, 400); +}); + +test('server: invoices csv export edge cases', async () => { + const app = createApp(); + const get = (q) => app.handle('GET', '/billing/invoices.csv' + q); + assert.equal((await get('')).status, 400); + assert.equal((await get('?tenant=')).status, 400); + assert.equal((await get('?from=2026-09-01')).status, 400); + assert.equal((await get('?tenant=acme&from=nope')).status, 400); + assert.equal((await get('?tenant=acme&to=2026-02-30')).status, 400); + assert.equal((await get('?tenant=nobody')).status, 404); + const empty = await get('?tenant=acme&from=2030-01-01'); + assert.equal(empty.status, 200); + assert.equal(empty.headers['content-type'], 'text/csv'); + assert.equal(empty.body, CSV_HEADER); +});