Fee cap status
BodyA cap is clipped, not printed: a hard cap or ceiling charges only what is left under it, and the excess is printed as fees above the cap, not charged, so the client sees the value written off. A cap already used up bills the period at nil. An estimate is not a cap: fees are charged in full, and once they pass it the invoice prints the revised estimate and when the client was told, or an 'incomplete' warning when nobody was, because an untold overrun can be challenged. A ceiling past its notice threshold (85% unless set) prints the percentage used and the notice. Optional withholding stops at its limit. Four states, four ids: under, approaching, reached, exceeded, all decided by one deriver.
npx dxcl add fee-cap-status feeCap.kind Preview data
the JSON this preview was built with{
"feeCap": {
"kind": "hard",
"amount": 2500000,
"billedToDate": 2312480.55,
"noticeThreshold": 85,
"withholding": {
"percent": 10,
"limit": 250000,
"withheldToDate": 231248.06
},
"currency": "GBP"
},
"fees": {
"thisPeriod": 418960.4
}
} {
"feeCap": {
"kind": "estimate",
"amount": 2500000,
"billedToDate": 2312480.55,
"noticeThreshold": 85,
"withholding": {
"percent": 10,
"limit": 250000,
"withheldToDate": 231248.06
},
"currency": "GBP"
},
"fees": {
"thisPeriod": 418960.4
}
} {
"feeCap": {
"kind": "ceiling",
"amount": 2500000,
"billedToDate": 2312480.55,
"noticeThreshold": 85,
"withholding": {
"percent": 10,
"limit": 250000,
"withheldToDate": 231248.06
},
"currency": "GBP"
},
"fees": {
"thisPeriod": 418960.4
}
} Rendered preview
each arrangement, rendered on its ownarrangement="table" default arrangement="stacked" arrangement="table" default arrangement="stacked" arrangement="table" default arrangement="stacked" Resolved nodes
what a renderer receives — 1 nodesfee-cap section fee-cap section fee-cap section The files
what installing writes; the selected file is the componentnodes/fee-cap-status.node.tsx import { arrange, Paragraph, Section, type Section as SectionComponent, useDeriver, useState } from "docxcelerate/template";
import type { FeeCapStatusLines } from "../arrangements/fee-cap-status/lines.ts";
import { stacked } from "../arrangements/fee-cap-status/stacked.arrangement.tsx";
import { table } from "../arrangements/fee-cap-status/table.arrangement.tsx";
import feeCapStatus from "../derivers/fee-cap-status.deriver.ts";
/**
* What an invoice under a fee limit may charge, and what it has to say about
* it. Those are decisions about money and about what a client was told, not
* about layout.
*
* Hard cap and ceiling: the invoice charges only what is left under the cap.
* The excess is printed as written off, so the client sees the value given up
* and nobody reads the bill as the whole value of the work. A cap already used
* up bills the period at nil, never below it.
*
* Ceiling: once fees reach the notice threshold (85% unless told otherwise,
* following FAR 52.232-7) the invoice prints the percentage used and the
* notice. The percentage is floored, so a figure just under 100% never prints
* as 100%.
*
* Estimate: not a limit, so fees are charged in full. Once they pass the
* estimate the invoice must print the revised estimate and the date the client
* was told. Without a revised estimate it prints an "incomplete" warning, at
* the top, because an overrun the client was not told about can be challenged:
* the SRA's position in England and Wales, and in Ireland LSRA 2015 s.150
* requires a fresh notice when costs will be significantly greater. A draft
* that cannot go out says so before anything else.
*
* Withholding: the agreed percentage of what the invoice charges is retained
* until total retention reaches its limit, and after that nothing is.
*
* Four states, each with its own id: under, approaching, reached, exceeded.
* The whole decision is one deriver, because every part of it is arithmetic on
* request data, and that throws at publish time. The node prints what the
* deriver returns, so nothing is computed on request data here.
*
* Arrangement: where the figures sit is chosen with the `arrangement` prop.
* This file decides every line; each arrangement, in
* `arrangements/fee-cap-status/`, only places them, so both print the same
* rows under the same conditions.
*
* A publish build of this node emits 13 conditions against the default
* `branchLimit` of 32: 8 in the node and 5 in the chosen arrangement. The
* state arms are not collapsed into one paragraph, because the per-arm id is
* what records which state a recipient got.
*
* Installed by `dxcl add fee-cap-status`, which also installs its deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface FeeCapStatusData {
feeCap: {
/**
* What kind of limit the engagement has.
*
* `hard` is a cap or not-to-exceed: nothing above it is charged.
* `ceiling` is a hard cap with a notice duty as fees approach it (FAR
* 52.232-7): it clips like `hard`, and past `noticeThreshold` prints the
* notice. `estimate` is not a limit: fees are charged in full, and an
* overrun has to have been told to the client. Required: anything else
* throws, because a cap read as an estimate overcharges, and an estimate
* read as a cap writes off fees that were owed.
*/
kind: "hard" | "estimate" | "ceiling";
/**
* The cap, ceiling or original estimate, in major units of `currency`.
* Required, finite and greater than 0: the deriver throws otherwise,
* because every percentage divides by it.
*/
amount: number;
/**
* Fees charged on earlier invoices under this limit, before any
* withholding, not counting this invoice. Required, finite and 0 or more:
* the deriver throws otherwise. A figure above `amount` on a hard cap or
* ceiling is read as "cap used up", not as an error.
*/
billedToDate: number;
/**
* The percentage of the limit at which the reader is warned that fees are
* approaching it. A number greater than 0 and less than 100, for example `85`.
* Missing means 85 for `ceiling` and no "approaching" state for `hard` and
* `estimate`. Out of range or not finite throws.
*/
noticeThreshold?: number;
/**
* For `estimate` only: the revised estimate and the day the client was told.
* When given, it replaces `amount` as the estimate fees are measured
* against, and the revision is printed. Missing means fees are measured
* against `amount`, and an overrun prints the "incomplete" warning.
* Ignored for `hard` and `ceiling`: a cap is not raised by notice.
*/
revisedEstimate?: {
/** The revised estimate, in major units. Finite and greater than 0, or it throws. */
amount: number;
/** When the client was told, as an ISO 8601 date (`2026-03-03`). Throws when not one. */
notifiedOn: string;
};
/**
* A retention the agreement allows: a percentage of each invoice held back
* until the total held reaches a limit. Missing means nothing is withheld.
*/
withholding?: {
/** Percentage of what this invoice charges, greater than 0 and at most 100. Throws otherwise. */
percent: number;
/** The most that may be held in total, in major units. Greater than 0, or it throws. */
limit: number;
/**
* Held back on earlier invoices. Required, 0 or more: throws when
* missing, because guessing 0 would keep withholding after the limit.
*/
withheldToDate: number;
};
/** ISO 4217 code. Defaults to GBP. A code Intl does not know throws. */
currency?: string;
};
fees: {
/**
* Fees for the work in this invoice's period, before the cap and before
* withholding, in major units. Required, finite and 0 or more: a credit
* throws, because a credit against a capped engagement is a credit note,
* not this.
*/
thisPeriod: number;
};
}
/**
* Where the figures sit.
*
* - `table`: labels in a column, amounts right-aligned beside them, so the
* reader can check cap, billed and charged against each other. The default.
* - `stacked`: one labelled figure under another, down the text column.
*/
export type FeeCapStatusArrangement = "table" | "stacked";
/** Props for {@linkcode FeeCapStatus}. */
export interface FeeCapStatusProps {
/** Where the figures sit. Defaults to `"table"`. */
arrangement?: FeeCapStatusArrangement;
}
export const FeeCapStatus: SectionComponent<FeeCapStatusProps> = async ({ arrangement }) => {
const [feeCap] = useState((data: FeeCapStatusData) => data.feeCap);
const [fees] = useState((data: FeeCapStatusData) => data.fees);
const fee = await useDeriver(feeCapStatus, [feeCap, fees]);
const lines: FeeCapStatusLines = {
capLabel: fee.capLabel,
capValue: fee.capValue,
billedToDate: fee.billedToDate,
thisPeriod: fee.thisPeriod,
writtenOffLabel: fee.writtenOffLabel,
writtenOff: fee.writtenOff,
charged: fee.charged,
withheldLabel: fee.withheldLabel,
withheld: fee.withheld,
payable: fee.payable,
remainingLabel: fee.remainingLabel,
remaining: fee.remaining,
};
return (
<Section id="fee-cap" title={fee.heading}>
{fee.incomplete && <Paragraph id="fee-cap-incomplete">{fee.incomplete}</Paragraph>}
{fee.state === "under" && <Paragraph id="fee-cap-under">{fee.status}</Paragraph>}
{fee.state === "approaching" && <Paragraph id="fee-cap-approaching">{fee.status}</Paragraph>}
{fee.state === "reached" && <Paragraph id="fee-cap-reached">{fee.status}</Paragraph>}
{fee.state === "exceeded" && <Paragraph id="fee-cap-exceeded">{fee.status}</Paragraph>}
{arrange(arrangement, { table: () => table(lines), stacked: () => stacked(lines) })}
{fee.revised && <Paragraph id="fee-cap-revised">{fee.revised}</Paragraph>}
{fee.notice && <Paragraph id="fee-cap-notice">{fee.notice}</Paragraph>}
{fee.retention && <Paragraph id="fee-cap-retention">{fee.retention}</Paragraph>}
</Section>
);
}; derivers/fee-cap-status.deriver.ts import { deriver } from "docxcelerate/template";
/**
* Decides what an invoice under a fee limit may charge, and what it has to say
* about it. Installed by `dxcl add fee-cap-status`.
*
* 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: "feeCapStatus",
run: (feeCap: unknown, fees: unknown) => {
// deno-lint-ignore no-explicit-any
const fc = feeCap as any;
// deno-lint-ignore no-explicit-any
const fe = fees as any;
const num = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
const kinds = ["hard", "estimate", "ceiling"];
if (!kinds.includes(fc?.kind)) {
throw new Error("feeCap.kind must be one of " + kinds.join(", "));
}
const kind: string = fc.kind;
let money: Intl.NumberFormat;
try {
money = new Intl.NumberFormat("en-GB", { style: "currency", currency: fc.currency ?? "GBP", currencyDisplay: "narrowSymbol" });
} catch {
throw new Error("feeCap.currency must be an ISO 4217 code");
}
if (!num(fc.amount) || fc.amount <= 0) throw new Error("feeCap.amount must be a number above 0");
if (!num(fc.billedToDate) || fc.billedToDate < 0) throw new Error("feeCap.billedToDate must be a number, 0 or more");
if (!num(fe?.thisPeriod) || fe.thisPeriod < 0) throw new Error("fees.thisPeriod must be a number, 0 or more");
const nt = fc.noticeThreshold;
if (nt !== undefined && nt !== null && (!num(nt) || nt <= 0 || nt >= 100)) {
throw new Error("feeCap.noticeThreshold must be a number above 0 and below 100");
}
const isDate = (v: unknown) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}/.test(v);
const rev = kind === "estimate" && fc.revisedEstimate ? fc.revisedEstimate : null;
if (rev) {
if (!num(rev.amount) || rev.amount <= 0) throw new Error("feeCap.revisedEstimate.amount must be a number above 0");
if (!isDate(rev.notifiedOn)) throw new Error("feeCap.revisedEstimate.notifiedOn must be an ISO 8601 date");
}
const wh = fc.withholding ? fc.withholding : null;
if (wh) {
if (!num(wh.percent) || wh.percent <= 0 || wh.percent > 100) {
throw new Error("feeCap.withholding.percent must be a number above 0 and at most 100");
}
if (!num(wh.limit) || wh.limit <= 0) throw new Error("feeCap.withholding.limit must be a number above 0");
if (!num(wh.withheldToDate) || wh.withheldToDate < 0) {
throw new Error("feeCap.withholding.withheldToDate must be a number, 0 or more");
}
}
// Integer minor units, so 0.1 + 0.2 against a cap of 0.3 is "reached".
const exp = money.resolvedOptions().maximumFractionDigits ?? 2;
const minor = (v: number) => Math.round(v * 10 ** exp);
const fmt = (m: number) => money.format(m / 10 ** exp);
const major = (m: number) => m / 10 ** exp;
const pctFmt = new Intl.NumberFormat("en-GB", { maximumFractionDigits: 2 });
// UTC, so the date does not shift by a day on the engine.
const dateFmt = new Intl.DateTimeFormat("en-GB", { dateStyle: "long", timeZone: "UTC" });
const day = (iso: string) => dateFmt.format(new Date(iso.slice(0, 10) + "T00:00:00Z"));
const estimate = kind === "estimate";
const L = minor(rev ? rev.amount : fc.amount);
const B = minor(fc.billedToDate);
const P = minor(fe.thisPeriod);
const T: number | null = nt === undefined || nt === null ? (kind === "ceiling" ? 85 : null) : nt;
const phrase = kind === "hard"
? "the agreed cap"
: kind === "ceiling"
? "the agreed ceiling"
: rev
? "our revised estimate"
: "our estimate";
const Phrase = phrase.charAt(0).toUpperCase() + phrase.slice(1);
const noun = kind === "hard" ? "cap" : kind === "ceiling" ? "ceiling" : rev ? "revised estimate" : "estimate";
const heading = kind === "hard" ? "Fee cap" : kind === "ceiling" ? "Fee ceiling" : "Fee estimate";
const charged = estimate ? P : Math.min(P, Math.max(0, L - B));
const writtenOff = P - charged;
const used = B + charged;
const upFront = B >= L;
let state: "under" | "approaching" | "reached" | "exceeded";
if (estimate ? used > L : writtenOff > 0) state = "exceeded";
else if (estimate ? used === L : used >= L) state = "reached";
else if (T !== null && used * 100 >= T * L) state = "approaching";
else state = "under";
// Floored, so a figure just under the threshold or 100% never prints as having reached it.
const pct = Math.floor(used * 100 / L);
let status: string;
if (state === "under") {
status = fmt(used) + " of " + phrase + " of " + fmt(L) + " has been billed, including this invoice.";
} else if (state === "approaching") {
status = fmt(used) + " of " + phrase + " of " + fmt(L) + " has been billed, including this invoice: " + pct +
"% of it.";
} else if (state === "reached") {
status = upFront
? Phrase + " of " + fmt(L) + " was reached on an earlier invoice. Nothing further is charged."
: !estimate
? "This invoice brings fees billed to " + phrase + " of " + fmt(L) + ". Work beyond it will not be charged."
: "This invoice brings fees billed to " + phrase + " of " + fmt(L) +
". Work beyond it will be charged only once a revised estimate has been given.";
} else if (estimate) {
status = fmt(used) + " has been billed, including this invoice, against " + phrase + " of " + fmt(L) + ".";
} else {
status = upFront
? Phrase + " of " + fmt(L) + " was reached on an earlier invoice. Fees of " + fmt(writtenOff) +
" for this period are above it and are not charged."
: "This invoice reaches " + phrase + " of " + fmt(L) + ". Fees of " + fmt(writtenOff) +
" above it are not charged.";
}
let incomplete: string | null = null;
if (estimate && state === "exceeded") {
const against = rev
? "our revised estimate of " + fmt(L) + ", notified on " + day(rev.notifiedOn) + ", and no later estimate"
: "our estimate of " + fmt(L) + ", and no revised estimate";
incomplete = "Fee estimate incomplete: fees billed to date, including this invoice, are " + fmt(used) +
", above " + against +
" is recorded. An overrun the client was not told of can be challenged. Record the revised estimate and the date the client was told before this invoice is issued.";
}
const revised = rev
? "Our estimate of " + fmt(minor(fc.amount)) + " was revised to " + fmt(L) + ", and you were told on " +
day(rev.notifiedOn) + "."
: null;
const notice = kind === "ceiling" && state === "approaching" && T !== null
? "This is our notice that fees billed have reached " + pctFmt.format(T) + "% of the ceiling."
: null;
let withheld = 0;
let retention: string | null = null;
let withheldLabel: string | null = null;
if (wh) {
const Lw = minor(wh.limit);
const W0 = minor(wh.withheldToDate);
const room = Math.max(0, Lw - W0);
const byPercent = Math.round(charged * wh.percent / 100);
withheld = Math.min(byPercent, room);
if (room === 0) {
retention = "Retention has reached its agreed limit of " + fmt(Lw) +
", so nothing is retained from this invoice.";
} else if (withheld === 0) {
retention = null;
} else if (W0 + withheld === Lw) {
retention = "We have retained " + fmt(withheld) + " of this invoice under the agreement. That brings retention to its agreed limit of " +
fmt(Lw) + ", and nothing more will be retained.";
} else {
retention = "We have retained " + fmt(withheld) + " (" + pctFmt.format(wh.percent) +
"%) of this invoice under the agreement: " + fmt(W0 + withheld) + " retained to date, against a limit of " +
fmt(Lw) + ".";
}
withheldLabel = withheld === byPercent
? "Retained (" + pctFmt.format(wh.percent) + "%)"
: "Retained (to the agreed limit)";
}
const payable = charged - withheld;
const showRemaining = state === "under" || state === "approaching";
return {
heading,
state,
status,
incomplete,
revised,
notice,
retention,
capLabel: kind === "hard" ? "Agreed cap" : kind === "ceiling" ? "Ceiling" : rev ? "Revised estimate" : "Estimate",
capValue: fmt(L),
billedToDate: fmt(B),
thisPeriod: fmt(P),
writtenOffLabel: writtenOff > 0 ? "Above the " + noun + ", not charged" : null,
writtenOff: writtenOff > 0 ? fmt(writtenOff) : null,
charged: writtenOff > 0 ? fmt(charged) : null,
withheldLabel: withheld > 0 ? withheldLabel : null,
withheld: withheld > 0 ? fmt(withheld) : null,
payable: withheld > 0 ? fmt(payable) : null,
remainingLabel: showRemaining ? "Remaining under the " + noun : null,
remaining: showRemaining ? fmt(Math.max(0, L - used)) : null,
amounts: {
charged: major(charged),
writtenOff: major(writtenOff),
withheld: major(withheld),
payable: major(payable),
},
};
},
}); arrangements/fee-cap-status/lines.ts /**
* What the fee cap status hands each of its arrangements: every figure it may
* print, already decided and formatted. An arrangement places these and
* decides nothing, so both print the same rows under the same conditions.
*
* A field that is `null` is a row this invoice does not carry. Test the value
* in the JSX, `{lines.writtenOff && …}`, so the test is compiled into a
* condition the engine settles per document.
*
* Installed by `dxcl add fee-cap-status`, with the arrangements.
*/
export interface FeeCapStatusLines {
/** The cap row's label: "Agreed cap", "Ceiling", "Estimate" or "Revised estimate". */
capLabel: string;
/** The limit fees are measured against. */
capValue: string;
/** Fees charged on earlier invoices. */
billedToDate: string;
/** Fees for this period, before the cap and withholding. */
thisPeriod: string;
/** "Above the cap, not charged" or "Above the ceiling, not charged"; null when nothing is written off. */
writtenOffLabel: string | null;
/** The fees above the limit that are not charged, or null. */
writtenOff: string | null;
/** What this invoice charges; null unless something is written off, since otherwise it equals the period's fees. */
charged: string | null;
/** "Retained (5%)" or "Retained (to the agreed limit)"; null when nothing is retained. */
withheldLabel: string | null;
/** The retention held back on this invoice, or null. */
withheld: string | null;
/** What is payable for these fees after retention, or null. */
payable: string | null;
/** "Remaining under the cap" and so on; null once the limit is reached or passed. */
remainingLabel: string | null;
/** What is left under the limit, or null. */
remaining: string | null;
} arrangements/fee-cap-status/table.arrangement.tsx import { Cell, Row, Table, type Yield } from "docxcelerate/template";
import type { FeeCapStatusLines } from "./lines.ts";
/**
* Labels in a column with the amounts right-aligned beside them, so a reader
* can check cap, billed and charged against each other by eye. The default.
*/
export const table = (lines: FeeCapStatusLines): Yield => (
// 40mm holds "£2,500,000.00" on one line.
<Table id="fee-cap-figures" columns={[{ width: "auto" }, { width: 40, align: "right" }]}>
<Row id="fee-cap-amount">
<Cell>{lines.capLabel}</Cell>
<Cell>{lines.capValue}</Cell>
</Row>
<Row id="fee-cap-billed">
<Cell>Billed before this invoice</Cell>
<Cell>{lines.billedToDate}</Cell>
</Row>
<Row id="fee-cap-period">
<Cell>Fees this period</Cell>
<Cell>{lines.thisPeriod}</Cell>
</Row>
{lines.writtenOff && (
<Row id="fee-cap-written-off">
<Cell>{lines.writtenOffLabel}</Cell>
<Cell>{lines.writtenOff}</Cell>
</Row>
)}
{lines.charged && (
<Row id="fee-cap-charged">
<Cell>Charged on this invoice</Cell>
<Cell>{lines.charged}</Cell>
</Row>
)}
{lines.withheld && (
<Row id="fee-cap-withheld">
<Cell>{lines.withheldLabel}</Cell>
<Cell>{lines.withheld}</Cell>
</Row>
)}
{lines.payable && (
<Row id="fee-cap-payable">
<Cell>Payable for these fees</Cell>
<Cell>{lines.payable}</Cell>
</Row>
)}
{lines.remaining && (
<Row id="fee-cap-remaining">
<Cell>{lines.remainingLabel}</Cell>
<Cell>{lines.remaining}</Cell>
</Row>
)}
</Table>
); arrangements/fee-cap-status/stacked.arrangement.tsx import { Paragraph, type Yield } from "docxcelerate/template";
import type { FeeCapStatusLines } from "./lines.ts";
/**
* One labelled figure under another, down the text column. Pick it where the
* figures sit in running text and nothing has to line up with anything.
*/
export const stacked = (lines: FeeCapStatusLines): Yield => (
<>
<Paragraph id="fee-cap-amount">{lines.capLabel}: {lines.capValue}</Paragraph>
<Paragraph id="fee-cap-billed">Billed before this invoice: {lines.billedToDate}</Paragraph>
<Paragraph id="fee-cap-period">Fees this period: {lines.thisPeriod}</Paragraph>
{lines.writtenOff && <Paragraph id="fee-cap-written-off">{lines.writtenOffLabel}: {lines.writtenOff}</Paragraph>}
{lines.charged && <Paragraph id="fee-cap-charged">Charged on this invoice: {lines.charged}</Paragraph>}
{lines.withheld && <Paragraph id="fee-cap-withheld">{lines.withheldLabel}: {lines.withheld}</Paragraph>}
{lines.payable && <Paragraph id="fee-cap-payable">Payable for these fees: {lines.payable}</Paragraph>}
{lines.remaining && <Paragraph id="fee-cap-remaining">{lines.remainingLabel}: {lines.remaining}</Paragraph>}
</>
);