diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..78e32cb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ # Changes ## Unreleased +- Billing: CSV export of a tenant's invoices at `GET /billing/invoices.csv` + (optional `from`, `to` and `currency` filters). ## 3.2.0 - Returns: partial refunds. diff --git a/src/modules/billing/csv.js b/src/modules/billing/csv.js new file mode 100644 index 0000000..56ecbc9 --- /dev/null +++ b/src/modules/billing/csv.js @@ -0,0 +1,26 @@ +import { formatCents } from '../../lib/money.js'; + +export const CSV_COLUMNS = ['id', 'date', 'customer', 'subtotal', 'discount', 'tax', 'total', 'currency']; + +// RFC 4180: quote fields containing a comma, double quote or line break; double inner quotes. +export function csvField(value) { + const s = String(value ?? ''); + return /[",\r\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; +} + +export function invoiceRow(inv) { + return [ + inv.id, + inv.date, + inv.customer, + formatCents(inv.subtotal), + formatCents(inv.discount), + formatCents(inv.tax), + formatCents(inv.total), + inv.currency, + ].map(csvField).join(','); +} + +export function invoicesToCsv(invoices) { + return [CSV_COLUMNS.join(','), ...invoices.map(invoiceRow)].join('\n') + '\n'; +} diff --git a/src/modules/billing/index.js b/src/modules/billing/index.js index 88a5e1c..7cb98f3 100644 --- a/src/modules/billing/index.js +++ b/src/modules/billing/index.js @@ -2,4 +2,5 @@ export * from './service.js'; export * from './formatters.js'; export { taxFor, taxRate } from './tax.js'; export { discountFor } from './discounts.js'; +export { invoicesToCsv, csvField } from './csv.js'; export { routes } from './routes.js'; diff --git a/src/modules/billing/routes.js b/src/modules/billing/routes.js index 0ac3d5c..020d7e4 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 { ok, text, wrap } from '../../lib/http.js'; +import { exportInvoices, getInvoice, listInvoices } from './service.js'; import { formatInvoice } from './formatters.js'; +import { invoicesToCsv } from './csv.js'; export const routes = [ ['GET', '/billing/invoices', wrap(async (req) => ok(listInvoices(req.query).map(formatInvoice)))], + ['GET', '/billing/invoices.csv', wrap(async (req) => text(invoicesToCsv(exportInvoices(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..6a4267b 100644 --- a/src/modules/billing/service.js +++ b/src/modules/billing/service.js @@ -1,7 +1,9 @@ -import { NotFoundError } from '../../lib/errors.js'; +import { NotFoundError, ValidationError } from '../../lib/errors.js'; +import { inRange, isoDate } from '../../lib/time.js'; import { discountFor } from './discounts.js'; import { taxFor } from './tax.js'; import { TAX_REGION } from './constants.js'; +import { validateCurrency } from './validators.js'; import { allInvoices, findInvoice } from './repo.js'; // Prices order lines. Returns integer cents. @@ -21,3 +23,24 @@ export function getInvoice(id) { export function listInvoices({ tenantId } = {}) { return allInvoices().filter((i) => !tenantId || i.tenantId === tenantId); } + +function optionalDate(value, key) { + if (value === undefined) return undefined; + const valid = /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(value)) && isoDate(value) === value; + if (!valid) throw new ValidationError(`${key} must be a date in YYYY-MM-DD format`); + return value; +} + +// Invoices for one tenant, optionally limited to an inclusive date range, sorted by date then id. +export function exportInvoices({ tenant, from, to, currency } = {}) { + if (typeof tenant !== 'string' || tenant.trim() === '') throw new ValidationError('tenant is required'); + const fromDate = optionalDate(from, 'from'); + const toDate = optionalDate(to, 'to'); + const wanted = currency === undefined ? undefined : validateCurrency({ currency }); + const all = listInvoices({ tenantId: tenant }); + if (all.length === 0) throw new NotFoundError('tenant ' + tenant); + const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + return all + .filter((i) => inRange(i.date, fromDate, toDate) && (!wanted || i.currency === wanted)) + .sort((a, b) => cmp(a.date, b.date) || cmp(a.id, b.id)); +} diff --git a/tests/billing.test.js b/tests/billing.test.js index 445b393..d93b6f4 100644 --- a/tests/billing.test.js +++ b/tests/billing.test.js @@ -1,6 +1,10 @@ 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, csvField, invoicesToCsv, +} from '../src/modules/billing/index.js'; + +const HEADER = 'id,date,customer,subtotal,discount,tax,total,currency'; test('billing: prices lines with discount and tax', () => { const p = priceLines([{ unitCents: 1000, qty: 2 }], { discountCode: 'save10', region: 'US' }); @@ -17,3 +21,50 @@ test('billing: invoices', () => { assert.equal(listInvoices({ tenantId: 'globex' }).length, 1); assert.throws(() => getInvoice('inv_9999'), /not found/); }); + +test('csv: csvField quotes only when needed', () => { + assert.equal(csvField('plain'), 'plain'); + assert.equal(csvField('a,b'), '"a,b"'); + assert.equal(csvField('say "hi"'), '"say ""hi"""'); + assert.equal(csvField('line1\nline2'), '"line1\nline2"'); + assert.equal(csvField('a\r\nb'), '"a\r\nb"'); +}); + +test('csv: empty list is just the header line', () => { + assert.equal(invoicesToCsv([]), HEADER + '\n'); +}); + +test('csv: exportInvoices sorts by date then id', () => { + assert.deepEqual(exportInvoices({ tenant: 'acme' }).map((i) => i.id), + ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0003', 'inv_0004']); +}); + +test('csv: exportInvoices range is inclusive and optional', () => { + const ids = (q) => exportInvoices({ tenant: '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: '2027-01-01' }), []); + assert.deepEqual(ids({ from: '2026-10-01', to: '2026-09-01' }), []); +}); + +test('csv: exportInvoices currency filter', () => { + const ids = (q) => exportInvoices({ tenant: 'acme', ...q }).map((i) => i.id); + assert.deepEqual(ids({ currency: 'EUR' }), ['inv_0003']); + assert.deepEqual(ids({ currency: 'USD', from: '2026-09-15' }), ['inv_0002', 'inv_0004']); + assert.deepEqual(ids({ currency: 'GBP' }), []); + for (const bad of ['usd', 'JPY', '']) { + assert.throws(() => exportInvoices({ tenant: 'acme', currency: bad }), (e) => e.status === 400); + } + assert.throws(() => exportInvoices({ tenant: 'nobody', currency: 'JPY' }), (e) => e.status === 400); +}); + +test('csv: exportInvoices validation and 404', () => { + const status = (n) => (e) => e.status === n; + assert.throws(() => exportInvoices({}), status(400)); + assert.throws(() => exportInvoices({ tenant: ' ' }), status(400)); + assert.throws(() => exportInvoices({ tenant: 'acme', from: 'abc' }), status(400)); + assert.throws(() => exportInvoices({ tenant: 'acme', to: '2026-02-30' }), status(400)); + assert.throws(() => exportInvoices({ tenant: 'acme', from: '2026-9-1' }), status(400)); + assert.throws(() => exportInvoices({ tenant: 'nobody' }), status(404)); +}); diff --git a/tests/server.test.js b/tests/server.test.js index e836eaa..2433158 100644 --- a/tests/server.test.js +++ b/tests/server.test.js @@ -17,3 +17,46 @@ 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); }); + +test('server: invoices.csv', async () => { + const app = createApp(); + const get = (q) => app.handle('GET', '/billing/invoices.csv' + q); + const HEADER = 'id,date,customer,subtotal,discount,tax,total,currency'; + + const r = await get('?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 ranged = await get('?tenant=acme&from=2026-09-15&to=2026-09-15'); + assert.deepEqual(ranged.body.split('\n').map((l) => l.slice(0, 8)), ['id,date,', 'inv_0002', 'inv_0003', '']); + + const none = await get('?tenant=acme&from=2030-01-01'); + assert.equal(none.status, 200); + assert.equal(none.body, HEADER + '\n'); + + const globex = await get('?tenant=globex'); + assert.equal(globex.body, HEADER + '\ninv_0005,2026-09-20,Northwind,80.00,8.00,14.40,86.40,GBP\n'); + + const eur = await get('?tenant=acme¤cy=EUR'); + assert.equal(eur.body, HEADER + '\ninv_0003,2026-09-15,"The ""Quick"" Shop",200.00,5.00,39.00,234.00,EUR\n'); + const noGbp = await get('?tenant=acme¤cy=GBP'); + assert.equal(noGbp.status, 200); + assert.equal(noGbp.body, HEADER + '\n'); + assert.equal((await get('?tenant=acme¤cy=JPY')).status, 400); + assert.equal((await get('?tenant=acme¤cy=usd')).status, 400); + assert.equal((await get('?tenant=acme¤cy=')).status, 400); + + assert.equal((await get('')).status, 400); + assert.equal((await get('?tenant=')).status, 400); + assert.equal((await get('?tenant=acme&from=nope')).status, 400); + assert.equal((await get('?tenant=nobody')).status, 404); +});