diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..963ba14 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Billing: CSV export of invoices (`GET /billing/invoices.csv?tenant=&from=&to=¤cy=`). ## 3.2.0 - Returns: partial refunds. diff --git a/src/modules/billing/formatters.js b/src/modules/billing/formatters.js index f64ce28..5d0c20c 100644 --- a/src/modules/billing/formatters.js +++ b/src/modules/billing/formatters.js @@ -1,5 +1,28 @@ import { formatCents } from '../../lib/money.js'; +import { isoDate } from '../../lib/time.js'; export function formatInvoice(inv) { return { ...inv, total: formatCents(inv.total) }; } + +const CSV_COLUMNS = ['id', 'date', 'customer', 'subtotal', 'discount', 'tax', 'total', 'currency']; + +// RFC 4180: quote fields containing a comma, double quote or newline; double inner quotes. +export function csvField(value) { + const s = String(value ?? ''); + return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +export function invoicesToCsv(invoices) { + const rows = invoices.map((i) => [ + i.id, + isoDate(i.date), + i.customer, + formatCents(i.subtotal), + formatCents(i.discount), + formatCents(i.tax), + formatCents(i.total), + i.currency, + ]); + return [CSV_COLUMNS, ...rows].map((r) => r.map(csvField).join(',')).join('\n') + '\n'; +} diff --git a/src/modules/billing/routes.js b/src/modules/billing/routes.js index 0ac3d5c..f81a15c 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 { 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'; +import { validateExportQuery } 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(invoicesToCsv(exportInvoices(validateExportQuery(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..abafbb0 100644 --- a/src/modules/billing/service.js +++ b/src/modules/billing/service.js @@ -1,4 +1,5 @@ import { NotFoundError } 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'; @@ -21,3 +22,14 @@ 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); + +// A tenant's invoices within an inclusive date range, sorted by date then id. +export function exportInvoices({ tenantId, from, to, currency }) { + 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) => cmp(isoDate(a.date), isoDate(b.date)) || cmp(a.id, b.id)); +} diff --git a/src/modules/billing/validators.js b/src/modules/billing/validators.js index 501b848..a28cdc3 100644 --- a/src/modules/billing/validators.js +++ b/src/modules/billing/validators.js @@ -1,6 +1,27 @@ -import { oneOf } from '../../lib/validate.js'; +import { oneOf, requireString } from '../../lib/validate.js'; +import { ValidationError } from '../../lib/errors.js'; import { CURRENCIES } from './constants.js'; export function validateCurrency(input) { return oneOf(input, 'currency', CURRENCIES); } + +function optionalDate(query, key) { + const v = query?.[key]; + if (v === undefined || v === '') return undefined; + const valid = typeof v === 'string' + && /^\d{4}-\d{2}-\d{2}$/.test(v) + && !Number.isNaN(Date.parse(v)) + && new Date(v).toISOString().slice(0, 10) === v; + if (!valid) throw new ValidationError(`${key} must be a date in YYYY-MM-DD format`); + return v; +} + +export function validateExportQuery(query) { + return { + tenantId: requireString(query, 'tenant'), + from: optionalDate(query, 'from'), + to: optionalDate(query, 'to'), + currency: query?.currency === undefined ? undefined : oneOf(query, 'currency', CURRENCIES), + }; +} diff --git a/tests/billing.test.js b/tests/billing.test.js index 445b393..f2bcd47 100644 --- a/tests/billing.test.js +++ b/tests/billing.test.js @@ -1,6 +1,65 @@ 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, routes, csvField } from '../src/modules/billing/index.js'; + +const csvRoute = routes.find(([m, p]) => m === 'GET' && p === '/billing/invoices.csv')[2]; +const getCsv = (query) => csvRoute({ query, params: {} }); +const HEADER = 'id,date,customer,subtotal,discount,tax,total,currency'; + +test('billing csv: full tenant export is sorted, quoted and formatted', async () => { + const res = await getCsv({ tenant: 'acme' }); + assert.equal(res.status, 200); + assert.equal(res.headers['content-type'], 'text/csv'); + assert.equal(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', + ].join('\n') + '\n'); +}); + +test('billing csv: from/to are inclusive', async () => { + const res = await getCsv({ tenant: 'acme', from: '2026-09-15', to: '2026-09-15' }); + const ids = res.body.trimEnd().split('\n').slice(1).map((l) => l.split(',')[0]); + assert.deepEqual(ids, ['inv_0002', 'inv_0003']); + const onlyFrom = await getCsv({ tenant: 'acme', from: '2026-10-01' }); + assert.equal(onlyFrom.body, HEADER + '\ninv_0004,2026-10-01,Ortega Freight,1.05,0.00,0.07,1.12,USD\n'); +}); + +test('billing csv: no matches returns just the header line', async () => { + const res = await getCsv({ tenant: 'acme', from: '2030-01-01' }); + assert.equal(res.status, 200); + assert.equal(res.headers['content-type'], 'text/csv'); + assert.equal(res.body, HEADER + '\n'); +}); + +test('billing csv: errors', async () => { + assert.equal((await getCsv({})).status, 400); + assert.equal((await getCsv({ tenant: '' })).status, 400); + assert.equal((await getCsv({ tenant: 'nobody' })).status, 404); + assert.equal((await getCsv({ tenant: 'acme', from: 'garbage' })).status, 400); + assert.equal((await getCsv({ tenant: 'acme', to: '2026-02-30' })).status, 400); +}); + +test('billing csv: currency filter', async () => { + const eur = await getCsv({ tenant: 'acme', currency: '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 gbp = await getCsv({ tenant: 'acme', currency: 'GBP' }); + assert.equal(gbp.status, 200); + assert.equal(gbp.body, HEADER + '\n'); + assert.equal((await getCsv({ tenant: 'acme', currency: 'JPY' })).status, 400); + assert.equal((await getCsv({ tenant: 'acme', currency: 'usd' })).status, 400); + assert.equal((await getCsv({ tenant: 'acme', currency: '' })).status, 400); +}); + +test('billing csv: field 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"'); +}); test('billing: prices lines with discount and tax', () => { const p = priceLines([{ unitCents: 1000, qty: 2 }], { discountCode: 'save10', region: 'US' });