Commitment drawdown
BodyApplies prepaid commitment and credit grants to each usage line in invoice order, before tax, and splits the line where a balance runs out into a covered part and an overage part, exact in minor units. A grant counts if it was live on the usage date, not the invoice date, so usage from the last days of a period still draws on a grant that expired before the invoice. Rollover burns first, then paid commitment, then promotional credit, and within each by priority then earliest expiry, so the credit closest to lapsing is used first. Unit grants such as minutes cover only the prices they name, and their overage is priced at the line's unit price. On the invoice that ends the term, the minimum commitment is trued up against eligible spend, which excludes promotional credit, less true-ups already billed. Credits expiring soon are named, with what is projected to go unused. The tax basis decides whether only the overage carries VAT or the full usage does, with the credit deducted after tax. All of it is one deriver.
npx dxcl add commitment-drawdown drawdown.creditTaxBasis Preview data
the JSON this preview was built with{
"drawdown": {
"currency": "USD",
"invoiceDate": "2026-07-02",
"period": {
"start": "2026-06-01",
"end": "2026-06-30"
},
"term": {
"start": "2025-07-01",
"end": "2026-06-30",
"commitment": 300000000,
"eligibleSpendToDate": 198450000,
"trueUpsBilled": 2500000
},
"creditTaxBasis": "taxed-at-purchase",
"warnDays": 30,
"lines": [
{
"key": "L1",
"description": "Inference API: frontier model, input tokens (EU data residency)",
"usageDate": "2026-06-30",
"quantity": 18400000000,
"unit": "tokens",
"unitPrice": 0.0003,
"amount": 5520000,
"priceId": "price_frontier_input_eu"
},
{
"key": "L2",
"description": "Inference API: frontier model, output tokens (EU data residency)",
"usageDate": "2026-06-30",
"quantity": 2950000000,
"unit": "tokens",
"unitPrice": 0.0015,
"amount": 4425000,
"priceId": "price_frontier_output_eu"
},
{
"key": "L3",
"description": "Speech-to-text transcription, enhanced accuracy tier",
"usageDate": "2026-06-30",
"quantity": 1284750.5,
"unit": "minutes",
"unitPrice": 2.4,
"amount": 3083401,
"priceId": "price_stt_enhanced"
},
{
"key": "L4",
"description": "Vector storage, GB-months (multi-region replicated)",
"usageDate": "2026-06-30",
"quantity": 48250.75,
"unit": "GB-months",
"unitPrice": 23,
"amount": 1109767,
"priceId": "price_vector_storage"
},
{
"key": "L5",
"description": "Dedicated capacity reservation: 8 accelerator nodes, eu-west",
"usageDate": "2026-06-30",
"quantity": 720,
"unit": "hours",
"unitPrice": 98000,
"amount": 70560000,
"priceId": "price_dedicated_capacity"
},
{
"key": "L6",
"description": "Batch inference: frontier model, input tokens (batch discount)",
"usageDate": "2026-06-30",
"quantity": 9200000000,
"unit": "tokens",
"unitPrice": 0.00015,
"amount": 1380000,
"priceId": "price_frontier_batch_input"
},
{
"key": "L7",
"description": "Premium support: 24/7 enterprise response (monthly)",
"usageDate": "2026-06-30",
"quantity": 1,
"unitPrice": 4500000,
"amount": 4500000,
"priceId": "price_support_enterprise"
}
],
"grants": [
{
"id": "g-roll",
"name": "Rollover from the 2024–25 annual commitment",
"kind": "rollover",
"denomination": "money",
"balance": 12500000,
"priority": 1,
"effective": "2025-07-01",
"expires": "2026-07-01"
},
{
"id": "g-commit",
"name": "Annual prepaid commitment 2025–26 (enterprise platform agreement)",
"kind": "commit",
"denomination": "money",
"balance": 48000000,
"priority": 1,
"effective": "2025-07-01",
"expires": "2026-07-31",
"dailyBurn": 1600000
},
{
"id": "g-minutes",
"name": "Prepaid transcription minutes bundle, enhanced tier",
"kind": "commit",
"denomination": "units",
"unit": "minutes",
"balance": 1000000,
"priority": 0,
"effective": "2025-07-01",
"expires": "2026-07-15",
"priceIds": [
"price_stt_enhanced"
],
"dailyBurn": 9500
},
{
"id": "g-promo",
"name": "Launch partner promotional credit (frontier models)",
"kind": "promotional",
"denomination": "money",
"balance": 2500000,
"effective": "2026-01-01",
"expires": "2026-12-31",
"priceIds": [
"price_frontier_input_eu",
"price_frontier_output_eu"
]
}
]
}
} {
"drawdown": {
"currency": "USD",
"invoiceDate": "2026-07-02",
"period": {
"start": "2026-06-01",
"end": "2026-06-30"
},
"term": {
"start": "2025-07-01",
"end": "2026-06-30",
"commitment": 300000000,
"eligibleSpendToDate": 198450000,
"trueUpsBilled": 2500000
},
"creditTaxBasis": "multi-purpose",
"warnDays": 30,
"lines": [
{
"key": "L1",
"description": "Inference API: frontier model, input tokens (EU data residency)",
"usageDate": "2026-06-30",
"quantity": 18400000000,
"unit": "tokens",
"unitPrice": 0.0003,
"amount": 5520000,
"priceId": "price_frontier_input_eu"
},
{
"key": "L2",
"description": "Inference API: frontier model, output tokens (EU data residency)",
"usageDate": "2026-06-30",
"quantity": 2950000000,
"unit": "tokens",
"unitPrice": 0.0015,
"amount": 4425000,
"priceId": "price_frontier_output_eu"
},
{
"key": "L3",
"description": "Speech-to-text transcription, enhanced accuracy tier",
"usageDate": "2026-06-30",
"quantity": 1284750.5,
"unit": "minutes",
"unitPrice": 2.4,
"amount": 3083401,
"priceId": "price_stt_enhanced"
},
{
"key": "L4",
"description": "Vector storage, GB-months (multi-region replicated)",
"usageDate": "2026-06-30",
"quantity": 48250.75,
"unit": "GB-months",
"unitPrice": 23,
"amount": 1109767,
"priceId": "price_vector_storage"
},
{
"key": "L5",
"description": "Dedicated capacity reservation: 8 accelerator nodes, eu-west",
"usageDate": "2026-06-30",
"quantity": 720,
"unit": "hours",
"unitPrice": 98000,
"amount": 70560000,
"priceId": "price_dedicated_capacity"
},
{
"key": "L6",
"description": "Batch inference: frontier model, input tokens (batch discount)",
"usageDate": "2026-06-30",
"quantity": 9200000000,
"unit": "tokens",
"unitPrice": 0.00015,
"amount": 1380000,
"priceId": "price_frontier_batch_input"
},
{
"key": "L7",
"description": "Premium support: 24/7 enterprise response (monthly)",
"usageDate": "2026-06-30",
"quantity": 1,
"unitPrice": 4500000,
"amount": 4500000,
"priceId": "price_support_enterprise"
}
],
"grants": [
{
"id": "g-roll",
"name": "Rollover from the 2024–25 annual commitment",
"kind": "rollover",
"denomination": "money",
"balance": 12500000,
"priority": 1,
"effective": "2025-07-01",
"expires": "2026-07-01"
},
{
"id": "g-commit",
"name": "Annual prepaid commitment 2025–26 (enterprise platform agreement)",
"kind": "commit",
"denomination": "money",
"balance": 48000000,
"priority": 1,
"effective": "2025-07-01",
"expires": "2026-07-31",
"dailyBurn": 1600000
},
{
"id": "g-minutes",
"name": "Prepaid transcription minutes bundle, enhanced tier",
"kind": "commit",
"denomination": "units",
"unit": "minutes",
"balance": 1000000,
"priority": 0,
"effective": "2025-07-01",
"expires": "2026-07-15",
"priceIds": [
"price_stt_enhanced"
],
"dailyBurn": 9500
},
{
"id": "g-promo",
"name": "Launch partner promotional credit (frontier models)",
"kind": "promotional",
"denomination": "money",
"balance": 2500000,
"effective": "2026-01-01",
"expires": "2026-12-31",
"priceIds": [
"price_frontier_input_eu",
"price_frontier_output_eu"
]
}
]
}
} Resolved nodes
what a renderer receives — 1 nodescommitment-drawdown section commitment-drawdown section The files
what installing writes; the selected file is the componentnodes/commitment-drawdown.node.tsx import { Cell, type Nodes, Paragraph, Row, Section, Table, useDeriver, useState } from "docxcelerate/template";
import commitmentDrawdown from "../derivers/commitment-drawdown.deriver.ts";
/**
* A usage invoice section that draws prepaid commitment and credit grants down
* line by line, before tax, and says what is left, what is about to lapse, and
* whether the term's minimum was met.
*
* Decisions already made for you:
*
* - Covered and overage are split per line, not on the total. Applying credit
* to the total loses which usage was charged, and puts tax on the wrong base.
* - Whether a grant may be used is tested on the usage date, not the invoice
* date. June usage invoiced on 2 July still draws on a grant that expired on
* 1 July.
* - Burn order is by type (rollover, then paid commitment, then promotional),
* and within a type by priority (lower first), then earliest expiry, then
* earliest effective date, then earliest creation. The credit closest to
* expiring is used before it lapses, instead of being picked first-in-first-out.
* - Promotional credit never counts toward a minimum commitment.
* - The true-up runs only on the invoice that ends the term, and subtracts
* true-ups already billed.
* - Credits about to expire are named, with the amount projected to go unused
* when a burn rate is known.
* - The tax basis is decided from how the credit was sold. Credit taxed when
* bought (a prepayment or a single-purpose voucher): only the overage carries
* VAT here. A multi-purpose voucher: VAT falls on the full usage, and the
* credit is deducted after tax like a payment. This is the one choice that
* changes what the customer owes.
*
* All of it is one deriver, because every step is arithmetic, sorting or date
* maths on request data, and publishing refuses all of those. The node computes
* nothing: it prints the deriver's strings and branches on its flags, with
* every test written inline so a publish build keeps each arm.
*
* The lines are six fixed slots and the grants four, 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 nothing.
*
* The node publishes 18 branches against the default `branchLimit` of 32.
*
* Installed by `dxcl add commitment-drawdown`.
*/
/** What this component reads. Add these fields to your document data type. */
export interface CommitmentDrawdownData {
drawdown: {
/**
* ISO 4217 code every money amount is in: `"GBP"`, `"USD"`, `"JPY"`. It also
* sets how many minor units make one major unit. Required: the deriver throws
* when it is missing or not a code `Intl` knows.
*/
currency: string;
/**
* The invoice's issue date, ISO 8601. Used only for the expiry warnings and
* to mark a grant as expired; never to decide whether a grant could be used.
* Anything after the tenth character is ignored. Required: throws when
* missing or not YYYY-MM-DD.
*/
invoiceDate: string;
/**
* The usage period this invoice bills, ISO 8601, `end` inclusive. `end` is
* the usage date of any line without one, and is compared with `term.end`
* to decide whether this invoice closes the term. Required: throws when
* either end is missing or not a date, or when `end` is before `start`.
*/
period: { start: string; end: string };
/**
* The commitment term, when the contract has a minimum spend. Missing means
* no minimum: no true-up, and no true-up line on any invoice.
*/
term?: {
/** First day of the term, ISO 8601. Required when `term` is given; printed in the true-up line. */
start: string;
/** Last day of the term, ISO 8601. Required when `term` is given. */
end: string;
/**
* The minimum spend over the whole term, in integer minor units. Throws
* when it is not a non-negative integer. Zero means no true-up.
*/
commitment: number;
/**
* Eligible spend already billed on EARLIER invoices in this term, minor
* units: usage charged plus usage covered by paid commitment or rollover,
* never usage covered by promotional credit. Not including this invoice.
* Missing means 0. Throws when present and not a non-negative integer.
*/
eligibleSpendToDate?: number;
/**
* True-ups already billed against this term, minor units. Missing means 0.
* Throws when present and not a non-negative integer.
*/
trueUpsBilled?: number;
};
/**
* The priced usage lines, in invoice order. Grants are drawn in this order.
* Every line counts toward the minimum commitment, so leave out charges that
* do not. Missing or empty means nothing to draw against.
*/
lines?: Array<{
/** Your reference for the line, echoed in the deriver's `allocation`. Missing means its index. */
key?: string;
/** What the line is, as printed. Required: throws when missing or blank. */
description: string;
/**
* The day the usage happened, ISO 8601. For a line covering the whole
* period, the last day of usage. Missing means `period.end`, so a grant
* has to still be live on the last day to cover it. Never the invoice date.
*/
usageDate?: string;
/** How much was used, in the line's unit. Throws when it is not a finite number of 0 or more. */
quantity: number;
/**
* Decimal places the quantity is counted in (0 for tokens, 1 for minutes
* to the tenth). An overage quantity is rounded to this. Missing means the
* number of decimals `quantity` was given with, at most 6.
*/
quantityDecimals?: number;
/** The unit, printed after an overage quantity: `"hours"`, `"tokens"`. Missing prints the bare number. */
unit?: string;
/**
* Price of one unit in minor units, fractions allowed (0.0003 for $3 per
* million tokens). Read only when a unit-denominated grant covers the
* line, to price its overage. Throws then if it is missing or not a finite
* number of 0 or more.
*/
unitPrice?: number;
/**
* What the line costs before any credit, in integer minor units. This is
* authoritative: it is not recomputed from quantity × unitPrice, so tiered
* pricing is honoured. Zero draws nothing and is not printed. Throws when
* it is not a non-negative integer: a refund or an adjustment is not usage.
*/
amount: number;
/** The price the line was billed at, matched against a grant's `priceIds`. Missing means only unscoped grants cover it. */
priceId?: string;
}>;
/**
* Every grant with a balance going into this invoice, in any order: they are
* sorted into burn order. Missing or empty means nothing is drawn, and the
* component prints nothing unless a true-up is due.
*/
grants?: Array<{
/** Your id for the grant, echoed in `balances`. Required. */
id: string;
/** What the grant is called, as printed: `"Annual prepaid commitment 2025–26"`. Required. */
name: string;
/**
* `rollover`: unused paid commitment carried from an earlier term.
* `commit`: paid commitment for this term. `promotional`: free credit.
* Rollover burns first and promotional last. Promotional credit is a
* discount, so it never counts toward the minimum and is always taken off
* before tax. Required: anything else throws.
*/
kind: "rollover" | "commit" | "promotional";
/**
* `money`: `balance` is integer minor units. `units`: `balance` is a count
* of the lines' units (tokens, minutes). Required: anything else throws.
*/
denomination: "money" | "units";
/** Printed after a units balance: `"minutes"`. Missing prints `"units"`. Ignored for money. */
unit?: string;
/**
* What is left going into this invoice. Money: a non-negative integer.
* Units: a finite number of 0 or more. Throws otherwise. Zero is skipped.
*/
balance: number;
/** Burn order within its kind, lower first. Missing sorts after every numbered grant of its kind. */
priority?: number;
/** First day the grant may be used, ISO 8601, inclusive. Required: throws when missing or not a date. */
effective: string;
/**
* The day the grant stops covering usage, ISO 8601. It covers usage dated
* strictly before this day. Missing means it never expires: it sorts after
* dated grants and never warns.
*/
expires?: string;
/** When the grant was created, ISO 8601. The last tie-breaker. Missing falls back to input order. */
created?: string;
/**
* The prices this grant may cover. Missing or empty covers every line.
* Required (non-empty) for a `units` grant: throws without it, because
* minutes must not be spent on tokens.
*/
priceIds?: string[];
/**
* Trailing average draw per day, in the grant's denomination (minor units
* or units). Used only to project how much of an expiring grant goes
* unused. Missing means the warning names the expiry without a projection.
*/
dailyBurn?: number;
}>;
/**
* How the paid credit (commit and rollover) was taxed.
* `taxed-at-purchase`: VAT was charged when it was bought (a prepayment or
* a single-purpose voucher), so only overage carries VAT here.
* `multi-purpose`: a multi-purpose voucher, so VAT falls on the full usage
* now and the credit is deducted after VAT like a payment. Required: throws
* when missing or anything else. Guessing either way changes what the
* customer owes.
*/
creditTaxBasis: "taxed-at-purchase" | "multi-purpose";
/**
* How many days after `invoiceDate` an expiring grant is warned about,
* inclusive. Missing means 30. Throws when present and not a non-negative
* integer. 0 turns the warnings off.
*/
warnDays?: number;
};
}
/**
* Prints the usage lines with what credit covered and what was charged, the
* state of each grant, the tax basis and any true-up. Prints nothing when there
* is nothing to say.
*/
export const CommitmentDrawdown: Nodes = async () => {
const [drawdown] = useState((data: CommitmentDrawdownData) => data.drawdown);
const d = await useDeriver(commitmentDrawdown, [drawdown]);
return (
<>
{d.show && (
<Section id="commitment-drawdown" title="Prepaid credit applied">
<Paragraph id="commitment-drawdown-intro">
Prepaid credit was applied to the usage for {d.periodLabel} line by line and before tax: rollover first, then
prepaid commitment, then promotional credit.
</Paragraph>
{d.showLines && (
<Table
id="commitment-drawdown-lines"
columns={[{ width: "auto" }, { width: 30, align: "right" }, { width: 30, align: "right" }, { width: 36, align: "right" }]}
>
<Row id="commitment-drawdown-lines-header" header>
<Cell>Usage</Cell>
<Cell>Amount</Cell>
<Cell>Covered by credit</Cell>
<Cell>Charged</Cell>
</Row>
{d.lines[0].description && (
<Row id="commitment-drawdown-line-1">
<Cell>{d.lines[0].description}</Cell>
<Cell>{d.lines[0].usage}</Cell>
<Cell>{d.lines[0].covered}</Cell>
<Cell>{d.lines[0].charged}</Cell>
</Row>
)}
{d.lines[1].description && (
<Row id="commitment-drawdown-line-2">
<Cell>{d.lines[1].description}</Cell>
<Cell>{d.lines[1].usage}</Cell>
<Cell>{d.lines[1].covered}</Cell>
<Cell>{d.lines[1].charged}</Cell>
</Row>
)}
{d.lines[2].description && (
<Row id="commitment-drawdown-line-3">
<Cell>{d.lines[2].description}</Cell>
<Cell>{d.lines[2].usage}</Cell>
<Cell>{d.lines[2].covered}</Cell>
<Cell>{d.lines[2].charged}</Cell>
</Row>
)}
{d.lines[3].description && (
<Row id="commitment-drawdown-line-4">
<Cell>{d.lines[3].description}</Cell>
<Cell>{d.lines[3].usage}</Cell>
<Cell>{d.lines[3].covered}</Cell>
<Cell>{d.lines[3].charged}</Cell>
</Row>
)}
{d.lines[4].description && (
<Row id="commitment-drawdown-line-5">
<Cell>{d.lines[4].description}</Cell>
<Cell>{d.lines[4].usage}</Cell>
<Cell>{d.lines[4].covered}</Cell>
<Cell>{d.lines[4].charged}</Cell>
</Row>
)}
{d.lines[5].description && (
<Row id="commitment-drawdown-line-6">
<Cell>{d.lines[5].description}</Cell>
<Cell>{d.lines[5].usage}</Cell>
<Cell>{d.lines[5].covered}</Cell>
<Cell>{d.lines[5].charged}</Cell>
</Row>
)}
<Row id="commitment-drawdown-lines-total">
<Cell>Total</Cell>
<Cell>{d.totals.usage}</Cell>
<Cell>{d.totals.covered}</Cell>
<Cell>{d.totals.charged}</Cell>
</Row>
</Table>
)}
{d.showGrants && (
<Table
id="commitment-drawdown-grants"
columns={[{ width: "auto" }, { width: 34, align: "right" }, { width: 30, align: "right" }, { width: 50 }]}
>
<Row id="commitment-drawdown-grants-header" header>
<Cell>Credit</Cell>
<Cell>Applied</Cell>
<Cell>Remaining</Cell>
<Cell>Notes</Cell>
</Row>
{d.grants[0].name && (
<Row id="commitment-drawdown-grant-1">
<Cell>{d.grants[0].name}</Cell>
<Cell>{d.grants[0].applied}</Cell>
<Cell>{d.grants[0].remaining}</Cell>
<Cell>{d.grants[0].note}</Cell>
</Row>
)}
{d.grants[1].name && (
<Row id="commitment-drawdown-grant-2">
<Cell>{d.grants[1].name}</Cell>
<Cell>{d.grants[1].applied}</Cell>
<Cell>{d.grants[1].remaining}</Cell>
<Cell>{d.grants[1].note}</Cell>
</Row>
)}
{d.grants[2].name && (
<Row id="commitment-drawdown-grant-3">
<Cell>{d.grants[2].name}</Cell>
<Cell>{d.grants[2].applied}</Cell>
<Cell>{d.grants[2].remaining}</Cell>
<Cell>{d.grants[2].note}</Cell>
</Row>
)}
{d.grants[3].name && (
<Row id="commitment-drawdown-grant-4">
<Cell>{d.grants[3].name}</Cell>
<Cell>{d.grants[3].applied}</Cell>
<Cell>{d.grants[3].remaining}</Cell>
<Cell>{d.grants[3].note}</Cell>
</Row>
)}
</Table>
)}
{d.expiring && <Paragraph id="commitment-drawdown-expiring">{d.expiring}</Paragraph>}
{d.taxArm === "purchase" && <Paragraph id="commitment-drawdown-tax-purchase">{d.taxNote}</Paragraph>}
{d.taxArm === "redemption" && <Paragraph id="commitment-drawdown-tax-redemption">{d.taxNote}</Paragraph>}
{d.trueUpArm === "shortfall" && <Paragraph id="commitment-drawdown-true-up">{d.trueUpNote}</Paragraph>}
{d.trueUpArm === "met" && <Paragraph id="commitment-drawdown-commitment-met">{d.trueUpNote}</Paragraph>}
</Section>
)}
</>
);
}; derivers/commitment-drawdown.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Draws prepaid commitment and credit grants down against priced usage lines,
* line by line and before tax, and decides the tax basis, the expiry warnings
* and the minimum-commitment true-up. Installed by `dxcl add commitment-drawdown`.
*
* 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: "commitmentDrawdown",
run: (drawdown: unknown) => {
const dd = drawdown as any;
// Currency first: the exponent decides how every amount is read and printed.
let money: Intl.NumberFormat;
try {
money = new Intl.NumberFormat("en-GB", { style: "currency", currency: dd?.currency });
} catch {
throw new Error("drawdown.currency must be an ISO 4217 code");
}
const exponent = money.resolvedOptions().maximumFractionDigits as number;
const fmtMoney = (minor: number) => money.format(minor / 10 ** exponent);
const fmtNum = (n: number, dec = 6) => new Intl.NumberFormat("en-GB", { maximumFractionDigits: dec }).format(n);
const isoDay = (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");
}
return value.slice(0, 10);
};
const dayIndex = (iso: string) => {
const [y, m, d] = iso.split("-").map(Number);
return Date.UTC(y, m - 1, d) / 86_400_000;
};
const dates = new Intl.DateTimeFormat("en-GB", { dateStyle: "long", timeZone: "UTC" });
const fmt = (iso: string) => dates.format(new Date(iso + "T00:00:00Z"));
const minorOf = (value: unknown, field: string): number => {
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
throw new Error(field + " must be a non-negative integer of minor units");
}
return value;
};
const countOf = (value: unknown, field: string): number => {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
throw new Error(field + " must be a finite number of 0 or more");
}
return value;
};
// Half away from zero; every input is >= 0, so this is round-half-up.
const round = (x: number, dec = 0) => {
const f = 10 ** dec;
return (Math.sign(x) * Math.round(Math.abs(x) * f)) / f;
};
const decimalsOf = (n: number) => {
const s = String(n);
return s.includes("e") ? 6 : Math.min(6, (s.split(".")[1] ?? "").length);
};
const cmp = (a: any, b: any) => (a < b ? -1 : a > b ? 1 : 0);
const invoiceDay = isoDay(dd?.invoiceDate, "drawdown.invoiceDate");
const startDay = isoDay(dd?.period?.start, "drawdown.period.start");
const endDay = isoDay(dd?.period?.end, "drawdown.period.end");
if (endDay < startDay) throw new Error("drawdown.period.end is before drawdown.period.start");
if (dd?.creditTaxBasis !== "taxed-at-purchase" && dd?.creditTaxBasis !== "multi-purpose") {
throw new Error('drawdown.creditTaxBasis must be "taxed-at-purchase" or "multi-purpose"');
}
const basis: string = dd.creditTaxBasis;
let warnDays = 30;
if (dd.warnDays !== undefined) {
if (typeof dd.warnDays !== "number" || !Number.isInteger(dd.warnDays) || dd.warnDays < 0) {
throw new Error("drawdown.warnDays must be a non-negative integer");
}
warnDays = dd.warnDays;
}
let term: { start: string; end: string; commitment: number; toDate: number; billed: number } | undefined;
if (dd.term) {
term = {
start: isoDay(dd.term.start, "drawdown.term.start"),
end: isoDay(dd.term.end, "drawdown.term.end"),
commitment: minorOf(dd.term.commitment, "drawdown.term.commitment"),
toDate: dd.term.eligibleSpendToDate === undefined
? 0
: minorOf(dd.term.eligibleSpendToDate, "drawdown.term.eligibleSpendToDate"),
billed: dd.term.trueUpsBilled === undefined ? 0 : minorOf(dd.term.trueUpsBilled, "drawdown.term.trueUpsBilled"),
};
}
const lines = (Array.isArray(dd.lines) ? dd.lines : []).map((l: any, i: number) => {
const f = "drawdown.lines[" + i + "]";
if (typeof l?.description !== "string" || l.description.trim() === "") throw new Error(f + ".description is required");
const quantity = countOf(l.quantity, f + ".quantity");
const decimals = l.quantityDecimals === undefined
? decimalsOf(quantity)
: (Number.isInteger(l.quantityDecimals) && l.quantityDecimals >= 0 && l.quantityDecimals <= 6
? l.quantityDecimals
: (() => { throw new Error(f + ".quantityDecimals must be an integer from 0 to 6"); })());
return {
i,
key: typeof l.key === "string" && l.key !== "" ? l.key : String(i),
description: l.description as string,
usageDay: l.usageDate === undefined ? endDay : isoDay(l.usageDate, f + ".usageDate"),
quantity,
decimals,
unit: l.unit as string | undefined,
priceId: l.priceId as string | undefined,
amount: minorOf(l.amount, f + ".amount"),
raw: l,
};
});
const kindRank: Record<string, number> = { rollover: 0, commit: 1, promotional: 2 };
const kindLabel: Record<string, string> = { rollover: "rollover", commit: "prepaid commitment", promotional: "promotional" };
const grants = (Array.isArray(dd.grants) ? dd.grants : []).map((g: any, i: number) => {
const f = "drawdown.grants[" + i + "]";
if (typeof g?.id !== "string" || g.id === "") throw new Error(f + ".id is required");
if (typeof g.name !== "string" || g.name.trim() === "") throw new Error(f + ".name is required");
if (!(g.kind in kindRank)) throw new Error(f + '.kind must be "rollover", "commit" or "promotional"');
if (g.denomination !== "money" && g.denomination !== "units") throw new Error(f + '.denomination must be "money" or "units"');
const units = g.denomination === "units";
const balance = units ? countOf(g.balance, f + ".balance") : minorOf(g.balance, f + ".balance");
const priceIds: string[] = Array.isArray(g.priceIds) ? g.priceIds : [];
if (units && priceIds.length === 0) throw new Error(f + ".priceIds is required for a units grant");
if (g.priority !== undefined && (typeof g.priority !== "number" || Number.isNaN(g.priority))) {
throw new Error(f + ".priority must be a number");
}
return {
i,
id: g.id as string,
name: g.name as string,
kind: g.kind as string,
units,
unit: (g.unit ?? "units") as string,
start: balance,
balance,
priority: g.priority === undefined ? Infinity : (g.priority as number),
effective: isoDay(g.effective, f + ".effective"),
expires: g.expires === undefined ? undefined : isoDay(g.expires, f + ".expires"),
created: g.created === undefined ? "" : isoDay(g.created, f + ".created"),
priceIds,
dailyBurn: g.dailyBurn === undefined ? undefined : countOf(g.dailyBurn, f + ".dailyBurn"),
dec: units ? decimalsOf(balance) : 0,
drawnMinor: 0,
drawnUnits: 0,
};
});
// Burn order: type, priority, soonest expiry, earliest effective, earliest created, input.
const order = grants.filter((g: any) => g.balance > 0).sort((a: any, b: any) =>
cmp(kindRank[a.kind], kindRank[b.kind]) || cmp(a.priority, b.priority) ||
cmp(a.expires ?? "", b.expires ?? "") || cmp(a.effective, b.effective) ||
cmp(a.created, b.created) || a.i - b.i
);
const eligible = (g: any, l: any) =>
g.effective <= l.usageDay && (g.expires === undefined || g.expires > l.usageDay) &&
(g.priceIds.length === 0 || (l.priceId !== undefined && g.priceIds.includes(l.priceId)));
const results = lines.map((l: any) => {
const draws: Array<{ grantId: string; amountMinor: number; units?: number }> = [];
let remAmt = l.amount;
let remQty = l.quantity;
if (l.amount > 0) {
for (const g of order) {
if (remAmt === 0) break;
if (g.balance <= 0 || !eligible(g, l)) continue;
if (!g.units) {
const take = Math.min(g.balance, remAmt);
g.balance -= take;
remAmt -= take;
remQty = remAmt === 0 ? 0 : round((l.quantity * remAmt) / l.amount, l.decimals);
g.drawnMinor += take;
draws.push({ grantId: g.id, amountMinor: take });
} else {
if (remQty <= 0) continue;
const unitPrice = l.raw.unitPrice;
if (typeof unitPrice !== "number" || !Number.isFinite(unitPrice) || unitPrice < 0) {
throw new Error("drawdown.lines[" + l.i + "].unitPrice must be a finite number of 0 or more");
}
const takeUnits = Math.min(g.balance, remQty);
g.balance = round(g.balance - takeUnits, 6);
remQty = round(remQty - takeUnits, l.decimals);
const newAmt = remQty === 0 ? 0 : Math.min(remAmt, round(remQty * unitPrice));
g.drawnMinor += remAmt - newAmt;
g.drawnUnits = round(g.drawnUnits + takeUnits, 6);
g.dec = Math.max(g.dec, l.decimals);
draws.push({ grantId: g.id, amountMinor: remAmt - newAmt, units: takeUnits });
remAmt = newAmt;
}
}
}
return { l, draws, charged: remAmt, covered: l.amount - remAmt, chargedQuantity: remQty };
});
// Totals, in integer minor units.
let coveredPaid = 0;
let coveredPromotional = 0;
for (const g of order) {
if (g.kind === "promotional") coveredPromotional += g.drawnMinor;
else coveredPaid += g.drawnMinor;
}
const usage = results.reduce((s: number, r: any) => s + r.l.amount, 0);
const covered = coveredPaid + coveredPromotional;
const charged = usage - covered;
// Tax basis.
const taxArm = covered === 0 ? "none" : basis === "taxed-at-purchase" ? "purchase" : "redemption";
const vatBase = basis === "multi-purpose" ? charged + coveredPaid : charged;
const deductionAfterTax = basis === "multi-purpose" ? coveredPaid : 0;
const promoSentence = coveredPromotional > 0
? " Promotional credit of " + fmtMoney(coveredPromotional) + " is a discount and is taken off before VAT."
: "";
const taxNote = taxArm === "none"
? ""
: taxArm === "purchase" || coveredPaid === 0
? (taxArm === "purchase"
? "Usage covered by prepaid credit carries no VAT on this invoice, because the credit was taxed when it was bought. "
: "") + "VAT applies to the " + fmtMoney(charged) + " of usage charged." + promoSentence
: "VAT applies to " + fmtMoney(vatBase) +
" of usage, because prepaid credit is a multi-purpose voucher and is taxed when it is used. The " +
fmtMoney(coveredPaid) + " of credit applied is deducted after VAT, like a payment." + promoSentence;
// True-up: only on the invoice that ends the term.
const eligibleSpend = (term?.toDate ?? 0) + charged + coveredPaid;
let trueUpArm = "none";
let trueUpNote = "";
let trueUp = 0;
if (term && term.commitment > 0 && endDay === term.end) {
const shortfall = Math.max(0, term.commitment - eligibleSpend - term.billed);
const span = "the term " + fmt(term.start) + " to " + fmt(term.end);
if (shortfall > 0) {
trueUpArm = "shortfall";
trueUp = shortfall;
trueUpNote = "Your minimum commitment for " + span + " is " + fmtMoney(term.commitment) +
". Eligible spend over the term came to " + fmtMoney(eligibleSpend) +
(term.billed > 0 ? ", and " + fmtMoney(term.billed) + " of true-ups were billed earlier" : "") +
", so a true-up of " + fmtMoney(shortfall) +
" is charged on this invoice. Usage covered by promotional credit does not count towards the commitment.";
} else {
trueUpArm = "met";
trueUpNote = "Your minimum commitment of " + fmtMoney(term.commitment) + " for " + span +
" has been met: eligible spend came to " + fmtMoney(eligibleSpend) + ". No true-up is due.";
}
}
// Grants shown, with a note each.
const amt = (g: any, n: number) => (g.units ? fmtNum(n, g.dec) + " " + g.unit : fmtMoney(n));
const warned: Array<{ name: string; expires: string }> = [];
const shown = order.filter((g: any) =>
g.drawnMinor > 0 || g.drawnUnits > 0 ||
(g.effective <= invoiceDay && (g.expires === undefined || invoiceDay < g.expires))
).map((g: any) => {
const remaining = g.units ? round(g.balance, g.dec) : g.balance;
const days = g.expires === undefined ? 0 : dayIndex(g.expires) - dayIndex(invoiceDay);
const warns = remaining > 0 && g.expires !== undefined && days > 0 && days <= warnDays;
let note: string;
if (warns) {
note = "Expires in " + days + (days === 1 ? " day" : " days") + ", on " + fmt(g.expires) + ".";
if (g.dailyBurn !== undefined) {
const unused = remaining - round(g.dailyBurn * days, g.units ? g.dec : 0);
if (unused > 0) note += " At recent usage about " + amt(g, round(unused, g.units ? g.dec : 0)) + " will go unused.";
}
warned.push({ name: g.name, expires: g.expires });
} else if (g.expires === undefined) note = "No expiry.";
else if (g.expires <= invoiceDay) note = "Expired on " + fmt(g.expires) + "." + (remaining > 0 ? " The rest has lapsed." : "");
else note = "Expires on " + fmt(g.expires) + ".";
return { g, remaining, warns, note };
});
const expiring = warned.length === 0
? ""
: warned.length + (warned.length === 1 ? " credit expires" : " credits expire") + " within " + warnDays +
" days of this invoice: " +
new Intl.ListFormat("en-GB", { type: "conjunction" }).format(warned.map((w) => w.name + " on " + fmt(w.expires))) +
".";
const grantRow = (s: any) => {
const g = s.g;
return {
name: g.name + " (" + kindLabel[g.kind] + ")",
applied: g.drawnMinor === 0 && g.drawnUnits === 0
? "—"
: g.units
? fmtNum(g.drawnUnits, g.dec) + " " + g.unit + " (" + fmtMoney(g.drawnMinor) + ")"
: fmtMoney(g.drawnMinor),
remaining: amt(g, s.remaining),
note: s.note,
};
};
const blankGrant = () => ({ name: "", applied: "", remaining: "", note: "" });
const grantSlots = shown.length <= 4 ? shown.map(grantRow) : shown.slice(0, 3).map(grantRow);
if (shown.length > 4) {
const rest = shown.slice(3);
const unitCount = rest.filter((s: any) => s.g.units).length;
const applied = rest.reduce((n: number, s: any) => n + s.g.drawnMinor, 0);
grantSlots.push({
name: rest.length + " other credits",
applied: applied === 0 ? "—" : fmtMoney(applied),
remaining: fmtMoney(rest.reduce((n: number, s: any) => n + (s.g.units ? 0 : s.remaining), 0)) +
(unitCount > 0 ? " plus " + unitCount + (unitCount === 1 ? " unit credit" : " unit credits") : ""),
note: "",
});
}
while (grantSlots.length < 4) grantSlots.push(blankGrant());
// Display lines: zero-amount lines are not printed.
const cells = (usage: number, covered: number, charged: number) => ({
usage: fmtMoney(usage),
covered: covered === 0 ? "—" : fmtMoney(covered),
charged: charged === 0 ? "—" : fmtMoney(charged),
});
const shownLines = results.filter((r: any) => r.l.amount > 0);
const lineRow = (r: any) => {
const c = cells(r.l.amount, r.covered, r.charged);
if (r.charged > 0 && r.charged < r.l.amount) {
c.charged += " (" + fmtNum(r.chargedQuantity, r.l.decimals) + (r.l.unit ? " " + r.l.unit : "") + ")";
}
return { description: r.l.description, ...c };
};
let lineSlots: any[];
if (shownLines.length <= 6) lineSlots = shownLines.map(lineRow);
else {
const drew = shownLines.filter((r: any) => r.covered > 0).slice(0, 5);
const folded = shownLines.filter((r: any) => !drew.includes(r));
lineSlots = drew.map(lineRow);
while (lineSlots.length < 5) lineSlots.push({ description: "", usage: "", covered: "", charged: "" });
const sum = (k: string) => folded.reduce((n: number, r: any) => n + (k === "usage" ? r.l.amount : r[k]), 0);
lineSlots.push({
description: folded.length + (folded.some((r: any) => r.covered > 0) ? " further lines" : " lines not covered by credit"),
...cells(sum("usage"), sum("covered"), sum("charged")),
});
}
while (lineSlots.length < 6) lineSlots.push({ description: "", usage: "", covered: "", charged: "" });
const showLines = covered > 0;
const showGrants = shown.length > 0;
return {
show: showLines || showGrants || trueUpArm !== "none",
periodLabel: fmt(startDay) + " to " + fmt(endDay),
showLines,
lines: lineSlots,
totals: { usage: fmtMoney(usage), covered: fmtMoney(covered), charged: fmtMoney(charged) },
showGrants,
grants: grantSlots,
expiring,
taxArm,
taxNote,
trueUpArm,
trueUpNote,
minor: { usage, covered, coveredPaid, coveredPromotional, charged, vatBase, deductionAfterTax, eligibleSpend, trueUp },
allocation: results.map((r: any) => ({
key: r.l.key,
coveredMinor: r.covered,
chargedMinor: r.charged,
chargedQuantity: r.chargedQuantity,
draws: r.draws,
})),
balances: order.map((g: any) => {
const s = shown.find((x: any) => x.g === g);
const remaining = g.units ? round(g.balance, g.dec) : g.balance;
const b: { id: string; drawnMinor: number; drawnUnits?: number; remaining: number; warns: boolean } = {
id: g.id,
drawnMinor: g.drawnMinor,
remaining,
warns: s?.warns ?? false,
};
if (g.units) b.drawnUnits = g.drawnUnits;
return b;
}),
};
},
});