diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..b672305 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ # Changes ## Unreleased +- Billing: CSV export of a tenant's invoices (`GET /billing/invoices.csv`), with optional + `from`/`to` dates and an optional `currency` (USD, EUR or GBP) filter. ## 3.2.0 - Returns: partial refunds. diff --git a/README.md b/README.md index fd4d579..e1cb0b1 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Back-office API for small fleet operators: tenants, catalog, orders, shipping, returns, billing and reporting. Plain Node (no dependencies), ES modules. - `src/server.js` builds the app from every module's `routes`. -- `src/lib/` holds shared helpers (money, errors, validation, logging, ids, time). +- `src/lib/` holds shared helpers (money, errors, validation, logging, ids, time, csv). - `src/modules//` holds one area each: `service.js` (logic), `repo.js` (in-memory store), `routes.js`, `validators.js`, `formatters.js`, `constants.js`, `events.js`, `index.js`. diff --git a/src/lib/csv.js b/src/lib/csv.js new file mode 100644 index 0000000..be6b1d6 --- /dev/null +++ b/src/lib/csv.js @@ -0,0 +1,9 @@ +// Minimal RFC 4180 writer. Rows end with "\n"; fields are quoted only when needed. +export function csvField(value) { + const s = String(value ?? ''); + return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +export function toCsv(rows) { + return rows.map((row) => row.map(csvField).join(',') + '\n').join(''); +} diff --git a/src/modules/billing/formatters.js b/src/modules/billing/formatters.js index f64ce28..826096a 100644 --- a/src/modules/billing/formatters.js +++ b/src/modules/billing/formatters.js @@ -1,5 +1,20 @@ 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 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..e57b9ef 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, formatInvoicesCsv } 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(formatInvoicesCsv(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..2281933 100644 --- a/src/modules/billing/service.js +++ b/src/modules/billing/service.js @@ -3,6 +3,8 @@ import { discountFor } from './discounts.js'; import { taxFor } from './tax.js'; import { TAX_REGION } from './constants.js'; import { allInvoices, findInvoice } from './repo.js'; +import { validateInvoiceExportQuery } from './validators.js'; +import { inRange } from '../../lib/time.js'; // Prices order lines. Returns integer cents. export function priceLines(lines, { discountCode, region = TAX_REGION } = {}) { @@ -21,3 +23,15 @@ export function getInvoice(id) { export function listInvoices({ tenantId } = {}) { return allInvoices().filter((i) => !tenantId || i.tenantId === tenantId); } + +// Invoices for the CSV export, in integer cents, sorted by date then id. +// 404 only when the tenant has no invoices at all; an empty date window or currency is not an error. +export function exportInvoices(query) { + const { tenant, from, to, currency } = validateInvoiceExportQuery(query); + const mine = allInvoices().filter((i) => i.tenantId === tenant); + if (mine.length === 0) throw new NotFoundError('invoices for tenant ' + tenant); + const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + return mine + .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..9a8752d 100644 --- a/src/modules/billing/validators.js +++ b/src/modules/billing/validators.js @@ -1,6 +1,26 @@ -import { oneOf } from '../../lib/validate.js'; +import { ValidationError } from '../../lib/errors.js'; +import { oneOf, requireString } from '../../lib/validate.js'; +import { isoDate } from '../../lib/time.js'; import { CURRENCIES } from './constants.js'; export function validateCurrency(input) { return oneOf(input, 'currency', CURRENCIES); } + +function optionalDate(obj, key) { + const v = obj?.[key]; + if (v === undefined || v === null || v === '') return undefined; + let valid = typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v); + if (valid) { + try { valid = isoDate(v) === v; } catch { valid = false; } + } + if (!valid) throw new ValidationError(`${key} must be YYYY-MM-DD`); + return v; +} + +export function validateInvoiceExportQuery(query) { + const tenant = requireString(query, 'tenant'); + // Unlike from/to, an empty currency is not "absent": anything but USD, EUR or GBP is a 400. + const currency = query?.currency === undefined ? undefined : validateCurrency(query); + return { tenant, from: optionalDate(query, 'from'), to: optionalDate(query, 'to'), currency }; +} diff --git a/tests/billing.test.js b/tests/billing.test.js index 445b393..0e28a56 100644 --- a/tests/billing.test.js +++ b/tests/billing.test.js @@ -1,6 +1,8 @@ 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 +19,55 @@ 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 and is tenant-scoped', () => { + assert.deepEqual(exportInvoices({ tenant: 'acme' }).map((i) => i.id), + ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0003', 'inv_0004']); + assert.deepEqual(exportInvoices({ tenant: 'globex' }).map((i) => i.id), ['inv_0005']); +}); + +test('billing: export date bounds are 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('billing: export validation and 404', () => { + assert.throws(() => exportInvoices({}), (e) => e.status === 400); + assert.throws(() => exportInvoices({ tenant: ' ' }), (e) => e.status === 400); + assert.throws(() => exportInvoices({ tenant: 'nobody' }), (e) => e.status === 404); + for (const bad of ['yesterday', '2026-13-01', '2026-02-30', '2026-9-1', '2026-09-15T00:00:00Z']) { + assert.throws(() => exportInvoices({ tenant: 'acme', from: bad }), (e) => e.status === 400, bad); + assert.throws(() => exportInvoices({ tenant: 'acme', to: bad }), (e) => e.status === 400, bad); + } + // empty from/to behave as absent + assert.equal(exportInvoices({ tenant: 'acme', from: '', to: '' }).length, 5); +}); + +test('billing: export currency filter', () => { + const ids = (q) => exportInvoices({ tenant: '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' }), []); // valid currency, no matches: not an error + assert.deepEqual(ids({ currency: 'USD', from: '2026-09-15', to: '2026-09-30' }), ['inv_0002']); + for (const bad of ['JPY', 'usd', '', ' USD']) { + assert.throws(() => exportInvoices({ tenant: 'acme', currency: bad }), (e) => e.status === 400, bad); + } + // bad currency is a 400 even for a tenant with no invoices + assert.throws(() => exportInvoices({ tenant: 'nobody', currency: 'JPY' }), (e) => e.status === 400); +}); + +test('billing: csv formatting', () => { + const csv = formatInvoicesCsv(exportInvoices({ tenant: 'acme', from: '2026-09-15', to: '2026-10-01' })); + assert.equal(csv, [ + 'id,date,customer,subtotal,discount,tax,total,currency', + '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..9f1e0ab 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'); @@ -9,6 +10,18 @@ test('lib: money', () => { assert.equal(percentOf(2000, 7), 140); }); +test('lib: csv', () => { + 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\rb'), '"a\rb"'); + assert.equal(csvField(''), ''); + assert.equal(csvField(12), '12'); + assert.equal(toCsv([['a', 'b,c'], ['1', '2']]), 'a,"b,c"\n1,2\n'); + assert.equal(toCsv([]), ''); +}); + test('lib: time', () => { assert.equal(isoDate('2026-10-01T23:00:00Z'), '2026-10-01'); assert.equal(inRange('2026-09-15', '2026-09-15', '2026-09-30'), true); diff --git a/tests/server.test.js b/tests/server.test.js index e836eaa..b9991aa 100644 --- a/tests/server.test.js +++ b/tests/server.test.js @@ -17,3 +17,45 @@ 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 header = 'id,date,customer,subtotal,discount,tax,total,currency\n'; + const ids = (body) => body.split('\n').slice(1, -1).map((l) => l.split(',')[0]); + + 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.ok(r.body.startsWith(header)); + assert.ok(r.body.endsWith('\n')); + assert.deepEqual(ids(r.body), ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0003', 'inv_0004']); + assert.ok(r.body.includes('inv_0002,2026-09-15,"Smith, Jones & Co",49.99,0.00,3.50,53.49,USD\n')); + assert.ok(r.body.includes('"The ""Quick"" Shop"')); + + const g = await app.handle('GET', '/billing/invoices.csv?tenant=globex'); + assert.equal(g.body, header + 'inv_0005,2026-09-20,Northwind,80.00,8.00,14.40,86.40,GBP\n'); + + const w = await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=2026-09-15&to=2026-09-15'); + assert.deepEqual(ids(w.body), ['inv_0002', 'inv_0003']); + + const empty = await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=2030-01-01'); + assert.equal(empty.status, 200); + assert.equal(empty.body, header); + + assert.equal((await app.handle('GET', '/billing/invoices.csv')).status, 400); + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=')).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=bogus')).status, 400); + + const eur = await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=EUR'); + assert.equal(eur.status, 200); + assert.deepEqual(ids(eur.body), ['inv_0003']); + const none = await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=GBP'); + assert.equal(none.status, 200); + assert.equal(none.body, header); + 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); + + // existing routes unaffected + assert.equal((await app.handle('GET', '/billing/invoices')).status, 200); +});