diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..5077045 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` + (`tenant` required; 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..adcb23a --- /dev/null +++ b/src/lib/csv.js @@ -0,0 +1,9 @@ +// Minimal RFC 4180 writer. Lines are joined with "\n" and the output always ends with one. +export function csvField(value) { + const s = String(value ?? ''); + return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +export function toCsv(header, rows) { + return [header, ...rows].map((r) => r.map(csvField).join(',')).join('\n') + '\n'; +} diff --git a/src/modules/billing/constants.js b/src/modules/billing/constants.js index 0815919..15e602f 100644 --- a/src/modules/billing/constants.js +++ b/src/modules/billing/constants.js @@ -2,3 +2,4 @@ export const TAX_REGION = process.env.TAX_REGION || 'US'; export const TAX_RATES = { US: 7, EU: 20, UK: 20 }; export const DISCOUNT_CODES = { SAVE10: { pct: 10 }, FLAT500: { cents: 500 } }; export const CURRENCIES = ['USD', 'EUR', 'GBP']; +export const INVOICE_CSV_HEADER = ['id', 'date', 'customer', 'subtotal', 'discount', 'tax', 'total', 'currency']; diff --git a/src/modules/billing/routes.js b/src/modules/billing/routes.js index 0ac3d5c..549e2f6 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 { exportInvoicesCsv, getInvoice, listInvoices } from './service.js'; import { formatInvoice } from './formatters.js'; +import { validateInvoiceExportQuery } 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(exportInvoicesCsv(validateInvoiceExportQuery(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..a2340df 100644 --- a/src/modules/billing/service.js +++ b/src/modules/billing/service.js @@ -1,8 +1,11 @@ import { NotFoundError } from '../../lib/errors.js'; import { discountFor } from './discounts.js'; import { taxFor } from './tax.js'; -import { TAX_REGION } from './constants.js'; +import { TAX_REGION, INVOICE_CSV_HEADER } from './constants.js'; import { allInvoices, findInvoice } from './repo.js'; +import { formatCents } from '../../lib/money.js'; +import { inRange } from '../../lib/time.js'; +import { toCsv } from '../../lib/csv.js'; // Prices order lines. Returns integer cents. export function priceLines(lines, { discountCode, region = TAX_REGION } = {}) { @@ -21,3 +24,18 @@ export function getInvoice(id) { export function listInvoices({ tenantId } = {}) { return allInvoices().filter((i) => !tenantId || i.tenantId === tenantId); } + +const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + +// CSV of a tenant's invoices, optionally limited to an inclusive date range and/or a currency. +// 404 only when the tenant has no invoices at all; an empty result yields just the header. +export function exportInvoicesCsv({ tenantId, from, to, currency }) { + const mine = listInvoices({ tenantId }); + if (mine.length === 0) throw new NotFoundError('tenant ' + tenantId); + const rows = 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)) + .map((i) => [i.id, i.date, i.customer, formatCents(i.subtotal), formatCents(i.discount), + formatCents(i.tax), formatCents(i.total), i.currency]); + return toCsv(INVOICE_CSV_HEADER, rows); +} diff --git a/src/modules/billing/validators.js b/src/modules/billing/validators.js index 501b848..b7e8e98 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 { 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 === '') 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 in YYYY-MM-DD format`); + } + return v; +} + +export function validateInvoiceExportQuery(query) { + return { + tenantId: requireString(query, 'tenant'), + from: optionalDate(query, 'from'), + to: optionalDate(query, 'to'), + currency: query?.currency === undefined ? undefined : validateCurrency(query), + }; +} diff --git a/tests/lib.test.js b/tests/lib.test.js index a03e86e..b7d1ff0 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,16 @@ test('lib: money', () => { assert.equal(percentOf(2000, 7), 140); }); +test('lib: csv 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(toCsv(['a', 'b'], []), 'a,b\n'); + assert.equal(toCsv(['a', 'b'], [['1', 'x,y']]), 'a,b\n1,"x,y"\n'); +}); + 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..7707a74 100644 --- a/tests/server.test.js +++ b/tests/server.test.js @@ -17,3 +17,61 @@ 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'; +const csv = (qs) => createApp().handle('GET', '/billing/invoices.csv' + qs); + +test('invoices.csv: full tenant export, sorted, quoted, money formatted', async () => { + const r = await csv('?tenant=acme'); + assert.equal(r.status, 200); + assert.equal(r.headers['content-type'], 'text/csv'); + assert.equal(r.body, CSV_HEADER + + 'inv_0006,2026-08-31,Blue Fern Ltd,30.00,0.00,2.10,32.10,USD\n' + + 'inv_0001,2026-09-02,Blue Fern Ltd,120.00,12.00,7.56,115.56,USD\n' + + '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'); +}); + +test('invoices.csv: from/to are optional and inclusive', async () => { + const ids = async (qs) => (await csv(qs)).body.split('\n').slice(1, -1).map((l) => l.split(',')[0]); + assert.deepEqual(await ids('?tenant=acme&from=2026-09-15'), ['inv_0002', 'inv_0003', 'inv_0004']); + assert.deepEqual(await ids('?tenant=acme&to=2026-09-02'), ['inv_0006', 'inv_0001']); + assert.deepEqual(await ids('?tenant=acme&from=2026-09-15&to=2026-09-15'), ['inv_0002', 'inv_0003']); +}); + +test('invoices.csv: empty range is header only; tenants are isolated', async () => { + const empty = await csv('?tenant=acme&from=2027-01-01'); + assert.equal(empty.status, 200); + assert.equal(empty.body, CSV_HEADER); + assert.equal((await csv('?tenant=acme&from=2026-10-02&to=2026-09-01')).body, CSV_HEADER); + assert.equal((await csv('?tenant=globex')).body, CSV_HEADER + 'inv_0005,2026-09-20,Northwind,80.00,8.00,14.40,86.40,GBP\n'); +}); + +test('invoices.csv: currency filter', async () => { + const ids = async (qs) => (await csv(qs)).body.split('\n').slice(1, -1).map((l) => l.split(',')[0]); + assert.deepEqual(await ids('?tenant=acme¤cy=EUR'), ['inv_0003']); + assert.deepEqual(await ids('?tenant=acme¤cy=USD'), ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0004']); + assert.deepEqual(await ids('?tenant=acme¤cy=USD&from=2026-09-10&to=2026-09-30'), ['inv_0002']); + // tenant has invoices, just none in GBP: header only, not 404 + const none = await csv('?tenant=acme¤cy=GBP'); + assert.equal(none.status, 200); + assert.equal(none.body, CSV_HEADER); +}); + +test('invoices.csv: invalid currency is a 400', async () => { + for (const c of ['JPY', 'usd', '', 'USD,EUR']) { + assert.equal((await csv('?tenant=acme¤cy=' + encodeURIComponent(c))).status, 400, c); + } + // validated before the tenant lookup + assert.equal((await csv('?tenant=nobody¤cy=JPY')).status, 400); +}); + +test('invoices.csv: error statuses', 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=abc')).status, 400); + assert.equal((await csv('?tenant=acme&to=2026-13-01')).status, 400); + assert.equal((await csv('?tenant=acme&to=2026-02-30')).status, 400); +});