Disbursements and recharges
BodySplits a professional-services invoice's expenses into the two VAT treatments. A recharge is a cost of your own service: it takes the main supply's VAT rate on what you are out of pocket, net of input VAT you reclaimed and including tax you could not, so a zero-rated fare or exempt postage recharged becomes standard-rated. A disbursement is paid as the client's agent at exact cost, outside the scope of VAT, and listed after the recharges' VAT total. An item marked as paid as agent is moved to the recharges with a printed note, or refused in strict mode, when it carries a markup, input VAT you reclaimed, or a category HMRC treats as your own cost such as travel or electronic search fees. Foreign receipts are converted at the rate for the expense date and print the original amount, rate and converted figure. VAT is worked once on the recharges' net, half away from zero. US invoices skip VAT and split on a per-line taxable flag. All of it is one deriver.
npx dxcl add disbursements-and-recharges invoice.jurisdiction Vorschaudaten
das JSON, mit dem diese Vorschau gebaut wurde{
"invoice": {
"jurisdiction": "UK",
"currency": "GBP",
"mainSupplyVatRate": 20,
"expenses": [
{
"date": "2026-10-20",
"description": "Stamp Duty Land Tax on the purchase of Unit 4, Riverside Commercial Park",
"net": 487250,
"supplierName": "HM Revenue & Customs",
"paidAsAgent": true
},
{
"date": "2026-10-07",
"description": "Return rail fare, London Euston to Manchester Piccadilly, for the site inspection",
"category": "travel",
"net": 382.4,
"paidAsAgent": true
},
{
"date": "2026-10-02",
"description": "Court issue fee, claim form, Business and Property Courts",
"category": "court-fee",
"net": 10000,
"supplierName": "HM Courts & Tribunals Service",
"paidAsAgent": true
},
{
"date": "2026-10-08",
"description": "Hotel, two nights, Frankfurt am Main, for the witness interviews",
"category": "accommodation",
"currency": "EUR",
"net": 1250,
"irrecoverableTax": 87.5,
"fxRate": 0.8571
},
{
"date": "2026-10-13",
"description": "Electronic local authority and drainage searches, 14 registered titles",
"category": "electronic-search",
"net": 2940,
"supplierName": "Northgate Property Searches Ltd",
"paidAsAgent": true
},
{
"date": "2026-10-06",
"description": "HM Land Registry official copies and title plans, 14 registered titles",
"category": "land-registry",
"net": 147,
"supplierName": "HM Land Registry",
"paidAsAgent": true
},
{
"date": "2026-10-15",
"description": "Printing and binding of eight lever-arch trial bundles",
"category": "printing",
"net": 1184.6,
"inputVatReclaimed": 236.92
},
{
"date": "2026-10-21",
"description": "Counsel's fee for advice on the lease and rent review",
"net": 18750,
"supplierName": "Three Crowns Lane Chambers",
"paidAsAgent": true
},
{
"date": "2026-10-17",
"description": "Translation of German witness statements into English",
"currency": "EUR",
"net": 4800,
"fxRate": 0.8569,
"markupPercent": 10
}
]
}
} {
"invoice": {
"jurisdiction": "EU",
"currency": "GBP",
"mainSupplyVatRate": 20,
"expenses": [
{
"date": "2026-10-20",
"description": "Stamp Duty Land Tax on the purchase of Unit 4, Riverside Commercial Park",
"net": 487250,
"supplierName": "HM Revenue & Customs",
"paidAsAgent": true
},
{
"date": "2026-10-07",
"description": "Return rail fare, London Euston to Manchester Piccadilly, for the site inspection",
"category": "travel",
"net": 382.4,
"paidAsAgent": true
},
{
"date": "2026-10-02",
"description": "Court issue fee, claim form, Business and Property Courts",
"category": "court-fee",
"net": 10000,
"supplierName": "HM Courts & Tribunals Service",
"paidAsAgent": true
},
{
"date": "2026-10-08",
"description": "Hotel, two nights, Frankfurt am Main, for the witness interviews",
"category": "accommodation",
"currency": "EUR",
"net": 1250,
"irrecoverableTax": 87.5,
"fxRate": 0.8571
},
{
"date": "2026-10-13",
"description": "Electronic local authority and drainage searches, 14 registered titles",
"category": "electronic-search",
"net": 2940,
"supplierName": "Northgate Property Searches Ltd",
"paidAsAgent": true
},
{
"date": "2026-10-06",
"description": "HM Land Registry official copies and title plans, 14 registered titles",
"category": "land-registry",
"net": 147,
"supplierName": "HM Land Registry",
"paidAsAgent": true
},
{
"date": "2026-10-15",
"description": "Printing and binding of eight lever-arch trial bundles",
"category": "printing",
"net": 1184.6,
"inputVatReclaimed": 236.92
},
{
"date": "2026-10-21",
"description": "Counsel's fee for advice on the lease and rent review",
"net": 18750,
"supplierName": "Three Crowns Lane Chambers",
"paidAsAgent": true
},
{
"date": "2026-10-17",
"description": "Translation of German witness statements into English",
"currency": "EUR",
"net": 4800,
"fxRate": 0.8569,
"markupPercent": 10
}
]
}
} {
"invoice": {
"jurisdiction": "DE",
"currency": "GBP",
"mainSupplyVatRate": 20,
"expenses": [
{
"date": "2026-10-20",
"description": "Stamp Duty Land Tax on the purchase of Unit 4, Riverside Commercial Park",
"net": 487250,
"supplierName": "HM Revenue & Customs",
"paidAsAgent": true
},
{
"date": "2026-10-07",
"description": "Return rail fare, London Euston to Manchester Piccadilly, for the site inspection",
"category": "travel",
"net": 382.4,
"paidAsAgent": true
},
{
"date": "2026-10-02",
"description": "Court issue fee, claim form, Business and Property Courts",
"category": "court-fee",
"net": 10000,
"supplierName": "HM Courts & Tribunals Service",
"paidAsAgent": true
},
{
"date": "2026-10-08",
"description": "Hotel, two nights, Frankfurt am Main, for the witness interviews",
"category": "accommodation",
"currency": "EUR",
"net": 1250,
"irrecoverableTax": 87.5,
"fxRate": 0.8571
},
{
"date": "2026-10-13",
"description": "Electronic local authority and drainage searches, 14 registered titles",
"category": "electronic-search",
"net": 2940,
"supplierName": "Northgate Property Searches Ltd",
"paidAsAgent": true
},
{
"date": "2026-10-06",
"description": "HM Land Registry official copies and title plans, 14 registered titles",
"category": "land-registry",
"net": 147,
"supplierName": "HM Land Registry",
"paidAsAgent": true
},
{
"date": "2026-10-15",
"description": "Printing and binding of eight lever-arch trial bundles",
"category": "printing",
"net": 1184.6,
"inputVatReclaimed": 236.92
},
{
"date": "2026-10-21",
"description": "Counsel's fee for advice on the lease and rent review",
"net": 18750,
"supplierName": "Three Crowns Lane Chambers",
"paidAsAgent": true
},
{
"date": "2026-10-17",
"description": "Translation of German witness statements into English",
"currency": "EUR",
"net": 4800,
"fxRate": 0.8569,
"markupPercent": 10
}
]
}
} {
"invoice": {
"jurisdiction": "FR",
"currency": "GBP",
"mainSupplyVatRate": 20,
"expenses": [
{
"date": "2026-10-20",
"description": "Stamp Duty Land Tax on the purchase of Unit 4, Riverside Commercial Park",
"net": 487250,
"supplierName": "HM Revenue & Customs",
"paidAsAgent": true
},
{
"date": "2026-10-07",
"description": "Return rail fare, London Euston to Manchester Piccadilly, for the site inspection",
"category": "travel",
"net": 382.4,
"paidAsAgent": true
},
{
"date": "2026-10-02",
"description": "Court issue fee, claim form, Business and Property Courts",
"category": "court-fee",
"net": 10000,
"supplierName": "HM Courts & Tribunals Service",
"paidAsAgent": true
},
{
"date": "2026-10-08",
"description": "Hotel, two nights, Frankfurt am Main, for the witness interviews",
"category": "accommodation",
"currency": "EUR",
"net": 1250,
"irrecoverableTax": 87.5,
"fxRate": 0.8571
},
{
"date": "2026-10-13",
"description": "Electronic local authority and drainage searches, 14 registered titles",
"category": "electronic-search",
"net": 2940,
"supplierName": "Northgate Property Searches Ltd",
"paidAsAgent": true
},
{
"date": "2026-10-06",
"description": "HM Land Registry official copies and title plans, 14 registered titles",
"category": "land-registry",
"net": 147,
"supplierName": "HM Land Registry",
"paidAsAgent": true
},
{
"date": "2026-10-15",
"description": "Printing and binding of eight lever-arch trial bundles",
"category": "printing",
"net": 1184.6,
"inputVatReclaimed": 236.92
},
{
"date": "2026-10-21",
"description": "Counsel's fee for advice on the lease and rent review",
"net": 18750,
"supplierName": "Three Crowns Lane Chambers",
"paidAsAgent": true
},
{
"date": "2026-10-17",
"description": "Translation of German witness statements into English",
"currency": "EUR",
"net": 4800,
"fxRate": 0.8569,
"markupPercent": 10
}
]
}
} Aufgelöste Nodes
was ein Renderer erhält — 1 Nodesdisbursements-and-recharges section disbursements-and-recharges section disbursements-and-recharges section disbursements-and-recharges section Die Dateien
was die Installation schreibt; die gewählte Datei ist die Komponentenodes/disbursements-and-recharges.node.tsx import { Cell, type Nodes, Paragraph, Row, Section, Table, useDeriver, useState } from "docxcelerate/template";
import disbursementsAndRecharges from "../derivers/disbursements-and-recharges.deriver.ts";
/**
* A professional-services invoice section that splits the firm's expenses into
* the two VAT treatments the law recognises and prints each as its own block
* with its own total.
*
* A recharge is a cost the firm incurred in making its own supply. It takes the
* main supply's VAT rate on what the firm is out of pocket: net of input VAT it
* reclaimed, including tax it could not. A disbursement is a payment made as the
* client's agent at exact cost (HMRC Notice 700 s.25; Directive 2006/112/EC
* Art 79(c)): outside the scope of VAT, printed with no VAT, and listed after the
* recharges' VAT total.
*
* Why agents get this wrong: they put every expense in one list, then add VAT to
* everything (overcharging genuine disbursements) or to nothing (undercharging
* recharges, the error HMRC assesses four years back). They pass the receipt's
* own VAT rate through, keep a markup on a "disbursement", and convert foreign
* receipts at the invoice-date rate.
*
* Decisions already made for you:
*
* - An item is a disbursement only when it is marked `paidAsAgent` and nothing
* contradicts that. A markup, input VAT the firm reclaimed, or a category HMRC
* treats as the firm's own cost (travel, subsistence, postage, electronic
* search fees since Brabners) moves it to the recharges with a printed note, or
* makes `strict` throw.
* - Recharges never inherit the receipt's rate; they always take the main
* supply's. A zero-rated fare recharged becomes standard-rated.
* - Foreign receipts are converted at the rate given for the expense date, and
* the original amount, the rate and the converted figure are all printed.
* - VAT is worked once on the recharges' net, half away from zero, not per line.
* - US invoices skip VAT and split on each line's `taxable` flag.
* - Disbursements are never folded together: each must be itemised.
*
* All of it is decided in one deriver, because every step does arithmetic,
* sorting or date formatting on request data, and publishing refuses all of
* those. The node computes nothing: it branches on the deriver's result with
* every test written inline so a publish build keeps each arm.
*
* The lines are fixed slots (8 recharges, 6 disbursements) rather than a
* `.map()`. The resolver reads a published loop's collection from request data
* and ignores the derived scope, so a `.map()` over the deriver's rows would
* publish and then resolve to no rows.
*
* The node publishes 20 branches: the section, the two blocks, eight recharge
* rows, the two VAT rows, six disbursement rows and the notes. A document that
* also carries tax-treatment-notice (15) will need `branchLimit` raised above the
* default 32.
*
* Installed by `dxcl add disbursements-and-recharges`.
*/
/** What this component reads. Add these fields to your document data type. */
export interface DisbursementsAndRechargesData {
invoice: {
/**
* Whose rules apply. `UK` and `EU` apply the disbursement test and charge VAT on
* recharges. `DE` and `FR` are read as `EU`, so a document that also uses
* invoice-document-type shares one field. `US` skips all VAT logic and splits on
* each expense's `taxable` flag. Required whenever there are expenses: anything
* else throws.
*/
jurisdiction: "UK" | "EU" | "DE" | "FR" | "US";
/**
* The invoice's ISO 4217 currency. Every figure is printed in it, and it sets the
* minor units. Compared upper-cased. Required whenever there are expenses: throws
* when missing or not a code Intl knows.
*/
currency: string;
/**
* VAT rate of the main supply (the firm's fees), as a percentage: 20, 5, 0, 8.5.
* At most two decimal places. Every recharge takes this rate. `null` means the
* fees carry no VAT on this invoice (exempt, or reverse-charged to a business
* customer abroad). Recharges then follow the same treatment: no VAT row, and the
* block says why. Required (number or null) for UK/EU; throws when undefined,
* negative, non-finite or more than 2 dp. Ignored for US.
*/
mainSupplyVatRate: number | null;
/**
* Every expense to pass on, in any order. Each block prints them by date, with
* ties in input order. Missing or empty prints nothing, and then nothing else on
* `invoice` is read or validated.
*/
expenses?: Array<{
/** The day the cost was incurred, ISO 8601; a time after the date is ignored.
* Required: throws when missing or not YYYY-MM-DD. Also the day `fxRate` must be for. */
date: string;
/** What it was, printed as given. Required: throws when missing or blank. */
description: string;
/**
* Recognised values, compared exactly: "travel", "subsistence", "accommodation",
* "postage", "telephone", "photocopying", "printing", "electronic-search".
* Under UK/EU these are the firm's own costs, so an item marked `paidAsAgent`
* with one of them is reclassified as a recharge. Any other value, or missing,
* has no effect. Never printed.
*/
category?: string;
/**
* The receipt amount before any VAT or sales tax on it, in the expense's
* currency, in major units (12.50). Negative is a refund of an expense and is
* allowed. Required: throws when not finite, or when it has more decimals than
* the currency has minor units.
*/
net: number;
/**
* VAT on the receipt that the firm reclaimed as input tax. It is never charged
* on and never printed. Under UK/EU, a value above 0 on an item marked
* `paidAsAgent` reclassifies it: a firm that reclaimed the VAT received the
* supply itself. Missing means 0. Throws when negative or when it has too many
* decimals.
*/
inputVatReclaimed?: number;
/**
* Tax on the receipt the firm paid and could not reclaim (foreign VAT, US sales
* tax). It is part of the cost: added to `net` before conversion, markup and
* VAT. Missing means 0. Throws when negative or when it has too many decimals.
*/
irrecoverableTax?: number;
/** ISO 4217 code of the receipt. Missing means `invoice.currency`. Compared upper-cased. */
currency?: string;
/**
* Units of `invoice.currency` per one unit of the expense currency, on `date`
* (1 EUR = 0.8571 GBP is 0.8571). At most 6 decimal places. It is printed as
* given. Required when the currencies differ: throws when missing, 0 or less,
* non-finite or more than 6 dp. Ignored when they match.
*/
fxRate?: number;
/**
* Handling markup, as a percentage of the converted cost. At most 2 dp. Above 0
* makes the item a recharge in every jurisdiction: a disbursement is passed on
* at exact cost. Missing means 0. Throws when negative.
*/
markupPercent?: number;
/**
* Whether the firm paid this as the client's agent: the client received the
* supply, the firm recorded it outside its own costs (a suspense account), and
* it is passed on at exact cost. Missing means false, so the item is a
* recharge, because undercharging VAT is the error that gets assessed. Ignored
* for US.
*/
paidAsAgent?: boolean;
/** Printed in brackets after the description when given and not blank. */
supplierName?: string;
/**
* US only: whether the state taxes this reimbursed expense. Missing means not
* taxable, and a note says so (strict throws). Ignored outside the US.
*/
taxable?: boolean;
}>;
};
}
/** Props for {@linkcode DisbursementsAndRecharges}. */
export interface DisbursementsAndRechargesProps {
/**
* Refuse to reclassify. When true, the deriver throws on the first item that would
* get a note (a reclassified disbursement, or a US item with no `taxable`), naming
* its index and reason. Defaults to false.
*/
strict?: boolean;
}
/**
* Prints the recharges, their VAT, and the disbursements after them. Prints
* nothing when there are no expenses, or none worth a line.
*/
export const DisbursementsAndRecharges: Nodes<DisbursementsAndRechargesProps> = async ({ strict }) => {
const [invoice] = useState((d: DisbursementsAndRechargesData) => d.invoice);
const p = await useDeriver(disbursementsAndRecharges, [invoice, strict === true]);
return (
<>
{p.any && (
<Section id="disbursements-and-recharges" title="Expenses">
{p.hasRecharges && (
<Section id="disbursements-and-recharges-recharges" title={p.rechargeTitle}>
<Paragraph id="disbursements-and-recharges-recharges-statement">{p.rechargeStatement}</Paragraph>
<Table
id="disbursements-and-recharges-recharges-lines"
columns={[{ width: 26 }, { width: "auto" }, { width: 32, align: "right" }]}
>
<Row id="disbursements-and-recharges-recharges-header" header>
<Cell>Date</Cell>
<Cell>Description</Cell>
<Cell>{p.rechargeAmountHeading}</Cell>
</Row>
{p.recharges[0].description && (
<Row id="disbursements-and-recharges-recharge-1">
<Cell>{p.recharges[0].date}</Cell>
<Cell>{p.recharges[0].description}</Cell>
<Cell>{p.recharges[0].amount}</Cell>
</Row>
)}
{p.recharges[1].description && (
<Row id="disbursements-and-recharges-recharge-2">
<Cell>{p.recharges[1].date}</Cell>
<Cell>{p.recharges[1].description}</Cell>
<Cell>{p.recharges[1].amount}</Cell>
</Row>
)}
{p.recharges[2].description && (
<Row id="disbursements-and-recharges-recharge-3">
<Cell>{p.recharges[2].date}</Cell>
<Cell>{p.recharges[2].description}</Cell>
<Cell>{p.recharges[2].amount}</Cell>
</Row>
)}
{p.recharges[3].description && (
<Row id="disbursements-and-recharges-recharge-4">
<Cell>{p.recharges[3].date}</Cell>
<Cell>{p.recharges[3].description}</Cell>
<Cell>{p.recharges[3].amount}</Cell>
</Row>
)}
{p.recharges[4].description && (
<Row id="disbursements-and-recharges-recharge-5">
<Cell>{p.recharges[4].date}</Cell>
<Cell>{p.recharges[4].description}</Cell>
<Cell>{p.recharges[4].amount}</Cell>
</Row>
)}
{p.recharges[5].description && (
<Row id="disbursements-and-recharges-recharge-6">
<Cell>{p.recharges[5].date}</Cell>
<Cell>{p.recharges[5].description}</Cell>
<Cell>{p.recharges[5].amount}</Cell>
</Row>
)}
{p.recharges[6].description && (
<Row id="disbursements-and-recharges-recharge-7">
<Cell>{p.recharges[6].date}</Cell>
<Cell>{p.recharges[6].description}</Cell>
<Cell>{p.recharges[6].amount}</Cell>
</Row>
)}
{p.recharges[7].description && (
<Row id="disbursements-and-recharges-recharge-8">
<Cell>{p.recharges[7].date}</Cell>
<Cell>{p.recharges[7].description}</Cell>
<Cell>{p.recharges[7].amount}</Cell>
</Row>
)}
{p.showVat && (
<Row id="disbursements-and-recharges-recharges-net">
<Cell></Cell>
<Cell>Net total</Cell>
<Cell>{p.rechargeNet}</Cell>
</Row>
)}
{p.showVat && (
<Row id="disbursements-and-recharges-recharges-vat">
<Cell></Cell>
<Cell>{p.vatLabel}</Cell>
<Cell>{p.vat}</Cell>
</Row>
)}
<Row id="disbursements-and-recharges-recharges-total">
<Cell></Cell>
<Cell>{p.rechargeTotalLabel}</Cell>
<Cell>{p.rechargeTotal}</Cell>
</Row>
</Table>
</Section>
)}
{p.hasDisbursements && (
<Section id="disbursements-and-recharges-disbursements" title={p.disbursementTitle}>
<Paragraph id="disbursements-and-recharges-disbursements-statement">{p.disbursementStatement}</Paragraph>
<Table
id="disbursements-and-recharges-disbursements-lines"
columns={[{ width: 26 }, { width: "auto" }, { width: 32, align: "right" }]}
>
<Row id="disbursements-and-recharges-disbursements-header" header>
<Cell>Date</Cell>
<Cell>Description</Cell>
<Cell>Amount</Cell>
</Row>
{p.disbursements[0].description && (
<Row id="disbursements-and-recharges-disbursement-1">
<Cell>{p.disbursements[0].date}</Cell>
<Cell>{p.disbursements[0].description}</Cell>
<Cell>{p.disbursements[0].amount}</Cell>
</Row>
)}
{p.disbursements[1].description && (
<Row id="disbursements-and-recharges-disbursement-2">
<Cell>{p.disbursements[1].date}</Cell>
<Cell>{p.disbursements[1].description}</Cell>
<Cell>{p.disbursements[1].amount}</Cell>
</Row>
)}
{p.disbursements[2].description && (
<Row id="disbursements-and-recharges-disbursement-3">
<Cell>{p.disbursements[2].date}</Cell>
<Cell>{p.disbursements[2].description}</Cell>
<Cell>{p.disbursements[2].amount}</Cell>
</Row>
)}
{p.disbursements[3].description && (
<Row id="disbursements-and-recharges-disbursement-4">
<Cell>{p.disbursements[3].date}</Cell>
<Cell>{p.disbursements[3].description}</Cell>
<Cell>{p.disbursements[3].amount}</Cell>
</Row>
)}
{p.disbursements[4].description && (
<Row id="disbursements-and-recharges-disbursement-5">
<Cell>{p.disbursements[4].date}</Cell>
<Cell>{p.disbursements[4].description}</Cell>
<Cell>{p.disbursements[4].amount}</Cell>
</Row>
)}
{p.disbursements[5].description && (
<Row id="disbursements-and-recharges-disbursement-6">
<Cell>{p.disbursements[5].date}</Cell>
<Cell>{p.disbursements[5].description}</Cell>
<Cell>{p.disbursements[5].amount}</Cell>
</Row>
)}
<Row id="disbursements-and-recharges-disbursements-total">
<Cell></Cell>
<Cell>{p.disbursementTotalLabel}</Cell>
<Cell>{p.disbursementTotal}</Cell>
</Row>
</Table>
</Section>
)}
{p.notes && <Paragraph id="disbursements-and-recharges-notes">{p.notes}</Paragraph>}
</Section>
)}
</>
);
}; derivers/disbursements-and-recharges.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Splits an invoice's expenses into recharges and disbursements, prices each
* block, and writes the wording. Installed by `dxcl add disbursements-and-recharges`.
*
* It is self-contained on purpose: it travels to the engine as source text, so
* a module-level constant or helper would be a ReferenceError there. Every
* helper and list is declared inside `run`.
*/
export default deriver({
name: "disbursementsAndRecharges",
run: (invoice: unknown, strict: unknown) => {
const inv = invoice as any;
const strictMode = strict === true;
const SLOTS_A = 8;
const SLOTS_B = 6;
const empty = () => ({ date: "", description: "", amount: "", amountMinor: 0 });
const fill = (rows: any[], n: number) => {
const slots = rows.slice();
while (slots.length < n) slots.push(empty());
return slots;
};
const nothing = () => ({
any: false, hasRecharges: false, hasDisbursements: false, showVat: false,
rechargeTitle: "", rechargeStatement: "", rechargeAmountHeading: "",
recharges: fill([], SLOTS_A),
rechargeNet: "", vatLabel: "", vat: "", rechargeTotal: "", rechargeTotalLabel: "",
disbursementTitle: "", disbursementStatement: "",
disbursements: fill([], SLOTS_B),
disbursementTotal: "", disbursementTotalLabel: "",
notes: "",
rechargeNetMinor: 0, vatMinor: 0, rechargeTotalMinor: 0, disbursementTotalMinor: 0,
});
// Nothing to print means nothing else on `invoice` is read.
const expenses = inv?.expenses;
if (!Array.isArray(expenses) || expenses.length === 0) return nothing();
const big = (n: number) => BigInt(n);
// Half away from zero, symmetric for credits, on exact integers (d > 0).
const roundHalfAway = (n: bigint, d: bigint): bigint => {
const abs = n < big(0) ? -n : n;
const q = (big(2) * abs + d) / (big(2) * d);
return n < big(0) ? -q : q;
};
// A decimal becomes an integer at `dp` places, or throws: no float rounding survives.
const scaled = (v: unknown, dp: number, field: string, what: string): number => {
if (typeof v !== "number" || !Number.isFinite(v)) throw new Error(field + " must be a finite number");
const s = v * 10 ** dp;
const m = Math.round(s);
if (Math.abs(s - m) > 1e-6) throw new Error(field + " has more decimals than " + what + " allows");
return m;
};
const jurisdictions = ["UK", "EU", "DE", "FR", "US"];
if (!jurisdictions.includes(inv.jurisdiction)) {
throw new Error("invoice.jurisdiction must be one of " + jurisdictions.join(", "));
}
const us = inv.jurisdiction === "US";
const locale = us ? "en-US" : "en-GB";
const moneyOf = (code: unknown, field: string) => {
if (typeof code !== "string") throw new Error(field + " must be an ISO 4217 code");
const cur = code.toUpperCase();
try {
if (!Intl.supportedValuesOf("currency").includes(cur)) throw new Error("unknown");
const nf = new Intl.NumberFormat(locale, { style: "currency", currency: cur });
return { cur, nf, e: nf.resolvedOptions().maximumFractionDigits as number };
} catch {
throw new Error(field + " must be an ISO 4217 code");
}
};
const home = moneyOf(inv.currency, "invoice.currency");
const fmt = (m: { nf: Intl.NumberFormat; e: number }, minor: bigint | number) =>
m.nf.format(Number(minor) / 10 ** m.e);
const rate = inv.mainSupplyVatRate;
let rateHundredths = 0;
if (!us) {
if (rate !== null) {
if (typeof rate !== "number" || !Number.isFinite(rate) || rate < 0) {
throw new Error("invoice.mainSupplyVatRate must be null or a number of 0 or more");
}
rateHundredths = scaled(rate, 2, "invoice.mainSupplyVatRate", "two places");
}
}
// The firm's own costs: an item marked paid-as-agent in one of these is a recharge.
// The electronic-search entry is Brabners (UK FTT, 2017). This is the list an owner edits.
const ownCosts: Record<string, string> = {
"travel": "travel",
"subsistence": "subsistence",
"accommodation": "accommodation",
"postage": "postage",
"telephone": "telephone calls",
"photocopying": "photocopying",
"printing": "printing",
"electronic-search": "electronic search fees",
};
const dates = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeZone: "UTC" });
type Item = { i: number; date: string; description: string; amount: bigint; note: string; block: "A" | "B" };
const items: Item[] = [];
expenses.forEach((x: any, i: number) => {
const f = "invoice.expenses[" + i + "]";
const date = typeof x?.date === "string" ? x.date.slice(0, 10) : "";
const d = /^\d{4}-\d{2}-\d{2}$/.test(date) ? new Date(date + "T00:00:00Z") : null;
if (!d || Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== date) {
throw new Error(f + ".date must be an ISO 8601 date");
}
if (typeof x.description !== "string" || x.description.trim() === "") {
throw new Error(f + ".description is required");
}
const src = x.currency === undefined ? home : moneyOf(x.currency, f + ".currency");
const nonNeg = (v: unknown, field: string) => {
if (v === undefined) return 0;
if (typeof v === "number" && v < 0) throw new Error(field + " must not be negative");
return scaled(v, src.e, field, src.cur);
};
const net = scaled(x.net, src.e, f + ".net", src.cur);
const reclaimed = nonNeg(x.inputVatReclaimed, f + ".inputVatReclaimed");
const irrecoverable = nonNeg(x.irrecoverableTax, f + ".irrecoverableTax");
let markup = 0;
if (x.markupPercent !== undefined) {
if (typeof x.markupPercent === "number" && x.markupPercent < 0) {
throw new Error(f + ".markupPercent must not be negative");
}
markup = scaled(x.markupPercent, 2, f + ".markupPercent", "two places");
}
const costSrc = net + irrecoverable;
const foreign = src.cur !== home.cur;
let converted = big(costSrc);
let fxText = "";
if (foreign) {
const fx = x.fxRate;
if (typeof fx !== "number" || !Number.isFinite(fx) || fx <= 0) {
throw new Error(f + ".fxRate must be a number above 0 when the currency differs");
}
const micros = scaled(fx, 6, f + ".fxRate", "six places");
converted = roundHalfAway(
big(costSrc) * big(micros) * big(10) ** big(home.e),
big(10) ** big(6) * big(10) ** big(src.e),
);
fxText = ": " + fmt(src, costSrc) + " at " + String(fx) + " = " + fmt(home, converted);
}
const amount = roundHalfAway(converted * big(10000 + markup), big(10000));
if (amount === big(0)) return;
let block: "A" | "B";
let note = "";
const name = x.description as string;
if (us) {
block = x.taxable === true ? "A" : "B";
if (x.taxable === undefined) {
if (strictMode) {
throw new Error(
"disbursementsAndRecharges: " + f + " has no taxable flag; strict mode does not reclassify",
);
}
note = name + ": listed as not taxable, because no taxability was given for it.";
}
} else {
block = "A";
if (x.paidAsAgent === true) {
const own = typeof x.category === "string" && Object.hasOwn(ownCosts, x.category)
? ownCosts[x.category]
: "";
const reason = reclaimed > 0
? "we reclaimed the VAT on it"
: markup > 0
? "it includes a handling charge"
: own
? own + " is a cost of providing our services, not a payment made on your behalf"
: "";
if (reason) {
if (strictMode) {
throw new Error(
"disbursementsAndRecharges: " + f + " is marked paidAsAgent but " + reason +
"; strict mode does not reclassify",
);
}
note = name + ": recharged with VAT, not passed on as a disbursement, because " + reason + ".";
} else block = "B";
}
}
const supplier = typeof x.supplierName === "string" ? x.supplierName.trim() : "";
items.push({
i, date, amount, note, block,
description: name + (supplier ? " (" + supplier + ")" : "") + fxText,
});
});
// Date, then input order: the same key orders the lines and the notes.
items.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : a.i - b.i));
const row = (it: Item) => ({
date: dates.format(new Date(it.date + "T00:00:00Z")),
description: it.description,
amount: fmt(home, it.amount),
amountMinor: Number(it.amount),
});
const a = items.filter((it) => it.block === "A");
const b = items.filter((it) => it.block === "B");
if (a.length > SLOTS_A) {
throw new Error(
"disbursementsAndRecharges: " + a.length + " recharged expenses; this component prints at most " + SLOTS_A,
);
}
if (b.length > SLOTS_B) {
throw new Error(
"disbursementsAndRecharges: " + b.length + " disbursements; this component prints at most " + SLOTS_B,
);
}
if (items.length === 0) return nothing();
const sum = (list: Item[]) => list.reduce((s, it) => s + it.amount, big(0));
const netA = sum(a);
const showVat = !us && rate !== null;
const vat = showVat ? roundHalfAway(netA * big(rateHundredths), big(10000)) : big(0);
const totalA = netA + vat;
const totalB = sum(b);
const hasRecharges = a.length > 0;
const hasDisbursements = b.length > 0;
const rateText = String(rate);
const statementA = us
? "Sales tax applies to these expenses as part of our taxable services."
: showVat
? "Costs we incurred in providing our services. VAT is charged on them at " + rateText +
"%, the rate that applies to our fees."
: "Costs we incurred in providing our services. They take the same VAT treatment as our fees, so no VAT is charged on them here.";
return {
any: hasRecharges || hasDisbursements,
hasRecharges,
hasDisbursements,
showVat,
rechargeTitle: us ? "Taxable reimbursed expenses" : "Recharged expenses",
rechargeStatement: statementA,
rechargeAmountHeading: us ? "Amount" : "Net",
recharges: fill(a.map(row), SLOTS_A),
rechargeNet: fmt(home, netA),
vatLabel: showVat ? "VAT at " + rateText + "%" : "",
vat: showVat ? fmt(home, vat) : "",
rechargeTotal: fmt(home, totalA),
rechargeTotalLabel: us ? "Total taxable expenses" : "Total recharged expenses",
disbursementTitle: us ? "Non-taxable reimbursed expenses" : "Disbursements",
disbursementStatement: us
? "No sales tax is charged on these expenses."
: "Paid on your behalf as your agent and passed on at exact cost. These are outside the scope of VAT, so no VAT is charged on them.",
disbursements: fill(b.map(row), SLOTS_B),
disbursementTotal: fmt(home, totalB),
disbursementTotalLabel: us ? "Total non-taxable expenses" : "Total disbursements",
notes: items.filter((it) => it.note).map((it) => it.note).join("\n"),
rechargeNetMinor: Number(netA),
vatMinor: Number(vat),
rechargeTotalMinor: Number(totalA),
disbursementTotalMinor: Number(totalB),
};
},
});