Functional Weave
Code in TypeScript

finance.invoice.calculate

Calculate a complete invoice: line nets, VAT per line, totals and a VAT summary grouped by rate.

1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra

Pinned by 7 tests, run in TypeScript, Python and Rust · fewer than the registry now requires. 1.0.1 adds them.

What it does

This is the whole point of the registry in one function. It is about forty lines in each language and it invents no arithmetic at all: line totals, discounts, rate lookup, VAT and summation are all capabilities that already exist and are already pinned by their own vectors.

VAT is calculated per line and then grouped by rate, which is the method HMRC accepts and which keeps a line's tax reconcilable against that line. The alternative - summing nets per rate first, then taxing the group - differs by a penny often enough to matter, so the choice is recorded here rather than left to whoever writes the next invoice screen.

For example

  • calculateInvoice(lines ×3, GB, 2026-09-16) → currency GBP, lines ×3, subtotal £1,614.99, tax total £318.00, total £1,932.99, tax breakdown ×2 mixed standard, zero and discounted lines
  • calculateInvoice(lines ×1, GB, 2020-12-25) → currency GBP, lines ×1, subtotal £200.00, tax total £10.00, total £210.00, tax breakdown ×1 hospitality invoice during the covid rate cut
  • calculateInvoice(lines ×1, GB, 2009-06-01) → currency GBP, lines ×1, subtotal £100.00, tax total £15.00, total £115.00, tax breakdown ×1 the same goods invoiced in 2009 use the 2009 rate

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

export function calculateInvoice(lines: readonly InvoiceLine[], jurisdiction: string, invoiceDate: string): Invoice
linesInvoiceLine[]
jurisdictionstring
invoiceDatedatetax point: the date that decides which rates apply
returnsInvoice

The types it declares, generated into your project

/** One line as the caller bills it. */
export interface InvoiceLine {
  readonly description: string;
  readonly unitPrice: Money;
  /** negative for credit lines */
  readonly quantity: number;
  /** 1000 = 10% off */
  readonly discountBasisPoints: number;
  /** STANDARD, REDUCED, ZERO, EXEMPT or HOSPITALITY */
  readonly taxCategory: string;
}

/** One line as the invoice prints it. */
export interface CalculatedLine {
  readonly description: string;
  readonly net: Money;
  readonly tax: Money;
  readonly gross: Money;
  readonly basisPoints: number;
}

/** The VAT summary for one rate. */
export interface TaxGroup {
  readonly basisPoints: number;
  readonly taxable: Money;
  readonly tax: Money;
}

export interface Invoice {
  readonly currency: string;
  readonly lines: readonly CalculatedLine[];
  readonly subtotal: Money;
  readonly taxTotal: Money;
  readonly total: Money;
  /** one group per rate, in first-appearance order */
  readonly taxBreakdown: readonly TaxGroup[];
}

Your code names it in one line, in the file that uses it

import { calculateInvoice } from "#fune/finance.invoice.calculate@^1";
impl/typescript.ts · 63 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { lineTotal } from "./finance_invoice_line_total.ts";  ← from finance.invoice.line-total ^1.0.0 · built alongside by fune
import { addVat } from "./finance_tax_add_vat.ts";  ← from finance.tax.add-vat ^1.0.0 · built alongside by fune
import { addMoney } from "./money_add.ts";  ← from money.add ^1.0.0 · built alongside by fune
import { type Money, money } from "./money_amount.ts";  ← from money.amount ^1.0.0 · built alongside by fune
import { sumMoney } from "./money_sum.ts";  ← from money.sum ^1.0.0 · built alongside by fune
import { type InvoiceLine, type CalculatedLine, type TaxGroup, type Invoice } from "./finance_invoice_calculate_types.ts";

/**
 * Calculate a complete invoice.
 *
 * Note what this function does not contain: no multiplication, no percentages,
 * no rounding, no rate table. Each of those is a capability that is already
 * pinned by its own vectors. What is left here is the part that is genuinely
 * about invoices - the order of operations, and how tax is grouped.
 *
 * VAT is calculated per line and then grouped by rate, which keeps each line's
 * tax reconcilable against that line.
 */
