diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..f528b73 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Billing: CSV export of tenant invoices (`GET /billing/invoices.csv?tenant=&from=&to=¤cy=`). ## 3.2.0 - Returns: partial refunds. diff --git a/src/lib/csv.js b/src/lib/csv.js new file mode 100644 index 0000000..4181925 --- /dev/null +++ b/src/lib/csv.js @@ -0,0 +1,12 @@ +// Minimal RFC 4180 field quoting. Lines are joined with "\n". +export function csvField(v) { + const s = String(v ?? ''); + return /[",\r\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; +} + +// columns: header names; rows: arrays of values (already formatted) in column order. +// Always ends with a newline; zero rows gives just the header line. +export function toCsv(columns, rows) { + const lines = [columns, ...rows].map((r) => r.map(csvField).join(',')); + return lines.join('\n') + '\n'; +} diff --git a/src/lib/validate.js b/src/lib/validate.js index 0fe84c3..724af2a 100644 --- a/src/lib/validate.js +++ b/src/lib/validate.js @@ -14,6 +14,17 @@ export function optionalInt(obj, key, { min = 0, max = Number.MAX_SAFE_INTEGER } return v; } +// Optional YYYY-MM-DD date. Missing/empty -> undefined; impossible dates (2026-02-30) are rejected. +export function optionalIsoDate(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 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..1502d75 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 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..1396b4b 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 { requireString, optionalIsoDate } from '../../lib/validate.js'; +import { exportInvoices, getInvoice, listInvoices } from './service.js'; +import { formatInvoice, formatInvoicesCsv } 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 tenant = requireString(req.query, 'tenant'); + const from = optionalIsoDate(req.query, 'from'); + const to = optionalIsoDate(req.query, 'to'); + const currency = req.query.currency === undefined ? undefined : validateCurrency(req.query); + return text(formatInvoicesCsv(exportInvoices({ tenant, 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..4f0cf65 100644 --- a/src/modules/billing/service.js +++ b/src/modules/billing/service.js @@ -3,6 +3,7 @@ import { discountFor } from './discounts.js'; import { taxFor } from './tax.js'; import { TAX_REGION } from './constants.js'; import { allInvoices, findInvoice } from './repo.js'; +import { inRange } from '../../lib/time.js'; // Prices order lines. Returns integer cents. export function priceLines(lines, { discountCode, region = TAX_REGION } = {}) { @@ -21,3 +22,14 @@ export function getInvoice(id) { export function listInvoices({ tenantId } = {}) { return allInvoices().filter((i) => !tenantId || i.tenantId === tenantId); } + +// Invoices for one tenant (required), optionally limited to an inclusive date range, +// sorted by date then id. A tenant with no invoices at all is a 404; an empty range is just []. +export function exportInvoices({ tenant, from, to, currency }) { + const mine = allInvoices().filter((i) => i.tenantId === tenant); + if (mine.length === 0) throw new NotFoundError('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/tests/billing.test.js b/tests/billing.test.js index 445b393..0cdbe31 100644 --- a/tests/billing.test.js +++ b/tests/billing.test.js @@ -1,6 +1,44 @@ 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'; + +const ids = (rows) => rows.map((r) => r.id); + +test('billing: export sorts by date then id and scopes to tenant', () => { + assert.deepEqual(ids(exportInvoices({ tenant: 'acme' })), + ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0003', 'inv_0004']); + assert.deepEqual(ids(exportInvoices({ tenant: 'globex' })), ['inv_0005']); +}); + +test('billing: export range is inclusive and open-ended when bounds are omitted', () => { + assert.deepEqual(ids(exportInvoices({ tenant: 'acme', from: '2026-09-15', to: '2026-09-15' })), ['inv_0002', 'inv_0003']); + assert.deepEqual(ids(exportInvoices({ tenant: 'acme', from: '2026-10-01' })), ['inv_0004']); + assert.deepEqual(ids(exportInvoices({ tenant: 'acme', to: '2026-08-31' })), ['inv_0006']); + assert.deepEqual(exportInvoices({ tenant: 'acme', from: '2027-01-01' }), []); +}); + +test('billing: export filters by currency', () => { + assert.deepEqual(ids(exportInvoices({ tenant: 'acme', currency: 'USD' })), ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0004']); + assert.deepEqual(ids(exportInvoices({ tenant: 'acme', currency: 'EUR' })), ['inv_0003']); + assert.deepEqual(exportInvoices({ tenant: 'acme', currency: 'GBP' }), []); + assert.deepEqual(ids(exportInvoices({ tenant: 'acme', currency: 'USD', from: '2026-09-15' })), ['inv_0002', 'inv_0004']); +}); + +test('billing: export of unknown tenant is not found', () => { + assert.throws(() => exportInvoices({ tenant: 'nobody' }), /not found/); +}); + +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'); +}); 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..7240942 100644 --- a/tests/lib.test.js +++ b/tests/lib.test.js @@ -2,6 +2,31 @@ 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: csvField quoting', () => { + 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(12), '12'); +}); + +test('lib: toCsv ends with newline and handles zero rows', () => { + 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', () => { + 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-13-01', '2026-02-30', 'abc', '2026-9-1', '2026-09-15T00:00:00Z']) { + assert.throws(() => optionalIsoDate({ from: bad }, 'from'), /YYYY-MM-DD/, bad); + } +}); test('lib: money', () => { assert.equal(formatCents(105), '1.05'); diff --git a/tests/server.test.js b/tests/server.test.js index e836eaa..e675184 100644 --- a/tests/server.test.js +++ b/tests/server.test.js @@ -17,3 +17,63 @@ 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 HEADER = 'id,date,customer,subtotal,discount,tax,total,currency'; + +test('server: invoices.csv full export', async () => { + const app = createApp(); + 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')); +}); + +test('server: invoices.csv tenant isolation and date range', async () => { + const app = createApp(); + const g = await app.handle('GET', '/billing/invoices.csv?tenant=globex'); + assert.equal(g.body, HEADER + '\ninv_0005,2026-09-20,Northwind,80.00,8.00,14.40,86.40,GBP\n'); + const r = await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=2026-09-15&to=2026-09-15'); + assert.deepEqual(r.body.trim().split('\n').map((l) => l.slice(0, 8)), ['id,date,', 'inv_0002', 'inv_0003']); +}); + +test('server: invoices.csv empty range is header only, not 404', async () => { + const r = await createApp().handle('GET', '/billing/invoices.csv?tenant=acme&from=2027-01-01'); + assert.equal(r.status, 200); + assert.equal(r.headers['content-type'], 'text/csv'); + assert.equal(r.body, HEADER + '\n'); +}); + +test('server: invoices.csv currency filter', async () => { + const app = createApp(); + const eur = await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=EUR'); + assert.equal(eur.status, 200); + assert.equal(eur.body, HEADER + '\ninv_0003,2026-09-15,"The ""Quick"" Shop",200.00,5.00,39.00,234.00,EUR\n'); + const gbp = await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=GBP'); + assert.equal(gbp.status, 200); + assert.equal(gbp.body, HEADER + '\n'); + for (const bad of ['JPY', 'usd', '']) { + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=' + bad)).status, 400, bad); + } + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=nobody¤cy=EUR')).status, 404); +}); + +test('server: invoices.csv errors', async () => { + const app = createApp(); + 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?from=2026-09-01')).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=2026-02-30')).status, 400); + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=acme&to=garbage')).status, 400); + // existing routes unaffected + assert.equal((await app.handle('GET', '/billing/invoices/inv_0004')).status, 200); + assert.equal((await app.handle('GET', '/billing/invoices')).status, 200); +});