Functional Weave
Code in Python

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

  • calculate_invoice(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
  • calculate_invoice(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
  • calculate_invoice(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.

def calculate_invoice(lines: Sequence[InvoiceLine], jurisdiction: str, invoice_date: str) -> Invoice
linesInvoiceLine[]
jurisdictionstring
invoice_datedatetax point: the date that decides which rates apply
returnsInvoice

The types it declares, generated into your project

@dataclass(frozen=True)
class InvoiceLine:
    """One line as the caller bills it."""

    description: str
    unit_price: Money
    #: negative for credit lines
    quantity: int
    #: 1000 = 10% off
    discount_basis_points: int
    #: STANDARD, REDUCED, ZERO, EXEMPT or HOSPITALITY
    tax_category: str

@dataclass(frozen=True)
class CalculatedLine:
    """One line as the invoice prints it."""

    description: str
    net: Money
    tax: Money
    gross: Money
    basis_points: int

@dataclass(frozen=True)
class TaxGroup:
    """The VAT summary for one rate."""

    basis_points: int
    taxable: Money
    tax: Money

@dataclass(frozen=True)
class Invoice:
    currency: str
    lines: List[CalculatedLine]
    subtotal: Money
    tax_total: Money
    total: Money
    #: one group per rate, in first-appearance order
    tax_breakdown: List[TaxGroup]

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

from fune.finance.invoice.calculate import calculate_invoice  # finance.invoice.calculate@^1
impl/python.py · 62 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.

from typing import List, Sequence

from .finance_invoice_calculate_types import InvoiceLine, CalculatedLine, TaxGroup, Invoice
from .finance_invoice_line_total import line_total  ← from finance.invoice.line-total ^1.0.0 · built alongside by fune
from .finance_tax_add_vat import add_vat  ← from finance.tax.add-vat ^1.0.0 · built alongside by fune
from .money_add import add_money  ← from money.add ^1.0.0 · built alongside by fune
from .money_amount import Money, money  ← from money.amount ^1.0.0 · built alongside by fune
from .money_sum import sum_money  ← from money.sum ^1.0.0 · built alongside by fune


def calculate_invoice(lines: Sequence[InvoiceLine], jurisdiction: str, invoice_date: str) -> Invoice:
    """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.
    """
    if len(lines) == 0:
        raise ValueError("an invoice needs at least one line")
    currency = lines[0].unit_price.currency

    calculated: List[CalculatedLine] = []
    for line in lines:
        net = line_total(line.unit_price, line.quantity, line.discount_basis_points)
        vat = add_vat(net, jurisdiction, line.tax_category, invoice_date)
        calculated.append(
            CalculatedLine(
                description=line.description,
                net=vat.net,
                tax=vat.tax,
                gross=vat.gross,
                basis_points=vat.basis_points,
            )
        )

    subtotal = sum_money([line.net for line in calculated], currency)
    tax_total = sum_money([line.tax for line in calculated], currency)

    # Grouped by rate and ordered by rate, so the summary block on a printed
    # invoice is stable between runs and between languages.
    groups = {}
    for line in calculated:
        taxable, tax = groups.get(line.basis_points, (money(0, currency), money(0, currency)))
        groups[line.basis_points] = (add_money(taxable, line.net), add_money(tax, line.tax))

    tax_breakdown = [
        TaxGroup(basis_points=basis_points, taxable=taxable, tax=tax)
        for basis_points, (taxable, tax) in sorted(groups.items())
    ]

    return Invoice(
        currency=currency,
        lines=calculated,
        subtotal=subtotal,
        tax_total=tax_total,
        total=add_money(subtotal, tax_total),
        tax_breakdown=tax_breakdown,
    )

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 5 dependencies, pins them in fune.lock, downloads only the Python 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 Python finance.invoice.calculate-1.0.1-python.fune · 28,403 bytes sha256 25077cef368ccb4c7a57dd64d748c80f99504e69089ee796b2bdf966594b7985

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

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