Credits applied to invoice
BodyCredits reduce the amount due, never the total or its VAT: a credit note adjusted VAT when it was issued and a payment on account is a means of payment, so the section sits below the VAT analysis. Credits are taken oldest first, or by your allocation, each capped at what is still owed, and what is left of each is printed as carried forward. Only credits in the invoice currency are applied; others, expired credits and disputed ones are listed with the reason. Credit notes and payments on account are grouped apart. The amount due never goes negative: when credits cover it, the section says there is nothing to pay. Integer minor units throughout, so the figures tie out, worked by a deriver that ships with it.
npx dxcl add credits-applied-to-invoice Datos de vista previa
el JSON con el que se construyó esta vista previa{
"invoice": {
"currency": "GBP",
"issueDate": "2026-11-30",
"totalMinor": 128475000,
"vatTotalMinor": 21412500
},
"credits": {
"open": [
{
"id": "CN-2026-000418/REV-1-FACILITIES-NORTH",
"kind": "credit-note",
"issuedOn": "2026-03-14",
"currency": "GBP",
"remainingMinor": 4250000
},
{
"id": "CN-2026-000771-SERVICE-LEVEL-REBATE-Q2",
"kind": "credit-note",
"issuedOn": "2026-05-30",
"currency": "GBP",
"remainingMinor": 1892745
},
{
"id": "POA-2026-07-0093-ADVANCE-MOBILISATION",
"kind": "payment-on-account",
"issuedOn": "2026-07-02",
"currency": "GBP",
"remainingMinor": 125000000
},
{
"id": "CN-2025-001207-GOODWILL-ADJUSTMENT",
"kind": "credit-note",
"issuedOn": "2025-10-31",
"currency": "GBP",
"remainingMinor": 975000,
"expiresOn": "2026-10-31"
},
{
"id": "POA-2026-09-0117-RETENTION-RELEASE",
"kind": "payment-on-account",
"issuedOn": "2026-09-15",
"currency": "GBP",
"remainingMinor": 3500000,
"disputed": true
},
{
"id": "CN-US-2026-000052-FREIGHT-OVERCHARGE",
"kind": "credit-note",
"issuedOn": "2026-06-01",
"currency": "USD",
"remainingMinor": 1250000
}
]
}
} Vista previa renderizada
el componente renderizado por su cuentaNodos resueltos
lo que recibe un renderizador — 1 nodoscredits-applied section Los archivos
lo que escribe la instalación; el archivo seleccionado es el componentenodes/credits-applied-to-invoice.node.tsx import { Cell, type Nodes, Paragraph, Row, Section, Table, useDeriver, useState } from "docxcelerate/template";
import creditsAppliedToInvoice from "../derivers/credits-applied-to-invoice.deriver.ts";
/**
* An invoice section that sets a customer's open credits (credit notes and
* payments on account) against the invoice and prints the reconciliation from
* the invoice total to the amount due.
*
* Decisions already made for you:
*
* - Credits reduce the amount due, never the invoice total or its VAT. A credit
* note adjusted VAT when it was issued and a payment on account is only a
* means of payment, so applying either before VAT would reduce the tax base a
* second time. The section belongs below the VAT analysis and its first line
* repeats the VAT-inclusive total unchanged.
* - Credits are taken oldest first and each is capped at what is still owed, or
* in the order of an explicit `credits.allocation` when the caller gives one.
* - Whatever is left of each credit is printed as carried forward.
* - Only credits in the invoice's own currency are applied. A foreign credit is
* listed as not applied, in its own currency, never converted.
* - Exclusions are judged in a fixed order: expired first (an expired credit is
* gone whatever else is true of it), then disputed, then a different currency.
* Each excluded credit is named with its one reason.
* - All arithmetic is on integer minor units, so total minus the sum applied is
* the amount due exactly, and it can never be negative.
*
* All of it is one deriver, because sorting, `min` and subtraction on request
* data all throw at publish. The node computes nothing: it interpolates, loops
* over the rows the deriver returns and branches on what it says.
*
* The loops run over derived rows, which needs a resolver that resolves a
* repeat's source by scope; the framework commit that adds it must be present.
*
* Installed by `dxcl add credits-applied-to-invoice`, which also installs its deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface CreditsAppliedToInvoiceData {
invoice: {
/**
* ISO 4217 code of the invoice: "GBP", "EUR", "JPY". Sets the exponent
* (two for GBP, none for JPY) from Intl. Only credits in this currency are
* applied. Required: the deriver throws, naming `invoice.currency`, when it
* is missing or a code Intl rejects.
*/
currency: string;
/**
* The invoice's date of issue, ISO 8601 (`2026-11-30`). Anything after the
* tenth character is ignored. Expiry is judged against this day, never
* against "today", so the same data always gives the same document.
* Required: throws when missing or not YYYY-MM-DD.
*/
issueDate: string;
/**
* The invoice total including VAT, in integer minor units (128475000 for
* £1,284,750.00), exactly as the VAT analysis above printed it. This
* component never recalculates or reduces it. Required: throws when it is
* not a safe integer ≥ 0. A negative total is a credit note, not an invoice.
*/
totalMinor: number;
/**
* The VAT included in `totalMinor`, in minor units. When given, a sentence
* says it is unchanged by the credits. Missing: no VAT sentence. Throws when
* present but not a safe integer between 0 and `totalMinor`.
*/
vatTotalMinor?: number;
};
credits: {
/**
* Every open credit on the customer's account, in any order. Missing,
* empty, or every entry at `remainingMinor` 0 means there is nothing to
* reconcile, and the component prints nothing at all.
*/
open?: Array<{
/**
* The credit's reference, printed as given ("CN-2026-000418"), and what
* an allocation names. Required, non-blank and unique: a missing or
* duplicate id throws.
*/
id: string;
/**
* `credit-note`: an issued credit note, which already adjusted VAT.
* `payment-on-account`: money received and not yet applied. The two are
* printed in separate groups. Anything else throws.
*/
kind: "credit-note" | "payment-on-account";
/**
* When it was issued or received, ISO 8601. Sets the oldest-first order
* and is printed. Required: throws when missing or not a date.
*/
issuedOn: string;
/**
* ISO 4217 code of the credit. Compared with `invoice.currency` trimmed
* and upper-cased. A different code is listed "Not applied – different
* currency" and its amount is shown in its own currency, never converted.
* Required: throws when missing or a code Intl rejects.
*/
currency: string;
/**
* What is left of the credit, in integer minor units of its own currency.
* 0 means used up: it is omitted entirely, not listed. Throws when it is
* not a safe integer ≥ 0.
*/
remainingMinor: number;
/**
* The last day the credit can be used, ISO 8601. A credit expiring on the
* issue date is still applied; one expiring before it is excluded and
* listed as expired. Missing: it never expires. Throws when present but
* not a date.
*/
expiresOn?: string;
/**
* True when the credit is blocked by a dispute. It is excluded and listed
* "On hold – disputed". Missing or anything but `true` means not disputed.
*/
disputed?: boolean;
}>;
/**
* An explicit allocation from your ledger, applied in this order in place
* of oldest first. Each amount is capped at the credit's remainder and at
* what is still owed. Eligible credits not named are not applied and carry
* forward in full. Missing or empty: oldest first. An entry naming an
* unknown id, naming an id twice, or with an amount that is not a safe
* integer ≥ 0 throws. One naming an excluded credit (expired, disputed,
* other currency) applies nothing; the credit stays listed with its reason.
*/
allocation?: Array<{ creditId: string; amountMinor: number }>;
};
}
/**
* Prints the credits applied to an invoice and the reconciliation from total to
* amount due. Prints nothing when the customer has no open credit.
*/
export const CreditsAppliedToInvoice: Nodes = async () => {
const [invoice] = useState((data: CreditsAppliedToInvoiceData) => data.invoice);
const [credits] = useState((data: CreditsAppliedToInvoiceData) => data.credits);
const p = await useDeriver(creditsAppliedToInvoice, [invoice, credits]);
return (
<>
{p.show && (
<Section id="credits-applied" title="Credits applied">
<Paragraph id="credits-applied-intro">{p.intro}</Paragraph>
{p.hasCreditNotes && (
<Table
id="credits-applied-credit-notes"
columns={[{ width: "auto" }, { width: 34 }, { width: 30, align: "right" }, { width: 34, align: "right" }]}
>
<Row id="credits-applied-credit-notes-header" header>
<Cell>Credit note</Cell>
<Cell>Issued</Cell>
<Cell>Applied</Cell>
<Cell>Carried forward</Cell>
</Row>
{p.creditNotes.map((row) => (
<Row id="credits-applied-credit-note">
<Cell>{row.reference}</Cell>
<Cell>{row.issued}</Cell>
<Cell>{row.applied}</Cell>
<Cell>{row.carriedForward}</Cell>
</Row>
))}
</Table>
)}
{p.hasPayments && (
<Table
id="credits-applied-payments"
columns={[{ width: "auto" }, { width: 34 }, { width: 30, align: "right" }, { width: 34, align: "right" }]}
>
<Row id="credits-applied-payments-header" header>
<Cell>Payment on account</Cell>
<Cell>Received</Cell>
<Cell>Applied</Cell>
<Cell>Carried forward</Cell>
</Row>
{p.payments.map((row) => (
<Row id="credits-applied-payment">
<Cell>{row.reference}</Cell>
<Cell>{row.issued}</Cell>
<Cell>{row.applied}</Cell>
<Cell>{row.carriedForward}</Cell>
</Row>
))}
</Table>
)}
{p.hasExcluded && (
<Table
id="credits-applied-excluded"
columns={[{ width: "auto" }, { width: 34 }, { width: 30, align: "right" }, { width: 34 }]}
>
<Row id="credits-applied-excluded-header" header>
<Cell>Not applied</Cell>
<Cell>Type</Cell>
<Cell>Amount</Cell>
<Cell>Reason</Cell>
</Row>
{p.excluded.map((row) => (
<Row id="credits-applied-excluded-credit">
<Cell>{row.reference}</Cell>
<Cell>{row.type}</Cell>
<Cell>{row.amount}</Cell>
<Cell>{row.reason}</Cell>
</Row>
))}
</Table>
)}
<Table id="credits-applied-reconciliation" columns={[{ width: "auto" }, { width: 40, align: "right" }]}>
<Row id="credits-applied-total">
<Cell>Invoice total</Cell>
<Cell>{p.total}</Cell>
</Row>
{p.lessCreditNotes && (
<Row id="credits-applied-less-credit-notes">
<Cell>Less credit notes applied</Cell>
<Cell>{p.lessCreditNotes}</Cell>
</Row>
)}
{p.lessPayments && (
<Row id="credits-applied-less-payments">
<Cell>Less payments on account applied</Cell>
<Cell>{p.lessPayments}</Cell>
</Row>
)}
<Row id="credits-applied-due">
<Cell>Amount due</Cell>
<Cell>{p.due}</Cell>
</Row>
</Table>
{p.vat && (
<Paragraph id="credits-applied-vat">
The VAT on this invoice, {p.vat}, is unchanged: credit notes adjusted VAT when they were issued, and a
payment on account is a means of payment.
</Paragraph>
)}
{p.outcome === "covered" && (
<Paragraph id="credits-applied-covered">Nothing to pay – covered by credits.</Paragraph>
)}
{p.outcome === "part" && (
<Paragraph id="credits-applied-part">The amount due after credits is {p.due}.</Paragraph>
)}
{p.carriedForward && (
<Paragraph id="credits-applied-carried-forward">
Credit of {p.carriedForward} remains on your account and is carried forward to your next invoice.
</Paragraph>
)}
</Section>
)}
</>
);
}; derivers/credits-applied-to-invoice.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Sets a customer's open credits against an invoice and works out the amount
* due. Installed by `dxcl add credits-applied-to-invoice`.
*
* 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: "creditsAppliedToInvoice",
run: (invoice: unknown, credits: unknown) => {
const inv = invoice as any;
const cr = credits as any;
const moneyFor = (code: unknown, field: string) => {
let format: Intl.NumberFormat;
try {
format = new Intl.NumberFormat("en-GB", { style: "currency", currency: code as string });
} catch {
throw new Error(field + " must be an ISO 4217 code");
}
const exponent = format.resolvedOptions().maximumFractionDigits as number;
return (minor: number) => format.format(minor / 10 ** exponent);
};
const minorOf = (value: unknown, field: string): number => {
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
throw new Error(field + " must be a non-negative integer of minor units");
}
return value;
};
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 dates = new Intl.DateTimeFormat("en-GB", { dateStyle: "long", timeZone: "UTC" });
const fmtDate = (iso: string) => dates.format(new Date(iso + "T00:00:00Z"));
const code = (value: unknown) => String(value).trim().toUpperCase();
// Invoice first: its currency and total decide how everything else is read.
if (typeof inv?.currency !== "string") throw new Error("invoice.currency must be an ISO 4217 code");
const currency = code(inv.currency);
const money = moneyFor(currency, "invoice.currency");
const issueDate = isoDay(inv?.issueDate, "invoice.issueDate");
const totalMinor = minorOf(inv?.totalMinor, "invoice.totalMinor");
let vat: string | null = null;
if (inv.vatTotalMinor !== undefined && inv.vatTotalMinor !== null) {
const vatMinor = minorOf(inv.vatTotalMinor, "invoice.vatTotalMinor");
if (vatMinor > totalMinor) throw new Error("invoice.vatTotalMinor must not exceed invoice.totalMinor");
vat = money(vatMinor);
}
// All validation runs before anything is decided, so bad data fails even
// when nothing would print.
const open: any[] = cr?.open ?? [];
if (!Array.isArray(open)) throw new Error("credits.open must be an array");
const seen = new Set<string>();
const all = open.map((c: any, index: number) => {
const at = "credits.open[" + index + "]";
if (typeof c?.id !== "string" || c.id.trim() === "") throw new Error(at + ".id is required");
if (seen.has(c.id)) throw new Error(at + ".id is a duplicate: " + c.id);
seen.add(c.id);
if (c.kind !== "credit-note" && c.kind !== "payment-on-account") {
throw new Error(at + '.kind must be "credit-note" or "payment-on-account"');
}
const issuedOn = isoDay(c.issuedOn, at + ".issuedOn");
if (typeof c.currency !== "string") throw new Error(at + ".currency must be an ISO 4217 code");
const creditCurrency = code(c.currency);
const fmt = moneyFor(creditCurrency, at + ".currency");
const remainingMinor = minorOf(c.remainingMinor, at + ".remainingMinor");
const hasExpiry = c.expiresOn !== undefined && c.expiresOn !== null;
const expiresOn = hasExpiry ? isoDay(c.expiresOn, at + ".expiresOn") : null;
let reason: string | null = null;
if (expiresOn !== null && expiresOn < issueDate) reason = "Expired on " + fmtDate(expiresOn);
else if (c.disputed === true) reason = "On hold – disputed";
else if (creditCurrency !== currency) reason = "Not applied – different currency";
return { id: c.id as string, kind: c.kind as string, index, issuedOn, remainingMinor, fmt, reason };
});
const allocation: any[] = cr?.allocation ?? [];
if (!Array.isArray(allocation)) throw new Error("credits.allocation must be an array");
const named = new Set<string>();
allocation.forEach((a: any, index: number) => {
const at = "credits.allocation[" + index + "]";
if (!seen.has(a?.creditId)) throw new Error(at + ".creditId names no credit in credits.open: " + a?.creditId);
if (named.has(a.creditId)) throw new Error(at + ".creditId is named twice: " + a.creditId);
named.add(a.creditId);
minorOf(a.amountMinor, at + ".amountMinor");
});
const live = all.filter((c) => c.remainingMinor > 0);
const byDate = (a: any, b: any) => (a.issuedOn < b.issuedOn ? -1 : a.issuedOn > b.issuedOn ? 1 : a.index - b.index);
const eligible = live.filter((c) => c.reason === null).sort(byDate);
// Credits reduce what is owed, never the total, so every step is min or subtraction.
const appliedById = new Map<string, number>();
let owed = totalMinor;
const take = (c: any, limit: number) => {
const applied = Math.min(c.remainingMinor, limit, owed);
owed -= applied;
appliedById.set(c.id, applied);
};
const allocated = allocation.length > 0;
if (allocated) {
for (const a of allocation) {
const c = eligible.find((e) => e.id === a.creditId);
if (c) take(c, a.amountMinor);
}
} else {
for (const c of eligible) take(c, Infinity);
}
const rowOf = (c: any) => {
const appliedMinor = appliedById.get(c.id) ?? 0;
const carriedForwardMinor = c.remainingMinor - appliedMinor;
return {
reference: c.id,
issued: fmtDate(c.issuedOn),
applied: money(appliedMinor),
carriedForward: money(carriedForwardMinor),
appliedMinor,
carriedForwardMinor,
};
};
const creditNotes = eligible.filter((c) => c.kind === "credit-note").map(rowOf);
const payments = eligible.filter((c) => c.kind === "payment-on-account").map(rowOf);
const excluded = live
.filter((c) => c.reason !== null)
.sort(byDate)
.map((c) => ({
reference: c.id,
type: c.kind === "credit-note" ? "Credit note" : "Payment on account",
amount: c.fmt(c.remainingMinor),
reason: c.reason as string,
}));
const creditNotesAppliedMinor = creditNotes.reduce((s, r) => s + r.appliedMinor, 0);
const paymentsAppliedMinor = payments.reduce((s, r) => s + r.appliedMinor, 0);
const appliedMinor = creditNotesAppliedMinor + paymentsAppliedMinor;
const dueMinor = totalMinor - appliedMinor;
const carriedForwardMinor = [...creditNotes, ...payments].reduce((s, r) => s + r.carriedForwardMinor, 0);
if (dueMinor + appliedMinor !== totalMinor || dueMinor < 0) throw new Error("credits do not tie out");
const outcome = appliedMinor === 0 ? "none" : dueMinor === 0 ? "covered" : "part";
const intro = appliedMinor > 0
? allocated
? "Credits on your account have been set against this invoice as allocated."
: "Open credits on your account have been set against this invoice, oldest first."
: totalMinor === 0
? "There is nothing on this invoice to set credits against."
: "None of the credits on your account could be set against this invoice.";
const less = (minor: number) => (minor > 0 ? "−" + money(minor) : null);
return {
show: live.length > 0,
outcome,
intro,
hasCreditNotes: creditNotes.length > 0,
creditNotes,
hasPayments: payments.length > 0,
payments,
hasExcluded: excluded.length > 0,
excluded,
total: money(totalMinor),
totalMinor,
lessCreditNotes: less(creditNotesAppliedMinor),
creditNotesAppliedMinor,
lessPayments: less(paymentsAppliedMinor),
paymentsAppliedMinor,
appliedMinor,
due: money(dueMinor),
dueMinor,
vat,
carriedForward: carriedForwardMinor > 0 ? money(carriedForwardMinor) : null,
carriedForwardMinor,
};
},
});