diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..d1a3b98 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?tenant=…`), with optional `from`/`to` date range and `currency` filter. ## 3.2.0 - Returns: partial refunds. diff --git a/src/lib/csv.js b/src/lib/csv.js new file mode 100644 index 0000000..d9a6c35 --- /dev/null +++ b/src/lib/csv.js @@ -0,0 +1,11 @@ +// RFC 4180 CSV helpers. +const EOL = '\r\n'; + +export function csvField(v) { + const s = String(v ?? ''); + return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +export function toCsv(header, rows) { + return [header, ...rows].map((r) => r.map(csvField).join(',')).join(EOL) + EOL; +} diff --git a/src/modules/billing/formatters.js b/src/modules/billing/formatters.js index f64ce28..7df42f2 100644 --- a/src/modules/billing/formatters.js +++ b/src/modules/billing/formatters.js @@ -1,5 +1,17 @@ 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_HEADER = ['id', 'date', 'customer', 'subtotal', 'discount', 'tax', 'total', 'currency']; + +export function invoicesToCsv(invoices) { + return toCsv(INVOICE_CSV_HEADER, 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..b5b6ec5 100644 --- a/src/modules/billing/routes.js +++ b/src/modules/billing/routes.js @@ -1,8 +1,9 @@ -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 { exportInvoices, getInvoice, listInvoices } from './service.js'; +import { formatInvoice, invoicesToCsv } from './formatters.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; charset=utf-8'))], ['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..47ec296 100644 --- a/src/modules/billing/service.js +++ b/src/modules/billing/service.js @@ -1,4 +1,7 @@ -import { NotFoundError } from '../../lib/errors.js'; +import { NotFoundError, ValidationError } from '../../lib/errors.js'; +import { requireString } from '../../lib/validate.js'; +import { inRange } from '../../lib/time.js'; +import { validateCurrency } from './validators.js'; import { discountFor } from './discounts.js'; import { taxFor } from './tax.js'; import { TAX_REGION } from './constants.js'; @@ -21,3 +24,26 @@ export function getInvoice(id) { export function listInvoices({ tenantId } = {}) { return allInvoices().filter((i) => !tenantId || i.tenantId === tenantId); } + +function optionalDate(query, key) { + const v = query?.[key]; + if (v === undefined || v === '') return undefined; + const d = new Date(v + 'T00:00:00Z'); + if (!/^\d{4}-\d{2}-\d{2}$/.test(v) || Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v) { + throw new ValidationError(`${key} must be a date (YYYY-MM-DD)`); + } + return v; +} + +// Invoices for a tenant's CSV export: filtered by inclusive date range, sorted by date then id. +export function exportInvoices(query = {}) { + const tenantId = requireString(query, 'tenant'); + const from = optionalDate(query, 'from'); + const to = optionalDate(query, 'to'); + const currency = query.currency === undefined || query.currency === '' ? undefined : validateCurrency(query); + const all = listInvoices({ tenantId }); + if (all.length === 0) throw new NotFoundError('tenant ' + tenantId); + return all + .filter((i) => inRange(i.date, from, to) && (!currency || i.currency === currency)) + .sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); +} diff --git a/tests/billing.test.js b/tests/billing.test.js index 445b393..a9ac74f 100644 --- a/tests/billing.test.js +++ b/tests/billing.test.js @@ -1,6 +1,58 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { priceLines, getInvoice, listInvoices, discountFor } from '../src/modules/billing/index.js'; +import { createApp } from '../src/server.js'; + +const HEADER = 'id,date,customer,subtotal,discount,tax,total,currency'; +const csv = (qs) => createApp().handle('GET', '/billing/invoices.csv' + qs); +const lines = (body) => body.split('\r\n'); +const ids = (body) => lines(body).map((l) => l.split(',')[0]); + +test('billing csv: full export for a tenant, sorted, quoted, formatted', async () => { + const res = await csv('?tenant=acme'); + assert.equal(res.status, 200); + assert.match(res.headers['content-type'], /^text\/csv/); + assert.ok(res.body.endsWith('\r\n')); + assert.deepEqual(lines(res.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', + '', + ]); +}); + +test('billing csv: from/to are inclusive', async () => { + assert.deepEqual(ids((await csv('?tenant=acme&from=2026-09-15&to=2026-09-15')).body), ['id', 'inv_0002', 'inv_0003', '']); + assert.deepEqual(ids((await csv('?tenant=acme&from=2026-09-16')).body), ['id', 'inv_0004', '']); + assert.deepEqual(ids((await csv('?tenant=acme&to=2026-08-31')).body), ['id', 'inv_0006', '']); +}); + +test('billing csv: currency filter', async () => { + assert.deepEqual(ids((await csv('?tenant=acme¤cy=EUR')).body), ['id', 'inv_0003', '']); + assert.deepEqual(ids((await csv('?tenant=acme¤cy=USD&from=2026-09-15')).body), ['id', 'inv_0002', 'inv_0004', '']); + const none = await csv('?tenant=acme¤cy=GBP'); + assert.equal(none.status, 200); + assert.equal(none.body, HEADER + '\r\n'); + assert.equal((await csv('?tenant=acme¤cy=JPY')).status, 400); + assert.equal((await csv('?tenant=acme¤cy=usd')).status, 400); +}); + +test('billing csv: no matches returns just the header', async () => { + const res = await csv('?tenant=acme&from=2030-01-01'); + assert.equal(res.status, 200); + assert.equal(res.body, HEADER + '\r\n'); +}); + +test('billing csv: errors', async () => { + assert.equal((await csv('')).status, 400); + assert.equal((await csv('?tenant=')).status, 400); + assert.equal((await csv('?tenant=nobody')).status, 404); + assert.equal((await csv('?tenant=acme&from=garbage')).status, 400); + assert.equal((await csv('?tenant=acme&to=2026-02-30')).status, 400); +}); test('billing: prices lines with discount and tax', () => { const p = priceLines([{ unitCents: 1000, qty: 2 }], { discountCode: 'save10', region: 'US' }); diff --git a/tests/lib.test.js b/tests/lib.test.js index a03e86e..3dfed99 100644 --- a/tests/lib.test.js +++ b/tests/lib.test.js @@ -2,6 +2,7 @@ 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'; test('lib: money', () => { assert.equal(formatCents(105), '1.05'); @@ -14,3 +15,13 @@ 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 quoting (RFC 4180)', () => { + assert.equal(csvField('plain'), 'plain'); + assert.equal(csvField('a,b'), '"a,b"'); + assert.equal(csvField('say "hi"'), '"say ""hi"""'); + assert.equal(csvField('two\nlines'), '"two\nlines"'); + assert.equal(csvField(null), ''); + assert.equal(toCsv(['a', 'b'], []), 'a,b\r\n'); + assert.equal(toCsv(['a', 'b'], [[1, 'x,y']]), 'a,b\r\n1,"x,y"\r\n'); +});