Invoice change explainer
GeneratedExplains why this invoice differs from the last one, in one generated sentence, and says nothing when the difference is too small to matter. Lines are matched by a stable key, never by description. Each difference becomes one structured cause: a line added or removed, a price or quantity change, a discount starting or ending, a tax rate or tax base change, a longer or shorter period, or a one-off charge. Price and volume effects use one convention that adds up exactly to the line's change: volume is the change in quantity at the old price, and price is the rest. When usage per day is flat, a longer period is the cause, not 'usage rose'. It names the fewest causes that cover 90% of the gross movement, at most three, so offsetting changes cannot hide behind a small net. A balance brought forward is never part of the change. It is silent below a floor (the larger of an absolute amount and a share of the previous total), on a first invoice, after a currency change, and when either invoice is a credit note. The model is limited to the chosen causes and their figures and may not guess at reasons. The placeholder is the same explanation written deterministically. All of it is one deriver.
npx dxcl add invoice-change-explainer Datos de vista previa
el JSON con el que se construyó esta vista previa{
"invoiceChange": {
"currency": "GBP",
"periodLabel": "last month",
"threshold": {
"absolute": 5,
"pct": 0.02
},
"previous": {
"total": 106320,
"periodDays": 30,
"documentType": "invoice",
"lines": [
{
"key": "platform",
"description": "Enterprise Data Platform licence (annual commitment, billed monthly)",
"kind": "recurring",
"quantity": 1,
"unitPrice": 18500,
"amount": 18500
},
{
"key": "api-calls",
"description": "Metered API requests over the included allowance",
"kind": "usage",
"quantity": 12400000,
"unitPrice": 0.00085,
"amount": 10540
},
{
"key": "seats",
"description": "Named analyst seats with Extended Data Retention",
"kind": "recurring",
"quantity": 1180,
"unitPrice": 46,
"amount": 54280
},
{
"key": "loyalty",
"description": "Multi-year loyalty discount (12% of platform licence)",
"kind": "discount",
"amount": -2220
},
{
"key": "migration",
"description": "Data migration and onboarding services (one-off)",
"kind": "one-off",
"amount": 7500
},
{
"key": "vat",
"description": "VAT",
"kind": "tax",
"taxRate": 0.2,
"amount": 17720
}
]
},
"current": {
"total": 234360,
"broughtForward": 106320,
"periodDays": 31,
"documentType": "invoice",
"lines": [
{
"key": "platform",
"description": "Enterprise Data Platform licence (annual commitment, billed monthly)",
"kind": "recurring",
"quantity": 1,
"unitPrice": 18500,
"amount": 18500
},
{
"key": "api-calls",
"description": "Metered API requests over the included allowance",
"kind": "usage",
"quantity": 15500000,
"unitPrice": 0.00085,
"amount": 13175
},
{
"key": "seats",
"description": "Named analyst seats with Extended Data Retention",
"kind": "recurring",
"quantity": 1450,
"unitPrice": 49.5,
"amount": 71775
},
{
"key": "support",
"description": "Dedicated Support (Premier tier, 24×7 with named engineer)",
"kind": "recurring",
"quantity": 1,
"unitPrice": 3250,
"amount": 3250
},
{
"key": "vat",
"description": "VAT",
"kind": "tax",
"taxRate": 0.2,
"amount": 21340
}
]
}
}
} Vista previa renderizada
el componente renderizado por su cuentaNodos resueltos
lo que recibe un renderizador — 1 nodosinvoice-change-explainer paragraph · dynamic Your total is £21,720.00 higher than last month, mostly because Named analyst seats with Extended Data Retention rose from 1,180 to 1,450 (+£12,420.00), Data migration and onboarding services (one-off) from last month is not repeated (-£7,500.00) and the price of Named analyst seats with Extended Data Retention went from £46.00 to £49.50 (+£5,075.00), with 5 smaller changes making up the rest. Los archivos
lo que escribe la instalación; el archivo seleccionado es el componentenodes/invoice-change-explainer.node.tsx import {
type Nodes,
Paragraph,
useDeriver,
useLocale,
useSetPlaceholders,
useSetPrompts,
useState,
} from "docxcelerate/template";
import invoiceChangeExplainer from "../derivers/invoice-change-explainer.deriver.ts";
/**
* One generated sentence under an invoice's totals: why this invoice differs
* from the previous one. Nothing at all, and no heading, when the difference is
* not worth a sentence.
*
* Decisions already made for the reader:
*
* - It names the fewest structured causes that cover 90% of the gross movement
* (the sum of |effect|), never more than three. A +100 and a -95 are not
* reported as "+5, one cause", and it does not list every changed line.
* - Price and quantity are split so they add up exactly to the line's change:
* volume is the change in quantity at the old price, and price is the rest. A
* tax change splits the same way into rate and base.
* - A longer billing period on its own raises a usage bill, so that share is
* attributed to period length, not to "usage rose".
* - A balance brought forward is never part of what changed.
* - Silent on a first invoice, after a currency change, when either invoice is
* a credit note, and when the difference is under the larger of an absolute
* floor and a share of the previous total.
* - The model may restate the chosen causes and their figures and nothing else;
* it may not give reasons. The placeholder is the same explanation written
* deterministically, so a document with no model still reads correctly.
*
* The node computes nothing: comparisons and arithmetic on request data would
* throw at publish, so all of it is one deriver. `useDeriver` is the last hook
* because the hook context does not survive its `await`; the prompts and the
* placeholder therefore carry hand-written `{{derived.invoiceChangeExplainer.*}}`
* tokens rather than interpolating the stand-in. The test stays inline, never
* hoisted into a `const`, so it publishes as a branch.
*
* Not done: translating the wording (the locale only formats numbers), guessing
* why anything changed, comparing against more than one invoice, converting
* currency, or prorating recurring lines.
*
* Installed by `dxcl add invoice-change-explainer`, which also installs its deriver.
*/
/** One invoice line, as this component compares it. */
export interface InvoiceChangeLine {
/**
* What matches this line to the same line on the other invoice: a SKU, a
* price id, a plan code. Stable across invoices and never the description,
* which gets reworded. Required, and unique within one invoice: the deriver
* throws on a missing, empty or duplicate key.
*/
key: string;
/** What the line is called, printed in the sentence as given. Required. */
description: string;
/**
* What sort of line it is, which decides how a difference is described.
* `usage` lines may be split by period length. `discount` lines start and
* end rather than appear and vanish. `one-off` lines are charges that are
* not expected to repeat. `tax` lines split into rate and base. Required:
* any other value throws.
*/
kind: "recurring" | "usage" | "one-off" | "discount" | "tax";
/**
* How many were charged. Needed on both invoices, together with
* `unitPrice`, for a price/quantity split. Without it the line's change is
* one `changed` cause, "X rose from £a to £b". Throws when present but not
* a finite number.
*/
quantity?: number;
/**
* The price of one unit, in major units. It may have more decimals than the
* currency has (`0.00015`). The same rules as `quantity`: needed on both
* sides for a split, and throws when present but not finite.
*/
unitPrice?: number;
/**
* What the line contributes to the total, in major units, signed. A
* discount is negative. This is the authority: the split is made against
* it, not against quantity × unitPrice. Required and finite, or the deriver
* throws.
*/
amount: number;
/**
* For a `tax` line, the rate as a fraction (`0.2` is 20%). Needed and above
* 0 on both invoices to split a tax change into rate and base. Otherwise the
* tax line's change is one `changed` cause. Ignored on other kinds.
*/
taxRate?: number;
}
/** One invoice, as this component compares it. The current and previous invoices share the shape. */
export interface InvoiceChangeSnapshot {
/**
* The invoice total as billed, in major units, including tax. Required and
* finite. `total - (broughtForward ?? 0)` must equal the sum of the line
* `amount`s once both are converted to minor units, or the deriver throws:
* an invoice whose lines do not add up cannot be explained.
*/
total: number;
/**
* Any balance carried in from earlier invoices that `total` includes.
* Subtracted before comparing, and never a cause. Missing means 0.
*/
broughtForward?: number;
/**
* How many days the billing period covered. Only used for the
* period-length split, which needs it on both invoices. Missing on either
* side means no split: the whole volume change of a usage line is a
* `quantity` cause. Throws when present but not a positive integer.
*/
periodDays?: number;
/**
* Missing means `"invoice"`. A credit note on either side makes the
* component silent: "lower than your credit note" means nothing.
*/
documentType?: "invoice" | "credit-note";
/**
* For `previous` only: its ISO 4217 currency. Missing means the same as
* `invoiceChange.currency`. A different code makes the component silent.
* It never converts. Ignored on `current`.
*/
currency?: string;
/** Every line on the invoice, in printed order. Required: throws when not an array. Empty is allowed. */
lines: InvoiceChangeLine[];
}
/** What this component reads. Add these fields to your document data type. */
export interface InvoiceChangeData {
invoiceChange: {
/**
* The current invoice's ISO 4217 currency. It sets the minor units that
* every figure is rounded to and the symbol printed. Required: the
* deriver throws when it is missing or `Intl` rejects it.
*/
currency: string;
/** The invoice this document is. Required. */
current: InvoiceChangeSnapshot;
/**
* The invoice before it. Missing or `null` means this is the first
* invoice: the component is silent.
*/
previous?: InvoiceChangeSnapshot | null;
/**
* When a difference is too small to mention. The component is silent when
* |difference| < max(`absolute`, `pct` × |previous total net of brought
* forward|). `absolute` is in major units, default `1`. `pct` is a fraction
* from 0 up to but not including 1, default `0.02`. Missing, or either
* field missing, uses the default. Throws on a negative `absolute` or a
* `pct` outside [0, 1).
*/
threshold?: { absolute?: number; pct?: number };
/**
* What the previous invoice is called in the sentence, after "than":
* `"last month"`, `"your March invoice"`. Missing or empty means
* `"your last invoice"`.
*/
periodLabel?: string;
};
}
/**
* One dynamic paragraph telling the customer why the total moved since the
* previous invoice, written from the facts the deriver settles. Renders
* nothing when the deriver says the change is not worth explaining.
*/
export const InvoiceChangeExplainer: Nodes = async () => {
const [change] = useState((data: InvoiceChangeData) => data.invoiceChange);
// A deriver cannot see the build locale, so it is handed over as an input.
const locale = useLocale();
useSetPrompts({
systemPrompt:
"You write one or two plain sentences on an invoice, to the customer. You explain figures you are given. You never speculate about why anything changed.",
generalPrompt:
"Tell the reader their total is {{derived.invoiceChangeExplainer.difference}} {{derived.invoiceChangeExplainer.direction}} than {{derived.invoiceChangeExplainer.periodLabel}}, and why, using only the changes listed. At most two sentences.",
infoPrompt: "{{derived.invoiceChangeExplainer.facts}}",
negativePrompt:
"Do not give a reason for any change beyond what is listed: nothing about activity, growth, seasons, usage habits or the customer's business. Do not mention any change, balance brought forward, payment or figure that is not listed. Do not round, convert or recompute the figures. Do not apologise or sell.",
examplePrompt: "Your total is £12.40 higher than last month, mostly because API calls rose from 120,000 to 180,000 (+£9.00).",
});
useSetPlaceholders("{{derived.invoiceChangeExplainer.sentence}}");
const explained = await useDeriver(invoiceChangeExplainer, [change, locale]);
return <>{explained.speak && <Paragraph id="invoice-change-explainer" />}</>;
}; derivers/invoice-change-explainer.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Explains why one invoice differs from the one before it. Installed by
* `dxcl add invoice-change-explainer`.
*
* Self-contained on purpose: it travels to the engine as source text, so a
* module-level helper or constant would be a ReferenceError there. Every figure
* is an integer in the currency's minor units from the moment it is computed,
* and remainders are taken by subtraction, never rounded on their own, which is
* what makes the causes add up to the difference exactly.
*/
export default deriver({
name: "invoiceChangeExplainer",
run: (change: unknown, locale: unknown) => {
const c = change as any;
const loc = typeof locale === "string" && locale !== "" ? locale : "en-GB";
const KINDS = ["recurring", "usage", "one-off", "discount", "tax"];
const silent = (silentReason: string, periodLabel: string) => ({
speak: false,
silentReason,
direction: null,
difference: "",
periodLabel,
causes: [] as never[],
omitted: 0,
sentence: "",
facts: "",
});
if (typeof c?.currency !== "string" || c.currency === "") {
throw new Error("invoiceChange.currency is required");
}
const currency: string = c.currency;
let digits: number;
try {
digits = new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2;
} catch {
throw new Error("invoiceChange.currency is not a valid ISO 4217 code: " + currency);
}
const scale = 10 ** digits;
const toMinor = (x: number) => Math.round(x * scale);
const label = typeof c.periodLabel === "string" && c.periodLabel.trim() !== ""
? c.periodLabel.trim()
: "your last invoice";
const th = c.threshold ?? {};
const absolute = th.absolute ?? 1;
const pct = th.pct ?? 0.02;
if (typeof absolute !== "number" || !Number.isFinite(absolute) || absolute < 0) {
throw new Error("invoiceChange.threshold.absolute must be a number of 0 or more");
}
if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct >= 1) {
throw new Error("invoiceChange.threshold.pct must be at least 0 and below 1");
}
const optNumber = (v: unknown, field: string) => {
if (v !== undefined && v !== null && (typeof v !== "number" || !Number.isFinite(v))) {
throw new Error(field + " must be a finite number");
}
};
// Checks one invoice and returns its total net of the balance brought forward.
const check = (snap: any, name: string): number => {
if (snap === null || typeof snap !== "object") throw new Error(name + " is required");
if (typeof snap.total !== "number" || !Number.isFinite(snap.total)) {
throw new Error(name + ".total must be a finite number");
}
optNumber(snap.broughtForward, name + ".broughtForward");
const pd = snap.periodDays;
if (pd !== undefined && pd !== null && (!Number.isInteger(pd) || pd <= 0)) {
throw new Error(name + ".periodDays must be a positive integer");
}
if (!Array.isArray(snap.lines)) throw new Error(name + ".lines must be an array");
const seen = new Set<string>();
let sum = 0;
for (const [i, l] of snap.lines.entries()) {
const at = name + ".lines[" + i + "]";
if (typeof l?.key !== "string" || l.key === "") throw new Error(at + ".key is required");
if (seen.has(l.key)) throw new Error(at + ".key is duplicated: " + l.key);
seen.add(l.key);
if (typeof l.description !== "string" || l.description === "") {
throw new Error(at + ".description is required");
}
if (!KINDS.includes(l.kind)) throw new Error(at + ".kind must be one of " + KINDS.join(", "));
if (typeof l.amount !== "number" || !Number.isFinite(l.amount)) {
throw new Error(at + ".amount must be a finite number");
}
optNumber(l.quantity, at + ".quantity");
optNumber(l.unitPrice, at + ".unitPrice");
optNumber(l.taxRate, at + ".taxRate");
sum += toMinor(l.amount);
}
const net = toMinor(snap.total) - toMinor(snap.broughtForward ?? 0);
if (net !== sum) throw new Error(name + ": lines do not add up to total less broughtForward");
return net;
};
const cur = c.current;
const curNet = check(cur, "invoiceChange.current");
const prev = c.previous;
if (prev === undefined || prev === null) return silent("first-invoice", label);
if (cur.documentType === "credit-note" || prev.documentType === "credit-note") {
return silent("credit-note", label);
}
if (typeof prev.currency === "string" && prev.currency !== "" && prev.currency !== currency) {
return silent("currency-change", label);
}
const prevNet = check(prev, "invoiceChange.previous");
const delta = curNet - prevNet;
const floor = Math.max(Math.round(absolute * scale), Math.round(pct * Math.abs(prevNet)));
if (delta === 0 || Math.abs(delta) < floor) return silent("below-threshold", label);
// Causes, in the fixed order that breaks ties.
type Cause = { kind: string; key: string; description: string | null; effect: number; clause: string };
type Raw = { kind: string; key: string; description: string | null; effect: number; clause: (e: string) => string };
const raws: Raw[] = [];
const add = (kind: string, key: string, description: string | null, effect: number, clause: (e: string) => string) => {
if (effect !== 0) raws.push({ kind, key, description, effect, clause });
};
const money = new Intl.NumberFormat(loc, { style: "currency", currency });
const signed = new Intl.NumberFormat(loc, { style: "currency", currency, signDisplay: "always" });
const unit = new Intl.NumberFormat(loc, {
style: "currency",
currency,
minimumFractionDigits: digits,
maximumFractionDigits: Math.max(digits, 6),
});
const qty = new Intl.NumberFormat(loc, { maximumFractionDigits: 6 });
const rate = new Intl.NumberFormat(loc, { style: "percent", maximumFractionDigits: 2 });
const m = (minor: number) => money.format(minor / scale);
const s = (minor: number) => signed.format(minor / scale);
const move = (up: boolean) => (up ? "rose" : "fell");
const before = new Map<string, any>();
for (const l of prev.lines) before.set(l.key, l);
const after = new Set<string>();
const d0: number | undefined = prev.periodDays ?? undefined;
const d1: number | undefined = cur.periodDays ?? undefined;
let periodEffect = 0;
for (const l of cur.lines) {
after.add(l.key);
const o = before.get(l.key);
const d: string = l.description;
const a1 = toMinor(l.amount);
if (!o) {
const kind = l.kind === "one-off" ? "one-off" : l.kind === "discount" ? "discount-started" : "new";
add(kind, l.key, d, a1, (e) =>
kind === "one-off"
? d + " is a one-off charge on this invoice (" + e + ")"
: kind === "discount-started"
? d + " was applied (" + e + ")"
: d + " was added (" + e + ")");
continue;
}
const a0 = toMinor(o.amount);
const delta2 = a1 - a0;
const changed = () =>
add("changed", l.key, d, delta2, (e) => d + " " + move(delta2 > 0) + " from " + m(a0) + " to " + m(a1) + " (" + e + ")");
if (o.kind !== l.kind) {
changed();
} else if (l.kind === "tax") {
const r0 = o.taxRate, r1 = l.taxRate;
if (!(r0 > 0 && r1 > 0)) {
changed();
} else if (r0 === r1) {
add("tax-base", l.key, d, delta2, (e) => d + " " + move(delta2 > 0) + " with the charges it is worked out on (" + e + ")");
} else {
const base = Math.round((l.amount / r1 - o.amount / r0) * r0 * scale);
const byRate = delta2 - base;
add("tax-base", l.key, d, base, (e) => d + " " + move(base > 0) + " with the charges it is worked out on (" + e + ")");
add("tax-rate", l.key, d, byRate, (e) => d + " changed from " + rate.format(r0) + " to " + rate.format(r1) + " (" + e + ")");
}
} else if (
typeof l.quantity === "number" && typeof l.unitPrice === "number" &&
typeof o.quantity === "number" && typeof o.unitPrice === "number"
) {
const q0: number = o.quantity, q1: number = l.quantity, p0: number = o.unitPrice, p1: number = l.unitPrice;
const volume = p0 === p1 ? delta2 : q0 === q1 ? 0 : Math.round((q1 - q0) * p0 * scale);
const price = delta2 - volume;
add("price", l.key, d, price, (e) => "the price of " + d + " went from " + unit.format(p0) + " to " + unit.format(p1) + " (" + e + ")");
let period = 0;
if (l.kind === "usage" && d0 !== undefined && d1 !== undefined && d0 !== d1 && q0 > 0 && volume !== 0) {
const perDay0 = q0 / d0, perDay1 = q1 / d1;
period = Math.abs(perDay1 - perDay0) <= 0.01 * perDay0
? volume
: Math.round((d1 - d0) * perDay0 * p0 * scale);
}
periodEffect += period;
const qEffect = volume - period;
// After a period split the effect can run against the quantity; "rose ... (-£4.50)" would contradict itself.
const verb = (qEffect > 0) === (q1 > q0) ? move(q1 > q0) : "changed";
add("quantity", l.key, d, qEffect, (e) => d + " " + verb + " from " + qty.format(q0) + " to " + qty.format(q1) + " (" + e + ")");
} else {
changed();
}
}
for (const o of prev.lines) {
if (after.has(o.key)) continue;
const d: string = o.description;
const kind = o.kind === "one-off" ? "one-off-ended" : o.kind === "discount" ? "discount-ended" : "removed";
add(kind, o.key, d, -toMinor(o.amount), (e) =>
kind === "one-off-ended"
? d + " from " + label + " is not repeated (" + e + ")"
: kind === "discount-ended"
? d + " has ended (" + e + ")"
: d + " is no longer charged (" + e + ")");
}
add("period-length", "period-length", null, periodEffect, (e) =>
"this period had " + d1 + " days against " + d0 + " (" + e + ")");
const sorted = raws.slice().sort((x, y) => Math.abs(y.effect) - Math.abs(x.effect));
const gross = sorted.reduce((t, r) => t + Math.abs(r.effect), 0);
const chosen: Cause[] = [];
let cumulative = 0;
for (const r of sorted) {
chosen.push({ kind: r.kind, key: r.key, description: r.description, effect: r.effect, clause: r.clause(s(r.effect)) });
cumulative += Math.abs(r.effect);
if (10 * cumulative >= 9 * gross || chosen.length === 3) break;
}
const omitted = sorted.length - chosen.length;
const difference = m(Math.abs(delta));
const direction = delta > 0 ? "higher" : "lower";
const clauses = chosen.map((x) => x.clause);
const list = new Intl.ListFormat(loc, { type: "conjunction" }).format(clauses);
const rest = omitted > 0 ? ", with " + omitted + " smaller change" + (omitted === 1 ? "" : "s") + " making up the rest" : "";
const sentence = "Your total is " + difference + " " + direction + " than " + label + ", " +
(omitted === 0 ? "because " : "mostly because ") + list + rest + ".";
const facts = "The total is " + difference + " " + direction + " than " + label +
". What changed, largest effect first: " + clauses.join("; ") + "." +
(omitted > 0
? " " + omitted + " smaller change" + (omitted === 1 ? " accounts" : "s account") + " for the rest; do not describe them."
: "");
return { speak: true, silentReason: null, direction, difference, periodLabel: label, causes: chosen, omitted, sentence, facts };
},
});