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.1 · published 2026-10-03 by charlie · Anterra

Pinned by 15 tests, run in TypeScript, Python and Rust.

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.1-typescript.fune · 28,438 bytes sha256 a96c0d9b0be312504363f9f2ee85f1e2c39ab73491cfdce34767539d0371d8a5

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

The whole function, every language, is one file too: finance.invoice.calculate-1.0.1.fune, 36,109 bytes, sha256 407c66fe0de98ea749e786a2b333280eba635925b5f685a3da36f577fedd1584. 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.

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
VAT is rounded per line, then added up: three 3p lines carry 3p of VAT, not the 2p a grouped total gives lines ×3, GB, 2026-09-16 → currency GBP, lines ×3, subtotal £0.09, tax total £0.03, total £0.12, tax breakdown ×1
the summary is ordered by rate, whatever order the lines come in lines ×3, GB, 2026-09-16 → currency GBP, lines ×3, subtotal £165.00, tax total £22.50, total £187.50, tax breakdown ×3
zero-rated and exempt lines share the 0% group lines ×2, GB, 2026-09-16 → currency GBP, lines ×2, subtotal £15.00, tax total £0.00, total £15.00, tax breakdown ×1
Show the other 5 tests
CaseArgumentsExpected
the discount is rounded before VAT: 12.5% off 9.99 is 1.25, then VAT on 8.74 lines ×1, GB, 2026-09-16 → currency GBP, lines ×1, subtotal £8.74, tax total £1.75, total £10.49, tax breakdown ×1
a line discounted by 100% is free and carries no VAT lines ×1, GB, 2026-09-16 → currency GBP, lines ×1, subtotal £0.00, tax total £0.00, total £0.00, tax breakdown ×1
a return that cancels a sale leaves a zero invoice with a zero group lines ×2, GB, 2026-09-16 → currency GBP, lines ×2, subtotal £0.00, tax total £0.00, total £0.00, tax breakdown ×1
a tax category with no rate is an error lines ×1, GB, 2026-09-16 → error: no VAT rule
a discount over 100% is an error lines ×1, GB, 2026-09-16 → error: must be between 0 and 10000

More from the author

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

1.0.1 adds tests; behaviour unchanged.

Files

PathBytes
README.md812
impl/python.py2,420
impl/rust.rs4,984
impl/typescript.ts2,440
vectors.json18,644