Stage payment schedule
BodyTurns a contract sum and its milestones into a schedule that adds up to the contract sum exactly. Percentage stages are floored to the penny and the pennies lost go on one stage, so the total is never a penny out; the last stage can be the balance. The deposit is netted off by the contract's rule (first stage, final stage or pro rata), and any part bigger than its stage carries on rather than leaving a negative stage. Each stage is pending, reached, invoiced or paid, and the totals split into paid, invoiced and not yet invoiced. Under UK VAT regulation 93 a stage's tax point is the earlier of its invoice and its payment, never the milestone, so a reached stage shows no VAT due; and because the deposit was taxed when it was received, stage VAT is worked on what is left after it. A single-payment contract gets one line saying its tax point is completion. All of it is one deriver.
npx dxcl add stage-payment-schedule Preview data
the JSON this preview was built with{
"contract": {
"currency": "GBP",
"contractSumMinor": 4875250033,
"vat": {
"jurisdiction": "UK",
"ratePercent": 20
},
"deposit": {
"amountMinor": 487525003,
"receivedDate": "2026-02-16",
"application": "first"
},
"stages": [
{
"label": "Site establishment, enabling works and temporary services",
"amountMinor": 350000000,
"state": "paid",
"reachedDate": "2026-03-02",
"invoiceDate": "2026-03-06",
"paidDate": "2026-03-27"
},
{
"label": "Substructure, piling and ground-floor slab complete",
"percent": 12.5,
"state": "paid",
"reachedDate": "2026-05-11",
"invoiceDate": "2026-05-15",
"paidDate": "2026-05-13"
},
{
"label": "Frame, upper floors and roof structure topped out",
"percent": 17.5,
"state": "invoiced",
"reachedDate": "2026-08-03",
"invoiceDate": "2026-08-07"
},
{
"label": "Building envelope weathertight, including curtain walling",
"percent": 15,
"state": "reached",
"reachedDate": "2026-10-19"
},
{
"label": "Mechanical, electrical and plumbing first fix complete",
"percent": 15,
"state": "pending"
},
{
"label": "Internal finishes, second fix and commissioning",
"percent": 12.5,
"state": "pending"
},
{
"label": "Practical completion and handover of the building",
"percent": 10,
"state": "pending"
},
{
"label": "Making good defects at the end of the rectification period",
"balance": true,
"state": "pending"
}
]
}
} Rendered preview
the component rendered on its ownResolved nodes
what a renderer receives — 1 nodesstage-payment-schedule section The files
what installing writes; the selected file is the componentnodes/stage-payment-schedule.node.tsx import { Cell, Paragraph, Row, Section, type Section as SectionComponent, Table, useDeriver, useState } from "docxcelerate/template";
import stagePaymentSchedule from "../derivers/stage-payment-schedule.deriver.ts";
/**
* A construction or works contract's stage payments as one table that adds up
* to the contract sum exactly, to the penny. For each stage it shows what is
* paid, what is invoiced and what is still to come, and where UK VAT applies it
* gives each stage the VAT tax point the law gives it.
*
* Decisions already made for you:
*
* - Rounding. Percentage stages are floored to the penny and the lost pennies
* go on the last percentage stage, so the stages never come to a penny or two
* more or less than the contract sum. A fixed stage is paid as stated and is
* never adjusted.
* - Deposit. It is netted off by the contract's own rule: first stage, final
* stage or pro rata. A deposit bigger than the stage it comes off carries its
* excess to the next stage, so no stage is ever negative.
* - Tax points, regulation 93. Under VAT Regulations 1995 reg. 93 (stage
* payments in the construction industry) a stage's tax point is the earlier
* of the date a VAT invoice is issued and the date payment is received.
* Reaching a milestone is never a tax point, so a stage that is reached but
* not invoiced shows no VAT due.
* - VAT after the deposit. The deposit had its own tax point when it was
* received, so the VAT on a stage is worked on the stage after the deposit,
* never charged again on the full stage.
* - Single-payment contracts. They fall outside reg. 93: the table gets no tax
* point column, and one line says the tax point is completion, unless the
* work is invoiced or paid for earlier.
*
* Every step does arithmetic, sorting or date logic on request data, so all of
* it happens in one deriver and the node only prints what it returns.
*
* Notes:
*
* 1. The table has eight fixed stage slots, not 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. `plan-change-proration` has the same limit.
* 2. The node publishes 21 branches against the default `branchLimit` of 32:
* the two table variants (with and without tax points), a deposit row in
* each, eight stage rows in each, and the tax note. The compile step counts
* the table choice as one decision, so it reports 20; the published
* document carries 21.
* 3. All amounts are exclusive of VAT, in integer minor units.
* 4. Installed by `dxcl add stage-payment-schedule`, which also installs its
* deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface StagePaymentScheduleData {
contract: {
/**
* ISO 4217 code the amounts are in. It also sets how many minor units make
* one major unit (two for GBP, none for JPY). Missing means "GBP". Throws
* when present but not a code `Intl` knows.
*/
currency?: string;
/**
* The contract sum, exclusive of VAT, in integer minor units
* (4875250033 is £48,752,500.33). Every stage is measured against it, and
* the schedule always adds up to it exactly. Required: throws when missing,
* zero, negative or not a safe integer.
*/
contractSumMinor: number;
/**
* The VAT the contract is under. Missing means no VAT applies: no VAT
* column, no tax point column, no tax note. Only the UK's rules are
* implemented.
*/
vat?: {
/** Whose rules apply. Only `"UK"`; anything else throws. */
jurisdiction: "UK";
/**
* The rate as a percentage: 20 means 20%. At most two decimal places.
* 0 (zero-rated) still shows the columns, because a zero-rated supply
* still has tax points. Throws when not finite, below 0, above 100, or
* given to more than two decimal places.
*/
ratePercent: number;
};
/**
* True for a contract paid in one sum on completion. Such a contract is
* outside regulation 93. It must have exactly one stage (throws
* otherwise). It gets no tax point column, and when `vat` is present it
* gets one line saying the tax point is completion. Missing means false.
*/
singlePayment?: boolean;
/**
* A deposit received before work started. Missing, or `amountMinor` 0,
* means no deposit: no deposit row, no netting, and the other deposit
* fields are not read.
*/
deposit?: {
/**
* The deposit, exclusive of VAT, in integer minor units. Throws when
* negative, not an integer, or more than `contractSumMinor`.
*/
amountMinor: number;
/**
* When it was received, ISO 8601 (YYYY-MM-DD; anything after the tenth
* character is ignored). This is the deposit's tax point. Required when
* `amountMinor` is above 0: throws when missing or not a date.
*/
receivedDate: string;
/**
* Which stages the contract nets the deposit off. `first`: off the first
* stage, with any excess carried to the second, then the third. `final`:
* off the last stage, with any excess carried back to the one before.
* `proRata`: spread over every stage in proportion to its size, floored,
* with the remaining pennies on the last stage. Required when
* `amountMinor` is above 0: anything else throws, because a guessed rule
* changes every amount on the page.
*/
application: "first" | "final" | "proRata";
};
/**
* The stages, in contract order. They are printed in this order and never
* sorted. 1 to 8 entries: throws when missing, empty or longer than 8.
*/
stages: Array<{
/** The milestone as printed: "Roof structure topped out". Required: throws when missing or blank. */
label: string;
/**
* A percentage of the contract sum, at most two decimal places: 12.5.
* Floored to the minor unit. Give exactly one of `percent`,
* `amountMinor` or `balance`, or it throws. Throws when not above 0,
* above 100, or given to more than two decimal places.
*/
percent?: number;
/**
* A fixed amount, exclusive of VAT, in integer minor units. Paid as
* stated and never adjusted for rounding. Throws when not a positive
* integer.
*/
amountMinor?: number;
/**
* True for "the balance": whatever the contract sum less every earlier
* stage comes to. Allowed on the last stage only (throws elsewhere).
* Throws when the earlier stages already come to the whole contract sum
* or more.
*/
balance?: true;
/**
* Where the stage has got to. `pending`: not reached. `reached`: the
* milestone is met but no VAT invoice has been issued. An application
* for payment is not a VAT invoice. `invoiced`: a VAT invoice has been
* issued but not paid. `paid`: payment received. Required: anything else
* throws.
*/
state: "pending" | "reached" | "invoiced" | "paid";
/** When the milestone was met, ISO 8601. Printed in the status when given. Optional in every state. Throws when present but not a date. */
reachedDate?: string;
/** When the VAT invoice was issued, ISO 8601. Required when `state` is `invoiced`. Read when `paid` (see below). Ignored when `pending` or `reached`. Throws when present but not a date. */
invoiceDate?: string;
/** When payment was received, ISO 8601. Required when `state` is `paid`. Ignored otherwise. Throws when present but not a date. */
paidDate?: string;
}>;
};
}
/** Prints the stage payment schedule, with VAT tax points where UK VAT applies. */
export const StagePaymentSchedule: SectionComponent = async () => {
const [contract] = useState((data: StagePaymentScheduleData) => data.contract);
const s = await useDeriver(stagePaymentSchedule, [contract]);
return (
<Section id="stage-payment-schedule" title="Stage payments">
<Paragraph id="stage-payment-schedule-intro">{s.intro}</Paragraph>
{s.taxPoints
? (
<Table
id="stage-payment-schedule-vat-table"
columns={[{ width: "auto" }, { width: 34 }, { width: 28, align: "right" }, { width: 24, align: "right" }, { width: 28 }]}
>
<Row id="stage-payment-schedule-vat-header" header>
<Cell>Stage</Cell>
<Cell>Status</Cell>
<Cell>Amount</Cell>
<Cell>VAT</Cell>
<Cell>Tax point</Cell>
</Row>
{s.deposit.description && (
<Row id="stage-payment-schedule-vat-deposit">
<Cell>{s.deposit.description}</Cell>
<Cell>{s.deposit.status}</Cell>
<Cell>{s.deposit.amount}</Cell>
<Cell>{s.deposit.vat}</Cell>
<Cell>{s.deposit.taxPoint}</Cell>
</Row>
)}
{s.stages[0].description && (
<Row id="stage-payment-schedule-vat-stage-1">
<Cell>{s.stages[0].description}</Cell>
<Cell>{s.stages[0].status}</Cell>
<Cell>{s.stages[0].amount}</Cell>
<Cell>{s.stages[0].vat}</Cell>
<Cell>{s.stages[0].taxPoint}</Cell>
</Row>
)}
{s.stages[1].description && (
<Row id="stage-payment-schedule-vat-stage-2">
<Cell>{s.stages[1].description}</Cell>
<Cell>{s.stages[1].status}</Cell>
<Cell>{s.stages[1].amount}</Cell>
<Cell>{s.stages[1].vat}</Cell>
<Cell>{s.stages[1].taxPoint}</Cell>
</Row>
)}
{s.stages[2].description && (
<Row id="stage-payment-schedule-vat-stage-3">
<Cell>{s.stages[2].description}</Cell>
<Cell>{s.stages[2].status}</Cell>
<Cell>{s.stages[2].amount}</Cell>
<Cell>{s.stages[2].vat}</Cell>
<Cell>{s.stages[2].taxPoint}</Cell>
</Row>
)}
{s.stages[3].description && (
<Row id="stage-payment-schedule-vat-stage-4">
<Cell>{s.stages[3].description}</Cell>
<Cell>{s.stages[3].status}</Cell>
<Cell>{s.stages[3].amount}</Cell>
<Cell>{s.stages[3].vat}</Cell>
<Cell>{s.stages[3].taxPoint}</Cell>
</Row>
)}
{s.stages[4].description && (
<Row id="stage-payment-schedule-vat-stage-5">
<Cell>{s.stages[4].description}</Cell>
<Cell>{s.stages[4].status}</Cell>
<Cell>{s.stages[4].amount}</Cell>
<Cell>{s.stages[4].vat}</Cell>
<Cell>{s.stages[4].taxPoint}</Cell>
</Row>
)}
{s.stages[5].description && (
<Row id="stage-payment-schedule-vat-stage-6">
<Cell>{s.stages[5].description}</Cell>
<Cell>{s.stages[5].status}</Cell>
<Cell>{s.stages[5].amount}</Cell>
<Cell>{s.stages[5].vat}</Cell>
<Cell>{s.stages[5].taxPoint}</Cell>
</Row>
)}
{s.stages[6].description && (
<Row id="stage-payment-schedule-vat-stage-7">
<Cell>{s.stages[6].description}</Cell>
<Cell>{s.stages[6].status}</Cell>
<Cell>{s.stages[6].amount}</Cell>
<Cell>{s.stages[6].vat}</Cell>
<Cell>{s.stages[6].taxPoint}</Cell>
</Row>
)}
{s.stages[7].description && (
<Row id="stage-payment-schedule-vat-stage-8">
<Cell>{s.stages[7].description}</Cell>
<Cell>{s.stages[7].status}</Cell>
<Cell>{s.stages[7].amount}</Cell>
<Cell>{s.stages[7].vat}</Cell>
<Cell>{s.stages[7].taxPoint}</Cell>
</Row>
)}
<Row id="stage-payment-schedule-vat-paid">
<Cell span={2}>Paid</Cell>
<Cell>{s.totals.paid}</Cell>
<Cell>{s.totals.paidVat}</Cell>
<Cell></Cell>
</Row>
<Row id="stage-payment-schedule-vat-invoiced">
<Cell span={2}>Invoiced, not yet paid</Cell>
<Cell>{s.totals.invoiced}</Cell>
<Cell>{s.totals.invoicedVat}</Cell>
<Cell></Cell>
</Row>
<Row id="stage-payment-schedule-vat-not-invoiced">
<Cell span={2}>Not yet invoiced</Cell>
<Cell>{s.totals.notInvoiced}</Cell>
<Cell>{s.totals.notInvoicedVat}</Cell>
<Cell></Cell>
</Row>
<Row id="stage-payment-schedule-vat-contract-sum">
<Cell span={2}>Contract sum</Cell>
<Cell>{s.totals.contractSum}</Cell>
<Cell></Cell>
<Cell></Cell>
</Row>
</Table>
)
: (
<Table
id="stage-payment-schedule-table"
columns={[{ width: "auto" }, { width: 40 }, { width: 30, align: "right" }]}
>
<Row id="stage-payment-schedule-header" header>
<Cell>Stage</Cell>
<Cell>Status</Cell>
<Cell>Amount</Cell>
</Row>
{s.deposit.description && (
<Row id="stage-payment-schedule-deposit">
<Cell>{s.deposit.description}</Cell>
<Cell>{s.deposit.status}</Cell>
<Cell>{s.deposit.amount}</Cell>
</Row>
)}
{s.stages[0].description && (
<Row id="stage-payment-schedule-stage-1">
<Cell>{s.stages[0].description}</Cell>
<Cell>{s.stages[0].status}</Cell>
<Cell>{s.stages[0].amount}</Cell>
</Row>
)}
{s.stages[1].description && (
<Row id="stage-payment-schedule-stage-2">
<Cell>{s.stages[1].description}</Cell>
<Cell>{s.stages[1].status}</Cell>
<Cell>{s.stages[1].amount}</Cell>
</Row>
)}
{s.stages[2].description && (
<Row id="stage-payment-schedule-stage-3">
<Cell>{s.stages[2].description}</Cell>
<Cell>{s.stages[2].status}</Cell>
<Cell>{s.stages[2].amount}</Cell>
</Row>
)}
{s.stages[3].description && (
<Row id="stage-payment-schedule-stage-4">
<Cell>{s.stages[3].description}</Cell>
<Cell>{s.stages[3].status}</Cell>
<Cell>{s.stages[3].amount}</Cell>
</Row>
)}
{s.stages[4].description && (
<Row id="stage-payment-schedule-stage-5">
<Cell>{s.stages[4].description}</Cell>
<Cell>{s.stages[4].status}</Cell>
<Cell>{s.stages[4].amount}</Cell>
</Row>
)}
{s.stages[5].description && (
<Row id="stage-payment-schedule-stage-6">
<Cell>{s.stages[5].description}</Cell>
<Cell>{s.stages[5].status}</Cell>
<Cell>{s.stages[5].amount}</Cell>
</Row>
)}
{s.stages[6].description && (
<Row id="stage-payment-schedule-stage-7">
<Cell>{s.stages[6].description}</Cell>
<Cell>{s.stages[6].status}</Cell>
<Cell>{s.stages[6].amount}</Cell>
</Row>
)}
{s.stages[7].description && (
<Row id="stage-payment-schedule-stage-8">
<Cell>{s.stages[7].description}</Cell>
<Cell>{s.stages[7].status}</Cell>
<Cell>{s.stages[7].amount}</Cell>
</Row>
)}
<Row id="stage-payment-schedule-paid">
<Cell span={2}>Paid</Cell>
<Cell>{s.totals.paid}</Cell>
</Row>
<Row id="stage-payment-schedule-invoiced">
<Cell span={2}>Invoiced, not yet paid</Cell>
<Cell>{s.totals.invoiced}</Cell>
</Row>
<Row id="stage-payment-schedule-not-invoiced">
<Cell span={2}>Not yet invoiced</Cell>
<Cell>{s.totals.notInvoiced}</Cell>
</Row>
<Row id="stage-payment-schedule-contract-sum">
<Cell span={2}>Contract sum</Cell>
<Cell>{s.totals.contractSum}</Cell>
</Row>
</Table>
)}
{s.taxNote && <Paragraph id="stage-payment-schedule-tax-note">{s.taxNote}</Paragraph>}
</Section>
);
}; derivers/stage-payment-schedule.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Settles a contract's stage payments: the gross, deposit deduction, net, VAT
* and tax point of every stage, and the totals. Installed by
* `dxcl add stage-payment-schedule`.
*
* 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 is declared inside `run`.
*/
export default deriver({
name: "stagePaymentSchedule",
run: (contract: unknown) => {
const c = contract as any;
const SLOTS = 8;
const currency = c?.currency ?? "GBP";
let money: Intl.NumberFormat;
try {
money = new Intl.NumberFormat("en-GB", { style: "currency", currency });
} catch {
throw new Error("contract.currency must be an ISO 4217 code");
}
const exponent = money.resolvedOptions().maximumFractionDigits as number;
const fmtMoney = (minor: number) => money.format(minor / 10 ** exponent);
// UTC so a date does not shift with the engine's time zone.
const dates = new Intl.DateTimeFormat("en-GB", { dateStyle: "medium", timeZone: "UTC" });
const fmtDate = (iso: string) => dates.format(new Date(iso + "T00:00:00Z"));
const isoDate = (value: unknown, field: string): string => {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}/.test(value)) {
throw new Error(field + " must be an ISO 8601 date");
}
const iso = value.slice(0, 10);
const d = new Date(iso + "T00:00:00Z");
if (Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== iso) {
throw new Error(field + " must be an ISO 8601 date");
}
return iso;
};
// Basis points: a percentage to two decimal places, as an exact integer.
const basisPoints = (value: unknown, field: string): number => {
if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(field + " must be a number");
const bp = Math.round(value * 100);
if (Math.abs(bp - value * 100) > 1e-9) throw new Error(field + " must have at most two decimal places");
return bp;
};
// Half up, once per line. BigInt because minor units times basis points can pass 2^53.
const vatOf = (net: number, rateBp: number) => Number((BigInt(net) * BigInt(rateBp) + 5000n) / 10000n);
const S = c?.contractSumMinor;
if (typeof S !== "number" || !Number.isSafeInteger(S) || S <= 0) {
throw new Error("contract.contractSumMinor must be a positive integer of minor units");
}
let rateBp = 0;
const hasVat = c.vat !== undefined && c.vat !== null;
if (hasVat) {
if (c.vat.jurisdiction !== "UK") throw new Error('contract.vat.jurisdiction must be "UK"');
rateBp = basisPoints(c.vat.ratePercent, "contract.vat.ratePercent");
if (rateBp < 0 || rateBp > 10000) throw new Error("contract.vat.ratePercent must be between 0 and 100");
}
const single = c.singlePayment === true;
const taxPoints = hasVat && !single;
const raw = c.stages;
if (!Array.isArray(raw) || raw.length === 0) throw new Error("contract.stages must have at least one stage");
if (raw.length > SLOTS) {
throw new Error(
"contract.stages has more than " + SLOTS + " stages; the node prints " + SLOTS +
". Add row slots to the node and raise the limit in the deriver.",
);
}
if (single && raw.length !== 1) throw new Error("contract.singlePayment requires exactly one stage");
const n = raw.length;
let D = 0;
let receivedDate = "";
let application = "";
if (c.deposit !== undefined && c.deposit !== null) {
D = c.deposit.amountMinor;
if (typeof D !== "number" || !Number.isSafeInteger(D) || D < 0) {
throw new Error("contract.deposit.amountMinor must be a non-negative integer of minor units");
}
if (D > S) throw new Error("contract.deposit.amountMinor is more than the contract sum");
if (D > 0) {
receivedDate = isoDate(c.deposit.receivedDate, "contract.deposit.receivedDate");
application = c.deposit.application;
if (application !== "first" && application !== "final" && application !== "proRata") {
throw new Error('contract.deposit.application must be "first", "final" or "proRata"');
}
}
}
// Validate every stage and total what is stated.
const states = ["pending", "reached", "invoiced", "paid"];
let fixedTotal = 0;
let bpTotal = 0;
let balanceAt = -1;
const stages = raw.map((s: any, i: number) => {
const f = "contract.stages[" + i + "]";
if (typeof s?.label !== "string" || s.label.trim() === "") throw new Error(f + ".label is required");
if (!states.includes(s.state)) throw new Error(f + ".state must be pending, reached, invoiced or paid");
const given = [s.percent !== undefined, s.amountMinor !== undefined, s.balance !== undefined].filter(Boolean).length;
if (given !== 1) throw new Error(f + " must give exactly one of percent, amountMinor or balance");
let bp = 0;
let fixed = -1;
if (s.percent !== undefined) {
bp = basisPoints(s.percent, f + ".percent");
if (bp <= 0 || bp > 10000) throw new Error(f + ".percent must be above 0 and at most 100");
bpTotal += bp;
} else if (s.amountMinor !== undefined) {
fixed = s.amountMinor;
if (typeof fixed !== "number" || !Number.isSafeInteger(fixed) || fixed <= 0) {
throw new Error(f + ".amountMinor must be a positive integer of minor units");
}
fixedTotal += fixed;
} else {
if (s.balance !== true) throw new Error(f + ".balance must be true");
if (i !== n - 1) throw new Error(f + ".balance is allowed on the last stage only");
balanceAt = i;
}
const reached = s.reachedDate === undefined ? "" : isoDate(s.reachedDate, f + ".reachedDate");
const invoiced = s.invoiceDate === undefined ? "" : isoDate(s.invoiceDate, f + ".invoiceDate");
const paid = s.paidDate === undefined ? "" : isoDate(s.paidDate, f + ".paidDate");
if (s.state === "invoiced" && !invoiced) throw new Error(f + ".invoiceDate is required when the stage is invoiced");
if (s.state === "paid" && !paid) throw new Error(f + ".paidDate is required when the stage is paid");
return { label: s.label as string, state: s.state as string, bp, fixed, reached, invoiced, paid };
});
// Allocation: every message states the excess in money.
if (bpTotal > 10000) throw new Error("contract.stages: percentages total more than 100");
if (fixedTotal > S) throw new Error("contract.stages: fixed amounts are " + fmtMoney(fixedTotal - S) + " more than the contract sum");
const floorBp = (bp: number) => Number((BigInt(S) * BigInt(bp)) / 10000n);
const g: number[] = stages.map((s: any) => (s.fixed >= 0 ? s.fixed : s.bp > 0 ? floorBp(s.bp) : 0));
const stated = g.reduce((a, b) => a + b, 0);
if (stated > S) throw new Error("contract.stages come to " + fmtMoney(stated - S) + " more than the contract sum");
if (balanceAt >= 0) {
g[balanceAt] = S - stated;
if (g[balanceAt] <= 0) throw new Error("contract.stages: the earlier stages already come to the whole contract sum, so there is no balance");
} else {
const exact = BigInt(fixedTotal) * 10000n + BigInt(S) * BigInt(bpTotal);
const whole = BigInt(S) * 10000n;
if (exact < whole) {
throw new Error(
"contract.stages come to " + fmtMoney(S - fixedTotal - floorBp(bpTotal)) +
" short of the contract sum; make the last stage `balance: true`",
);
}
if (exact > whole) {
// The percentages floor but the sum is checked exactly, so a stage can round to nothing and still tip it over.
throw new Error(
"contract.stages come to " + fmtMoney(Number((exact - whole + 9999n) / 10000n)) +
" more than the contract sum (a percentage stage rounds to less than one penny)",
);
}
// Lost pennies go on the last percentage stage; a fixed stage is paid as stated.
let last = -1;
stages.forEach((s: any, i: number) => {
if (s.bp > 0) last = i;
});
if (last >= 0) g[last] += S - stated;
}
// Deposit netting.
const d: number[] = g.map(() => 0);
if (D > 0) {
if (application === "first" || application === "final") {
let rem = D;
const order = g.map((_, i) => i);
if (application === "final") order.reverse();
for (const i of order) {
d[i] = Math.min(rem, g[i]);
rem -= d[i];
}
} else {
let sum = 0;
for (let i = 0; i < n - 1; i++) {
d[i] = Number((BigInt(D) * BigInt(g[i])) / BigInt(S));
sum += d[i];
}
d[n - 1] = D - sum;
let excess = d[n - 1] - g[n - 1];
if (excess > 0) {
d[n - 1] = g[n - 1];
for (let i = n - 2; i >= 0 && excess > 0; i--) {
const take = Math.min(excess, g[i] - d[i]);
d[i] += take;
excess -= take;
}
}
}
}
const net = g.map((x, i) => x - d[i]);
const empty = () => ({
description: "", status: "", amount: "", vat: "", taxPoint: "",
grossMinor: 0, deductionMinor: 0, netMinor: 0, vatMinor: null as number | null, taxPointDate: null as string | null,
});
const rows = stages.map((s: any, i: number) => {
let taxPointDate: string | null = null;
if (taxPoints) {
if (s.state === "invoiced") taxPointDate = s.invoiced;
else if (s.state === "paid") taxPointDate = s.invoiced && s.invoiced < s.paid ? s.invoiced : s.paid;
}
const vatMinor = taxPointDate ? vatOf(net[i], rateBp) : null;
const status = s.state === "pending"
? "Not yet reached"
: s.state === "reached"
? (s.reached ? "Reached " + fmtDate(s.reached) : "Reached")
: s.state === "invoiced"
? "Invoiced " + fmtDate(s.invoiced)
: "Paid " + fmtDate(s.paid);
return {
description: d[i] > 0 ? s.label + " (" + fmtMoney(g[i]) + " less " + fmtMoney(d[i]) + " of the deposit)" : s.label,
status,
amount: fmtMoney(net[i]),
vat: !taxPoints ? "" : vatMinor === null ? "Not yet due" : fmtMoney(vatMinor),
taxPoint: !taxPoints ? "" : taxPointDate ? fmtDate(taxPointDate) : "Not yet",
grossMinor: g[i], deductionMinor: d[i], netMinor: net[i], vatMinor, taxPointDate,
};
});
let deposit = empty();
let depositVat = 0;
if (D > 0) {
if (taxPoints) depositVat = vatOf(D, rateBp);
deposit = {
description: "Deposit",
status: "Received " + fmtDate(receivedDate),
amount: fmtMoney(D),
vat: taxPoints ? fmtMoney(depositVat) : "",
taxPoint: taxPoints ? fmtDate(receivedDate) : "",
grossMinor: D, deductionMinor: 0, netMinor: D,
vatMinor: taxPoints ? depositVat : null,
taxPointDate: taxPoints ? receivedDate : null,
};
}
// Totals.
let paidMinor = D;
let paidVatMinor = depositVat;
let invoicedMinor = 0;
let invoicedVatMinor = 0;
let notInvoicedMinor = 0;
stages.forEach((s: any, i: number) => {
if (s.state === "paid") {
paidMinor += net[i];
paidVatMinor += rows[i].vatMinor ?? 0;
} else if (s.state === "invoiced") {
invoicedMinor += net[i];
invoicedVatMinor += rows[i].vatMinor ?? 0;
} else notInvoicedMinor += net[i];
});
if (paidMinor + invoicedMinor + notInvoicedMinor !== S) {
throw new Error("stagePaymentSchedule: the totals do not add up to the contract sum");
}
const after = D > 0 ? ", after a deposit of " + fmtMoney(D) : "";
const intro = single
? "The contract sum of " + fmtMoney(S) + " is paid in a single sum on completion" + after + "."
: "The contract sum of " + fmtMoney(S) + " is paid in " + (n === 1 ? "one stage" : n + " stages") + after + ".";
let taxNote = "";
if (taxPoints) {
taxNote =
"VAT on each stage is due at its tax point: the date it is invoiced or paid, whichever comes first. " +
"Reaching a stage is not a tax point, so a stage that is reached but not yet invoiced has no VAT due." +
(D > 0
? " VAT on the deposit was due when it was received, so each stage's VAT is worked on what is left of it after the deposit."
: "");
} else if (single && hasVat) {
taxNote =
"This contract is paid in a single sum, so it is not a stage-payment contract under VAT regulation 93. " +
"Its tax point is the date the work is completed, unless it is invoiced or paid for before then. VAT of " +
fmtMoney(vatOf(net[0], rateBp)) + " is due at that point" +
(D > 0
? " on the " + fmtMoney(net[0]) + " left after the deposit, which had its own tax point when it was received on " +
fmtDate(receivedDate) + "."
: ".");
}
const slots = rows.slice();
while (slots.length < SLOTS) slots.push(empty());
return {
intro,
taxPoints,
taxNote,
deposit,
stages: slots,
totals: {
paid: fmtMoney(paidMinor),
paidVat: taxPoints ? fmtMoney(paidVatMinor) : "",
invoiced: fmtMoney(invoicedMinor),
invoicedVat: taxPoints ? fmtMoney(invoicedVatMinor) : "",
notInvoiced: fmtMoney(notInvoicedMinor),
notInvoicedVat: taxPoints ? "Not yet due" : "",
contractSum: fmtMoney(S),
paidMinor,
invoicedMinor,
notInvoicedMinor,
paidVatMinor,
invoicedVatMinor,
},
};
},
});