diff --git a/CHANGES.md b/CHANGES.md index 7539f2e..010b6d9 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`), with optional `from`, `to` and `currency` filters. ## 3.2.0 - Returns: partial refunds. diff --git a/src/modules/billing/formatters.js b/src/modules/billing/formatters.js index f64ce28..8cac6c6 100644 --- a/src/modules/billing/formatters.js +++ b/src/modules/billing/formatters.js @@ -1,5 +1,27 @@ 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']; + +function csvField(v) { + const s = String(v); + return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +} + +export function formatInvoicesCsv(invoices) { + const lines = invoices.map((i) => [ + i.id, + isoDate(i.date), + i.customer, + formatCents(i.subtotal), + formatCents(i.discount), + formatCents(i.tax), + formatCents(i.total), + i.currency, + ].map(csvField).join(',')); + return [CSV_COLUMNS.join(','), ...lines].join('\n') + '\n'; +} 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..2a5bef1 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, isoDate } 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,25 @@ 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; + if (!/^\d{4}-\d{2}-\d{2}$/.test(v) || isNaN(new Date(v)) || isoDate(v) !== v) { + throw new ValidationError(`${key} must be a date in YYYY-MM-DD format`); + } + return v; +} + +// Invoices for the CSV export: raw integer cents, filtered by inclusive date range, sorted by date then id. +export function exportInvoices(query = {}) { + const tenant = requireString(query, 'tenant'); + const from = optionalDate(query, 'from'); + const to = optionalDate(query, 'to'); + const currency = query.currency === undefined ? undefined : validateCurrency(query); + const all = listInvoices({ tenantId: tenant }); + if (all.length === 0) throw new NotFoundError('invoices for tenant ' + tenant); + 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..e0f8991 100644 --- a/tests/billing.test.js +++ b/tests/billing.test.js @@ -1,6 +1,6 @@ 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 +17,31 @@ test('billing: invoices', () => { assert.equal(listInvoices({ tenantId: 'globex' }).length, 1); assert.throws(() => getInvoice('inv_9999'), /not found/); }); + +test('billing: exportInvoices filters, sorts and validates', () => { + assert.deepEqual(exportInvoices({ tenant: 'acme' }).map((i) => i.id), + ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0003', 'inv_0004']); + assert.deepEqual(exportInvoices({ tenant: 'acme', from: '2026-09-15', to: '2026-09-15' }).map((i) => i.id), + ['inv_0002', 'inv_0003']); + assert.deepEqual(exportInvoices({ tenant: 'acme', from: '2027-01-01' }), []); + assert.deepEqual(exportInvoices({ tenant: 'acme', currency: 'USD' }).map((i) => i.id), + ['inv_0006', 'inv_0001', 'inv_0002', 'inv_0004']); + assert.deepEqual(exportInvoices({ tenant: 'acme', currency: 'EUR' }).map((i) => i.id), ['inv_0003']); + assert.deepEqual(exportInvoices({ tenant: 'acme', currency: 'GBP' }), []); + assert.throws(() => exportInvoices({ tenant: 'acme', currency: 'JPY' }), /currency must be one of/); + assert.throws(() => exportInvoices({ tenant: 'acme', currency: 'usd' }), /currency must be one of/); + assert.throws(() => exportInvoices({ tenant: 'acme', currency: '' }), /currency must be one of/); + assert.throws(() => exportInvoices({}), /tenant is required/); + assert.throws(() => exportInvoices({ tenant: 'acme', from: '2026-02-30' }), /from must be/); + assert.throws(() => exportInvoices({ tenant: 'acme', to: 'garbage' }), /to must be/); + assert.throws(() => exportInvoices({ tenant: 'nobody' }), /not found/); +}); + +test('billing: formatInvoicesCsv quotes fields and ends with newline', () => { + const header = 'id,date,customer,subtotal,discount,tax,total,currency\n'; + assert.equal(formatInvoicesCsv([]), header); + const csv = formatInvoicesCsv([ + { id: 'a', date: '2026-01-02', customer: 'x,y "z"\nw', currency: 'USD', subtotal: 105, discount: 0, tax: 7, total: 112 }, + ]); + assert.equal(csv, header + 'a,2026-01-02,"x,y ""z""\nw",1.05,0.00,0.07,1.12,USD\n'); +}); diff --git a/tests/server.test.js b/tests/server.test.js index e836eaa..b336dec 100644 --- a/tests/server.test.js +++ b/tests/server.test.js @@ -17,3 +17,27 @@ 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 export', async () => { + const app = createApp(); + const header = 'id,date,customer,subtotal,discount,tax,total,currency\n'; + 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\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'); + const ranged = await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=2026-09-15&to=2026-09-15'); + assert.deepEqual(ranged.body.split('\n').slice(1, -1).map((l) => l.slice(0, 8)), ['inv_0002', 'inv_0003']); + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=acme&from=2027-01-01')).body, header); + const eur = await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=EUR'); + assert.equal(eur.body, header + 'inv_0003,2026-09-15,"The ""Quick"" Shop",200.00,5.00,39.00,234.00,EUR\n'); + assert.equal((await app.handle('GET', '/billing/invoices.csv?tenant=acme¤cy=GBP')).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')).status, 400); + 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=nobody')).status, 404); +});