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 linescalculate_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 cutcalculate_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.
pub fn calculate_invoice(lines: &[InvoiceLine], jurisdiction: &str, invoice_date: &str) -> Invoice
| lines | InvoiceLine[] | |
| jurisdiction | string | |
| invoice_date | date | tax point: the date that decides which rates apply |
| returns | Invoice |
The types it declares, generated into your project
/// One line as the caller bills it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvoiceLine {
pub description: String,
pub unit_price: Money,
/// negative for credit lines
pub quantity: i64,
/// 1000 = 10% off
pub discount_basis_points: i64,
/// STANDARD, REDUCED, ZERO, EXEMPT or HOSPITALITY
pub tax_category: String,
}
/// One line as the invoice prints it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CalculatedLine {
pub description: String,
pub net: Money,
pub tax: Money,
pub gross: Money,
pub basis_points: i64,
}
/// The VAT summary for one rate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaxGroup {
pub basis_points: i64,
pub taxable: Money,
pub tax: Money,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Invoice {
pub currency: String,
pub lines: Vec<CalculatedLine>,
pub subtotal: Money,
pub tax_total: Money,
pub total: Money,
/// one group per rate, in first-appearance order
pub tax_breakdown: Vec<TaxGroup>,
}
Your code names it in one line, in the file that uses it
fune!(finance.invoice.calculate@^1); // then call calculate_invoice(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::finance_invoice_line_total::line_total; ← from finance.invoice.line-total ^1.0.0 · built alongside by fune
use super::finance_tax_add_vat::add_vat; ← from finance.tax.add-vat ^1.0.0 · built alongside by fune
use super::money_add::add_money; ← from money.add ^1.0.0 · built alongside by fune
use super::money_amount::{money, money_from_value, money_to_value, Money}; ← from money.amount ^1.0.0 · built alongside by fune
use super::money_sum::sum_money; ← from money.sum ^1.0.0 · built alongside by fune
/// 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.
///
/// # Panics
/// Panics if `lines` is empty or the lines are not all in one currency.
pub fn calculate_invoice(lines: &[InvoiceLine], jurisdiction: &str, invoice_date: &str) -> Invoice {
if lines.is_empty() {
panic!("an invoice needs at least one line");
}
let currency = lines[0].unit_price.currency.clone();
let mut calculated: Vec<CalculatedLine> = Vec::with_capacity(lines.len());
for line in lines {
let net = line_total(&line.unit_price, line.quantity, line.discount_basis_points);
let vat = add_vat(&net, jurisdiction, &line.tax_category, invoice_date);
calculated.push(CalculatedLine {
description: line.description.clone(),
net: vat.net,
tax: vat.tax,
gross: vat.gross,
basis_points: vat.basis_points,
});
}
let nets: Vec<Money> = calculated.iter().map(|l| l.net.clone()).collect();
let taxes: Vec<Money> = calculated.iter().map(|l| l.tax.clone()).collect();
let subtotal = sum_money(&nets, ¤cy);
let tax_total = sum_money(&taxes, ¤cy);
// Grouped by rate and ordered by rate, so the summary block on a printed
// invoice is stable between runs and between languages.
let mut tax_breakdown: Vec<TaxGroup> = Vec::new();
for line in &calculated {
match tax_breakdown
.iter_mut()
.find(|group| group.basis_points == line.basis_points)
{
Some(group) => {
group.taxable = add_money(&group.taxable, &line.net);
group.tax = add_money(&group.tax, &line.tax);
}
None => tax_breakdown.push(TaxGroup {
basis_points: line.basis_points,
taxable: line.net.clone(),
tax: line.tax.clone(),
}),
}
}
tax_breakdown.sort_by_key(|group| group.basis_points);
Invoice {
currency,
lines: calculated,
total: add_money(&subtotal, &tax_total),
subtotal,
tax_total,
tax_breakdown,
}
}
pub fn invoice_line_from_value(v: &Value) -> InvoiceLine {
InvoiceLine {
description: v.get("description").as_str().to_string(),
unit_price: money_from_value(v.get("unitPrice")),
quantity: v.get("quantity").as_i64(),
discount_basis_points: v.get("discountBasisPoints").as_i64(),
tax_category: v.get("taxCategory").as_str().to_string(),
}
}
pub fn invoice_to_value(invoice: &Invoice) -> Value {
Value::obj(vec![
("currency", Value::str(&invoice.currency)),
(
"lines",
Value::Arr(
invoice
.lines
.iter()
.map(|line| {
Value::obj(vec![
("description", Value::str(&line.description)),
("net", money_to_value(&line.net)),
("tax", money_to_value(&line.tax)),
("gross", money_to_value(&line.gross)),
("basisPoints", Value::Int(line.basis_points)),
])
})
.collect(),
),
),
("subtotal", money_to_value(&invoice.subtotal)),
("taxTotal", money_to_value(&invoice.tax_total)),
("total", money_to_value(&invoice.total)),
(
"taxBreakdown",
Value::Arr(
invoice
.tax_breakdown
.iter()
.map(|group| {
Value::obj(vec![
("basisPoints", Value::Int(group.basis_points)),
("taxable", money_to_value(&group.taxable)),
("tax", money_to_value(&group.tax)),
])
})
.collect(),
),
),
])
}
pub fn fune_vector(args: &[Value]) -> Value {
let lines: Vec<InvoiceLine> = args[0].as_arr().iter().map(invoice_line_from_value).collect();
invoice_to_value(&calculate_invoice(
&lines,
args[1].as_str(),
args[2].as_str(),
))
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 5 dependencies, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:
fune add finance.invoice.calculate
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./finance.invoice.calculate-1.0.1-rust.fune, or fetch it from a terminal with fune pull finance.invoice.calculate@1.0.1:rust.
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.
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Path | Bytes |
|---|---|
| README.md | 812 |
| impl/python.py | 2,420 |
| impl/rust.rs | 4,984 |
| impl/typescript.ts | 2,440 |
| vectors.json | 18,644 |