export function calculateInvoice(lines: readonly InvoiceLine[], jurisdiction: string, invoiceDate: string): Invoice {
  if (lines.length === 0) {
    throw new RangeError("an invoice needs at least one line");
  }
  const currency = lines[0].unitPrice.currency;

  const calculated: CalculatedLine[] = lines.map((line) => {
    const net = lineTotal(line.unitPrice, line.quantity, line.discountBasisPoints);
    const vat = addVat(net, jurisdiction, line.taxCategory, invoiceDate);
    return {
      description: line.description,
      net: vat.net,
      tax: vat.tax,
      gross: vat.gross,
      basisPoints: vat.basisPoints,
    };
  });

  const subtotal = sumMoney(calculated.map((l) => l.net), currency);
  const taxTotal = sumMoney(calculated.map((l) => l.tax), currency);

  // Grouped by rate and ordered by rate, so the summary block on a printed
  // invoice is stable between runs and between languages.
  const groups = new Map<number, { taxable: Money; tax: Money }>();
  for (const line of calculated) {
    const current = groups.get(line.basisPoints) ?? { taxable: money(0, currency), tax: money(0, currency) };
    groups.set(line.basisPoints, {
      taxable: addMoney(current.taxable, line.net),
      tax: addMoney(current.tax, line.tax),
    });
  }

  const taxBreakdown = [...groups.entries()]
    .sort((a, b) => a[0] - b[0])
    .map(([basisPoints, group]) => ({ basisPoints, taxable: group.taxable, tax: group.tax }));

  return {
    currency,
    lines: calculated,
    subtotal,
    taxTotal,
    total: addMoney(subtotal, taxTotal),
    taxBreakdown,
  };
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 5 dependencies, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add finance.invoice.calculate
Download for TypeScript finance.invoice.calculate-1.0.0-typescript.fune · 13,906 bytes sha256 3fedfd91c614da98f0fa5a7b1dfb5f9ff1e881e89b8bee44f3410ac3a6f9e07b

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./finance.invoice.calculate-1.0.0-typescript.fune, or fetch it from a terminal with fune pull finance.invoice.calculate@1.0.0:typescript.

The whole function, every language, is one file too: finance.invoice.calculate-1.0.0.fune, 21,577 bytes, sha256 df21cb0a6c145c61a5de4151aeb3b0b11b21ea455afd665db482710d2694a6ea. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before finance.invoice.calculate

after — your function gets the result and the arguments, and returns the final result.

// fune: after finance.invoice.calculate

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace finance.invoice.line-total in finance.invoice.calculate
// fune: replace finance.tax.add-vat in finance.invoice.calculate
// fune: replace money.add in finance.invoice.calculate
// fune: replace money.amount in finance.invoice.calculate
// fune: replace money.sum in finance.invoice.calculate

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show finance.invoice.calculate --steps.

// fune: step finance.invoice.calculate after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

This version has fewer tests than the registry now requires. It was published before every function had to have 8. 1.0.1 meets it, and a project on ^1.0.0 installs that or newer.

  • calculateInvoice has 7 tests; every function needs at least 8. Add 1 more to vectors.json: the ordinary case, the boundaries (zero, negative, the largest values), the rounding edge and every error it documents
CaseArgumentsExpected
mixed standard, zero and discounted lines lines ×3, GB, 2026-09-16 → currency GBP, lines ×3, subtotal £1,614.99, tax total £318.00, total £1,932.99, tax breakdown ×2
hospitality invoice during the covid rate cut lines ×1, GB, 2020-12-25 → currency GBP, lines ×1, subtotal £200.00, tax total £10.00, total £210.00, tax breakdown ×1
the same goods invoiced in 2009 use the 2009 rate lines ×1, GB, 2009-06-01 → currency GBP, lines ×1, subtotal £100.00, tax total £15.00, total £115.00, tax breakdown ×1
a credit note is an invoice with negative quantities lines ×1, GB, 2026-09-16 → currency GBP, lines ×1, subtotal -£100.00, tax total -£20.00, total -£120.00, tax breakdown ×1
an Irish invoice uses Irish rates lines ×1, IE, 2026-09-16 → currency EUR, lines ×1, subtotal €1,000.00, tax total €230.00, total €1,230.00, tax breakdown ×1
an invoice with no lines is an error , GB, 2026-09-16 → error: at least one line
mixing currencies across lines is an error lines ×2, GB, 2026-09-16 → error: currency mismatch

More from the author

The tax point is an argument. Reprinting a 2009 invoice gives 2009 rates, because the rate lookup takes the date.

Files

PathBytes
README.md772
impl/python.py2,420
impl/rust.rs4,984
impl/typescript.ts2,440
vectors.json5,838