Dunning reminder
BodyChases only invoices past their grace period that are not disputed, on hold or paid down to zero, and prints nothing at all when none qualify. Each invoice moves up one level per reminder and only after the minimum interval, so a daily run never jumps from first reminder to final notice or re-sends the same one. The level sets the title and tone. The deadline is never shorter than the Dutch, Belgian or UK pre-action minimum you name and never falls on a weekend. A final reminder states only the consequences you mark as intended, and none if you mark none, because an empty threat is unlawful in the UK and the US. Every level says which date payments were checked up to. The opening can be generated per document. One deriver decides it all.
npx dxcl add dunning-reminder reminder.legalFloor Данные предпросмотра
JSON, на котором построен этот предпросмотр{
"reminder": {
"sendDate": "2026-11-20",
"paymentsCheckedTo": "2026-11-19",
"currency": "GBP",
"graceDays": 7,
"minIntervalDays": 14,
"legalFloor": "NL-consumer",
"channel": "post",
"intendedConsequences": [
"agency",
"court"
],
"customerSince": "2019-03-01",
"invoices": [
{
"number": "SI-2026-07-004817/REV-2",
"dueDate": "2026-07-31",
"openAmount": 184250.75,
"lastLevel": 2,
"lastReminderDate": "2026-11-02"
},
{
"number": "SI-2026-08-005102-FACILITIES-NORTH",
"dueDate": "2026-08-31",
"openAmount": 96480,
"lastLevel": 2,
"lastReminderDate": "2026-11-02"
},
{
"number": "SI-2026-09-005390",
"dueDate": "2026-09-30",
"openAmount": 12999.99,
"lastLevel": 1,
"lastReminderDate": "2026-10-30"
},
{
"number": "SI-2026-09-005391",
"dueDate": "2026-09-30",
"openAmount": 7450,
"lastLevel": 1,
"lastReminderDate": "2026-11-12"
},
{
"number": "SI-2026-10-005688",
"dueDate": "2026-10-31",
"openAmount": 48120.4,
"disputed": true
},
{
"number": "SI-2026-10-005702",
"dueDate": "2026-10-31",
"openAmount": 23875
},
{
"number": "SI-2026-10-005703",
"dueDate": "2026-10-31",
"openAmount": 1250,
"onHold": true
},
{
"number": "SI-2026-10-005750",
"dueDate": "2026-10-20",
"openAmount": 0
},
{
"number": "SI-2026-11-005940",
"dueDate": "2026-11-10",
"openAmount": 3600
},
{
"number": "SI-2026-11-006011",
"dueDate": "2026-11-15",
"openAmount": 9999
}
]
}
} {
"reminder": {
"sendDate": "2026-11-20",
"paymentsCheckedTo": "2026-11-19",
"currency": "GBP",
"graceDays": 7,
"minIntervalDays": 14,
"legalFloor": "BE-consumer",
"channel": "post",
"intendedConsequences": [
"agency",
"court"
],
"customerSince": "2019-03-01",
"invoices": [
{
"number": "SI-2026-07-004817/REV-2",
"dueDate": "2026-07-31",
"openAmount": 184250.75,
"lastLevel": 2,
"lastReminderDate": "2026-11-02"
},
{
"number": "SI-2026-08-005102-FACILITIES-NORTH",
"dueDate": "2026-08-31",
"openAmount": 96480,
"lastLevel": 2,
"lastReminderDate": "2026-11-02"
},
{
"number": "SI-2026-09-005390",
"dueDate": "2026-09-30",
"openAmount": 12999.99,
"lastLevel": 1,
"lastReminderDate": "2026-10-30"
},
{
"number": "SI-2026-09-005391",
"dueDate": "2026-09-30",
"openAmount": 7450,
"lastLevel": 1,
"lastReminderDate": "2026-11-12"
},
{
"number": "SI-2026-10-005688",
"dueDate": "2026-10-31",
"openAmount": 48120.4,
"disputed": true
},
{
"number": "SI-2026-10-005702",
"dueDate": "2026-10-31",
"openAmount": 23875
},
{
"number": "SI-2026-10-005703",
"dueDate": "2026-10-31",
"openAmount": 1250,
"onHold": true
},
{
"number": "SI-2026-10-005750",
"dueDate": "2026-10-20",
"openAmount": 0
},
{
"number": "SI-2026-11-005940",
"dueDate": "2026-11-10",
"openAmount": 3600
},
{
"number": "SI-2026-11-006011",
"dueDate": "2026-11-15",
"openAmount": 9999
}
]
}
} {
"reminder": {
"sendDate": "2026-11-20",
"paymentsCheckedTo": "2026-11-19",
"currency": "GBP",
"graceDays": 7,
"minIntervalDays": 14,
"legalFloor": "UK-pre-action",
"channel": "post",
"intendedConsequences": [
"agency",
"court"
],
"customerSince": "2019-03-01",
"invoices": [
{
"number": "SI-2026-07-004817/REV-2",
"dueDate": "2026-07-31",
"openAmount": 184250.75,
"lastLevel": 2,
"lastReminderDate": "2026-11-02"
},
{
"number": "SI-2026-08-005102-FACILITIES-NORTH",
"dueDate": "2026-08-31",
"openAmount": 96480,
"lastLevel": 2,
"lastReminderDate": "2026-11-02"
},
{
"number": "SI-2026-09-005390",
"dueDate": "2026-09-30",
"openAmount": 12999.99,
"lastLevel": 1,
"lastReminderDate": "2026-10-30"
},
{
"number": "SI-2026-09-005391",
"dueDate": "2026-09-30",
"openAmount": 7450,
"lastLevel": 1,
"lastReminderDate": "2026-11-12"
},
{
"number": "SI-2026-10-005688",
"dueDate": "2026-10-31",
"openAmount": 48120.4,
"disputed": true
},
{
"number": "SI-2026-10-005702",
"dueDate": "2026-10-31",
"openAmount": 23875
},
{
"number": "SI-2026-10-005703",
"dueDate": "2026-10-31",
"openAmount": 1250,
"onHold": true
},
{
"number": "SI-2026-10-005750",
"dueDate": "2026-10-20",
"openAmount": 0
},
{
"number": "SI-2026-11-005940",
"dueDate": "2026-11-10",
"openAmount": 3600
},
{
"number": "SI-2026-11-006011",
"dueDate": "2026-11-15",
"openAmount": 9999
}
]
}
} Отрисованный предпросмотр
каждая компоновка, отрисованная сама по себеarrangement="table" по умолчанию arrangement="stacked" Разрешённые узлы
что получает рендерер — узлов: 1dunning-reminder section dunning-reminder section dunning-reminder section Файлы
что записывает установка; выбранный файл и есть компонентnodes/dunning-reminder.node.tsx import {
arrange,
Paragraph,
type Paragraph as ParagraphComponent,
type Nodes,
Section,
useDeriver,
useSetPlaceholders,
useSetPrompts,
useState,
} from "docxcelerate/template";
import type { DunningReminderLines } from "../arrangements/dunning-reminder/lines.ts";
import { stacked } from "../arrangements/dunning-reminder/stacked.arrangement.tsx";
import { table } from "../arrangements/dunning-reminder/table.arrangement.tsx";
import dunningReminder from "../derivers/dunning-reminder.deriver.ts";
/**
* The body of a payment reminder. It works out which overdue invoices this
* letter covers, which reminder level it is, its title, its deadline and what
* it may say will happen next, then prints those lines and nothing else.
*
* Written by hand, reminders escalate on days overdue alone, so an invoice
* jumps from first reminder to final notice, or a daily run sends the same
* final notice every day. They chase disputed invoices, invoices on a payment
* plan and balances already paid to zero. They set deadlines shorter than the
* law allows, and threaten court action the business never takes, which is
* itself unlawful (UK CPUTR misleading actions; US FDCPA section 807(5)).
*
* Decisions already made for you:
*
* - An invoice is chased only if it is past due by the grace period, is not
* disputed, on hold or on a payment plan, still has an open amount, and
* enough time has passed since its last reminder.
* - An invoice moves up one level per reminder, never more.
* - The deadline is never shorter than the named legal minimum and never falls
* on a weekend.
* - The final level threatens only the consequences the caller has marked as
* actually intended. With none marked, it threatens nothing.
* - Every level says which date payments were checked up to, because payments
* cross in the post.
* - If nothing qualifies, it prints nothing. It never prints a reminder for
* zero invoices.
*
* All of it is decided in one deriver, because every step does date
* arithmetic, filtering, sorting or summing on request data, and publishing
* refuses all of those.
*
* There are eight fixed invoice slots rather than a `.map()`. The resolver
* reads a published loop's collection from request data and ignores the
* derived scope, so a `.map()` over derived invoices would publish and then
* resolve to nothing; conditions and `{{derived.…}}` tokens do honour it.
*
* The node publishes 12 branches with the fixed opening and 15 with the
* generated one, against the default `branchLimit` of 32.
*
* The caller must record `lastLevel` and `lastReminderDate` for each invoice
* after sending. A document cannot write back. The deriver's `sent` field lists
* them for a caller that runs `run` itself.
*
* Installed by `dxcl add dunning-reminder`, which also installs its deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface DunningReminderData {
reminder: {
/**
* The date this reminder is sent, ISO 8601 (`2026-11-20`). Days overdue,
* the interval since the last reminder and the deadline are all counted
* from it, in whole UTC days. Anything after the tenth character is
* ignored. Required: the deriver throws when it is missing or not YYYY-MM-DD.
*/
sendDate: string;
/**
* The last day whose payments are reflected in `openAmount`, ISO 8601.
* Printed in the "if you have paid since" line at every level. Required:
* throws when missing, not a date, or after `sendDate`.
*/
paymentsCheckedTo: string;
/**
* ISO 4217 code every `openAmount` is in. It also sets the minor units
* amounts are rounded to (2 for GBP, 0 for JPY). Required: throws when
* missing or not a code `Intl.NumberFormat` accepts.
*/
currency: string;
/**
* Days past the due date before an invoice is chased at all. Missing
* means 7. An invoice is never chased on or before its due date, even at
* 0. Throws when present and not a non-negative integer.
*/
graceDays?: number;
/**
* Minimum days between two reminders for the same invoice. Missing
* means 14. An invoice reminded more recently than this is left out of
* this letter altogether, so a daily run neither escalates it nor sends
* the same level again. Throws when present and not a positive integer.
*/
minIntervalDays?: number;
/**
* Days from `sendDate` to the payment deadline at each level. Missing
* fields keep their defaults: first 14, second 10, final 7. A legal floor
* can push the deadline later than this, never earlier. Throws when a
* given field is not a positive integer.
*/
deadlineDays?: { first?: number; second?: number; final?: number };
/**
* A statutory minimum the deadline may not fall before. Missing means
* no floor.
* - `NL-consumer`: 14 days after the day of receipt (BW 6:96(6)).
* - `BE-consumer`: 14 days counted from the third working day after
* sending on paper, or from the day after sending electronically
* (WER art. XIX.2).
* - `UK-pre-action`: 30 days from the date of the letter (Pre-Action
* Protocol for Debt Claims).
* Throws on any other value.
*/
legalFloor?: "NL-consumer" | "BE-consumer" | "UK-pre-action";
/**
* How the reminder is delivered. Read only for the NL and BE floors.
* Missing means `"post"`, which gives the later of the two deadlines.
* Throws on any other value.
*/
channel?: "post" | "email";
/**
* The consequences the business actually intends if the final reminder
* goes unpaid. Printed only on a final-level letter. Missing or empty
* prints no consequence at all, because threatening an action that is
* not intended is a misleading practice. Duplicates are ignored. Throws
* on any other value.
*/
intendedConsequences?: Array<"agency" | "court" | "suspension">;
/**
* When the customer relationship began, ISO 8601. Used only to tell the
* generated opening how long the customer has been with you; never
* printed. Missing leaves that fact out of the prompt. Throws when
* present and not a date, or after `sendDate`.
*/
customerSince?: string;
/**
* Every open invoice on the account, in any order. The deriver decides
* which ones this reminder covers. Missing or empty means nothing is
* chased and the component prints nothing.
*/
invoices?: Array<{
/** The invoice number, printed as given. Required: throws when missing or blank. */
number: string;
/** The due date, ISO 8601. Required: throws when missing or not a date. */
dueDate: string;
/**
* What is still unpaid, in major units (`1234.56`), net of payments up
* to `paymentsCheckedTo` and of any credit already allocated to it.
* Rounded half-up to minor units. Zero or negative after rounding is
* not chased. Required: throws when not a finite number.
*/
openAmount: number;
/** True when the customer has disputed it. Missing means false. A disputed invoice is never chased. */
disputed?: boolean;
/**
* True when collection is paused: on hold, or covered by an active
* payment arrangement. Missing means false. A held invoice is never chased.
*/
onHold?: boolean;
/**
* The highest reminder level already sent for this invoice: 0 none, 1
* first, 2 second, 3 final. Missing means 0. An invoice at 3 has had its
* final reminder and is not chased again; what follows is the action,
* not another letter. Throws when not an integer from 0 to 3.
*/
lastLevel?: 0 | 1 | 2 | 3;
/**
* When the reminder at `lastLevel` was sent, ISO 8601. Required when
* `lastLevel` is 1 or more: throws when it is missing then, because
* without it the interval cannot be checked. Ignored at 0. Throws when
* not a date, or after `sendDate`.
*/
lastReminderDate?: string;
}>;
};
}
/**
* Where the invoice lines sit.
*
* - `table`: number, due date, days overdue and amount in columns, with a total row. The default.
* - `stacked`: one sentence per invoice down the text column, then the total.
*/
export type DunningReminderArrangement = "table" | "stacked";
/** Props for {@linkcode DunningReminder}. */
export interface DunningReminderProps {
/** Where the invoice lines sit. Defaults to `"table"`. */
arrangement?: DunningReminderArrangement;
/**
* Generate the opening paragraph per document instead of printing the
* fixed one. Missing means false. Previews show the level's placeholder.
*/
generateOpening?: boolean;
}
// Module level is fine here: only the deriver travels as source text.
const OPENINGS = {
first: {
general:
"Write the opening paragraph of a first payment reminder: one or two sentences, friendly, assuming the payment was simply overlooked.",
placeholder: "A friendly opening, written per document, that assumes the payment was overlooked.",
},
second: {
general:
"Write the opening paragraph of a second payment reminder: one or two sentences, firm and courteous, noting that an earlier reminder went unanswered.",
placeholder: "A firm opening, written per document, noting this is the second reminder.",
},
final: {
general:
"Write the opening paragraph of a final payment reminder: one or two sentences, serious and courteous, saying plainly that this is the final reminder.",
placeholder: "A serious opening, written per document, stating this is the final reminder.",
},
};
/** Its hooks belong to its own instance, so the node's `useDeriver` stays its last hook. */
const Opening: ParagraphComponent<{ level: "first" | "second" | "final"; facts: string }> = ({ level, facts }) => {
useSetPrompts({
systemPrompt:
"You write payment reminders on behalf of the sender, in plain English and the second person. Courteous at every level, never sarcastic.",
generalPrompt: OPENINGS[level].general,
// Interpolated, not passed bare: a published fact is a token, and the prompt is trimmed as text.
infoPrompt: `${facts}`,
negativePrompt:
"Do not mention amounts, dates, deadlines, invoice numbers or what will happen if the customer does not pay: the letter states those itself. Do not threaten any action. Do not apologise for writing. Do not invent contact details.",
});
useSetPlaceholders(OPENINGS[level].placeholder);
return <Paragraph id={`dunning-reminder-opening-${level}`} />;
};
/**
* Prints the overdue invoices a reminder covers, with its request, contact
* line, any intended consequence and the payments-checked line. Prints nothing
* when no invoice qualifies.
*/
export const DunningReminder: Nodes<DunningReminderProps> = async ({ arrangement, generateOpening }) => {
const [reminder] = useState((data: DunningReminderData) => data.reminder);
const r = await useDeriver(dunningReminder, [reminder]);
const lines: DunningReminderLines = { invoices: r.invoices, overflow: r.overflow, total: r.total };
return (
<>
{r.outcome === "remind" && (
<Section id="dunning-reminder" title={r.title}>
{!generateOpening && <Paragraph id="dunning-reminder-opening">{r.opening}</Paragraph>}
{generateOpening && r.level === 1 && <Opening level="first" facts={r.promptFacts} />}
{generateOpening && r.level === 2 && <Opening level="second" facts={r.promptFacts} />}
{generateOpening && r.level === 3 && <Opening level="final" facts={r.promptFacts} />}
{arrange(arrangement, { table: () => table(lines), stacked: () => stacked(lines) })}
<Paragraph id="dunning-reminder-request">{r.request}</Paragraph>
{r.contact && <Paragraph id="dunning-reminder-contact">{r.contact}</Paragraph>}
{r.consequence && <Paragraph id="dunning-reminder-consequence">{r.consequence}</Paragraph>}
<Paragraph id="dunning-reminder-paid-since">{r.paidSince}</Paragraph>
</Section>
)}
</>
);
}; derivers/dunning-reminder.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
interface Slot {
number: string;
dueDate: string;
overdue: string;
amount: string;
line: string;
}
interface Reminder {
outcome: "remind" | "none";
level: 0 | 1 | 2 | 3;
title: string;
opening: string;
invoices: Slot[];
overflow: string;
total: string;
request: string;
contact: string;
consequence: string;
paidSince: string;
promptFacts: string;
deadline: string;
sent: Array<{ number: string; level: 1 | 2 | 3 }>;
}
/**
* Decides which overdue invoices a payment reminder covers, its level, title,
* deadline and what it may say happens next. Installed by
* `dxcl add dunning-reminder`.
*
* 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 and number is declared inside `run`.
*/
export default deriver({
name: "dunningReminder",
run: (reminder: unknown): Reminder => {
const rem = reminder as any;
// The numbers an owner edits. The floors are as researched, not verified
// against current statute text; check them before relying on one.
const defaults = { graceDays: 7, minIntervalDays: 14, deadlineDays: { first: 14, second: 10, final: 7 } };
const floors = {
// BW 6:96(6): 14 days after receipt.
nlDays: 14,
// shortcut: post assumed received two days after sending, upgrade if tracked delivery dates are available
nlPostReceiptDays: 2,
// WER art. XIX.2: 14 days from the third working day after sending on paper, or the day after sending by email.
beDays: 14,
beWorkingDays: 3,
// Pre-Action Protocol for Debt Claims.
ukDays: 30,
};
const maxRows = 8;
// UTC day indexes, so a day does not shift with the engine's time zone.
const dayIndex = (iso: string) => {
const [y, m, d] = iso.split("-").map(Number);
return Date.UTC(y, m - 1, d) / 86_400_000;
};
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 (YYYY-MM-DD)");
}
const iso = value.slice(0, 10);
if (new Date(dayIndex(iso) * 86_400_000).toISOString().slice(0, 10) !== iso) {
throw new Error(field + " is not a real date");
}
return iso;
};
const count = (value: unknown, field: string, min: number, fallback: number): number => {
if (value === undefined || value === null) return fallback;
if (typeof value !== "number" || !Number.isInteger(value) || value < min) {
throw new Error(field + " must be an integer of at least " + min);
}
return value;
};
const dates = new Intl.DateTimeFormat("en-GB", { dateStyle: "long", timeZone: "UTC" });
const fmtDay = (index: number) => dates.format(new Date(index * 86_400_000));
if (typeof rem !== "object" || rem === null) throw new Error("reminder is required");
// 1. Validate everything first, so bad data throws even when nothing is sent.
const sendIso = isoDay(rem.sendDate, "reminder.sendDate");
const send = dayIndex(sendIso);
const checkedIso = isoDay(rem.paymentsCheckedTo, "reminder.paymentsCheckedTo");
if (dayIndex(checkedIso) > send) throw new Error("reminder.paymentsCheckedTo is after reminder.sendDate");
let money: Intl.NumberFormat;
try {
money = new Intl.NumberFormat("en-GB", { style: "currency", currency: rem.currency });
} catch {
throw new Error("reminder.currency must be an ISO 4217 code");
}
const digits = money.resolvedOptions().maximumFractionDigits as number;
const fmtMoney = (minor: number) => money.format(minor / 10 ** digits);
const graceDays = count(rem.graceDays, "reminder.graceDays", 0, defaults.graceDays);
const minInterval = count(rem.minIntervalDays, "reminder.minIntervalDays", 1, defaults.minIntervalDays);
const given = rem.deadlineDays ?? {};
if (typeof given !== "object") throw new Error("reminder.deadlineDays must be an object");
const deadlineDays = [
0,
count(given.first, "reminder.deadlineDays.first", 1, defaults.deadlineDays.first),
count(given.second, "reminder.deadlineDays.second", 1, defaults.deadlineDays.second),
count(given.final, "reminder.deadlineDays.final", 1, defaults.deadlineDays.final),
];
const floorNames = ["NL-consumer", "BE-consumer", "UK-pre-action"];
if (rem.legalFloor !== undefined && !floorNames.includes(rem.legalFloor)) {
throw new Error("reminder.legalFloor must be one of " + floorNames.join(", "));
}
if (rem.channel !== undefined && rem.channel !== "post" && rem.channel !== "email") {
throw new Error("reminder.channel must be post or email");
}
const email = rem.channel === "email";
const consequenceNames = ["suspension", "agency", "court"];
if (rem.intendedConsequences !== undefined && !Array.isArray(rem.intendedConsequences)) {
throw new Error("reminder.intendedConsequences must be an array");
}
const intended: string[] = rem.intendedConsequences ?? [];
intended.forEach((c, i) => {
if (!consequenceNames.includes(c)) {
throw new Error("reminder.intendedConsequences[" + i + "] must be one of " + consequenceNames.join(", "));
}
});
let sinceIso = "";
if (rem.customerSince !== undefined && rem.customerSince !== null && rem.customerSince !== "") {
sinceIso = isoDay(rem.customerSince, "reminder.customerSince");
if (dayIndex(sinceIso) > send) throw new Error("reminder.customerSince is after reminder.sendDate");
}
if (rem.invoices !== undefined && rem.invoices !== null && !Array.isArray(rem.invoices)) {
throw new Error("reminder.invoices must be an array");
}
const all: any[] = rem.invoices ?? [];
const included: Array<{ number: string; dueIso: string; minor: number; overdue: number; level: number }> = [];
all.forEach((inv, i) => {
const at = "reminder.invoices[" + i + "]";
if (typeof inv?.number !== "string" || inv.number.trim() === "") throw new Error(at + ".number is required");
const dueIso = isoDay(inv.dueDate, at + ".dueDate");
if (typeof inv.openAmount !== "number" || !Number.isFinite(inv.openAmount)) {
throw new Error(at + ".openAmount must be a finite number");
}
const lastLevel = inv.lastLevel ?? 0;
if (!Number.isInteger(lastLevel) || lastLevel < 0 || lastLevel > 3) {
throw new Error(at + ".lastLevel must be an integer from 0 to 3");
}
let sinceLast = Infinity;
if (lastLevel >= 1) {
if (inv.lastReminderDate === undefined || inv.lastReminderDate === null || inv.lastReminderDate === "") {
throw new Error(at + ".lastReminderDate is required when lastLevel is " + lastLevel);
}
const lastIso = isoDay(inv.lastReminderDate, at + ".lastReminderDate");
sinceLast = send - dayIndex(lastIso);
if (sinceLast < 0) throw new Error(at + ".lastReminderDate is after reminder.sendDate");
}
// 2. Minor units, so every sum is an integer.
const minor = Math.round(inv.openAmount * 10 ** digits);
// 3. Eligibility.
const overdue = send - dayIndex(dueIso);
if (
overdue > 0 && overdue >= graceDays && minor > 0 && inv.disputed !== true && inv.onHold !== true &&
lastLevel < 3 && (lastLevel === 0 || sinceLast >= minInterval)
) {
included.push({ number: inv.number, dueIso, minor, overdue, level: lastLevel + 1 });
}
});
const emptySlot = (): Slot => ({ number: "", dueDate: "", overdue: "", amount: "", line: "" });
const slots = Array.from({ length: maxRows }, emptySlot);
// 4. Nothing to chase prints nothing.
if (included.length === 0) {
return {
outcome: "none", level: 0, title: "", opening: "", invoices: slots, overflow: "", total: "", request: "",
contact: "", consequence: "", paidSince: "", promptFacts: "", deadline: "", sent: [],
};
}
// 5. The letter is as firm as its firmest invoice.
const level = Math.max(...included.map((i) => i.level)) as 1 | 2 | 3;
const mixed = included.some((i) => i.level < level);
// 6. Oldest first, ties by number.
included.sort((a, b) =>
a.dueIso < b.dueIso ? -1 : a.dueIso > b.dueIso ? 1 : a.number < b.number ? -1 : a.number > b.number ? 1 : 0
);
const one = included.length === 1;
const sum = (rows: typeof included) => rows.reduce((t, i) => t + i.minor, 0);
// 7. Slots.
included.slice(0, maxRows).forEach((inv, i) => {
const overdue = inv.overdue === 1 ? "1 day" : inv.overdue + " days";
const dueDate = fmtDay(dayIndex(inv.dueIso));
const amount = fmtMoney(inv.minor);
slots[i] = {
number: inv.number,
dueDate,
overdue,
amount,
line: "Invoice " + inv.number + ", due " + dueDate + ", " + overdue + " overdue: " + amount,
};
});
// 8. Overflow.
const rest = included.slice(maxRows);
const overflow = rest.length === 0 ? "" : rest.length + " further invoice" + (rest.length === 1 ? "" : "s") +
", totalling " + fmtMoney(sum(rest)) + ", " + (rest.length === 1 ? "is" : "are") +
" also overdue and included in the total.";
// 9, 10. Title and opening.
const title = ["", "Payment reminder", "Second reminder", "Final reminder"][level];
const some = mixed ? "some of " : "";
const below = one ? "the invoice below" : "the invoices below";
const opening = level === 1
? "Our records show that " + (one ? "the invoice below is" : "the invoices below are") + " past " +
(one ? "its" : "their") + " due date. This may simply have been overlooked, so this is a friendly reminder."
: level === 2
? "This is our second reminder about " + some + below + ". We have not yet received payment."
: "This is our final reminder about " + some + below + ". Despite earlier reminders, " +
(one ? "it remains" : "they remain") + " unpaid.";
// 11. Deadline: never before the floor, never on a weekend.
const base = send + deadlineDays[level];
let floor = -Infinity;
if (rem.legalFloor === "NL-consumer") {
floor = send + (email ? 0 : floors.nlPostReceiptDays) + floors.nlDays;
} else if (rem.legalFloor === "BE-consumer") {
if (email) {
floor = send + 1 + floors.beDays;
} else {
let day = send;
for (let worked = 0; worked < floors.beWorkingDays;) {
day += 1;
const weekday = new Date(day * 86_400_000).getUTCDay();
if (weekday !== 0 && weekday !== 6) worked += 1;
}
floor = day + floors.beDays;
}
} else if (rem.legalFloor === "UK-pre-action") {
floor = send + floors.ukDays;
}
let due = Math.max(base, floor);
const weekday = new Date(due * 86_400_000).getUTCDay();
if (weekday === 6) due += 2;
else if (weekday === 0) due += 1;
const deadline = fmtDay(due);
const total = fmtMoney(sum(included));
// 12, 13. Request and contact.
const request = level === 3
? "Please make sure " + total + " reaches us by " + deadline + "."
: "Please pay " + total + " by " + deadline + ".";
const contact = level === 1 ? "" : "If something is wrong with " + (one ? "the invoice" : "any of these invoices") +
", or you cannot pay in full by then, please contact us before " + deadline + " so we can agree a way forward.";
// 14. Consequence: only what is intended, and never for a first-time invoice.
let consequence = "";
if (level === 3 && intended.length > 0) {
const phrases: Record<string, string> = {
suspension: "suspend your service",
agency: "pass the debt to a collection agency",
court: "start a court claim to recover it",
};
const list = new Intl.ListFormat("en-GB", { type: "conjunction" });
const what = list.format(consequenceNames.filter((c) => intended.includes(c)).map((c) => phrases[c]));
const final = included.filter((i) => i.level === 3);
consequence = final.length === included.length
? "If we have not received payment by " + deadline + ", we intend to " + what + "."
: "If invoice" + (final.length === 1 ? " " : "s ") + list.format(final.map((i) => i.number)) +
(final.length === 1 ? " is" : " are") + " not paid by " + deadline + ", we intend to " + what + ".";
}
// 15. Payments cross in the post.
const paidSince = "This reminder takes account of payments received up to and including " +
fmtDay(dayIndex(checkedIso)) + ". If you have paid since then, thank you, and please ignore this reminder.";
// 16. Facts for the generated opening.
let promptFacts = "This is the " + ["", "first", "second", "final"][level] + " reminder. The oldest invoice in it is " +
Math.max(...included.map((i) => i.overdue)) + " days overdue.";
if (sinceIso) {
const [y1, m1, d1] = sinceIso.split("-").map(Number);
const [y2, m2, d2] = sendIso.split("-").map(Number);
const months = (y2 - y1) * 12 + (m2 - m1) - (d2 < d1 ? 1 : 0);
const years = Math.floor(months / 12);
promptFacts += " The customer has been with us for " + (months >= 12
? years + (years === 1 ? " year" : " years")
: months >= 1
? months + (months === 1 ? " month" : " months")
: "less than a month") + ".";
}
return {
outcome: "remind", level, title, opening, invoices: slots, overflow, total, request, contact, consequence,
paidSince, promptFacts, deadline, sent: included.map((i) => ({ number: i.number, level: i.level as 1 | 2 | 3 })),
};
},
}); arrangements/dunning-reminder/lines.ts /**
* What the dunning reminder hands each of its arrangements: the invoice lines
* it has already decided on. An arrangement places these and decides nothing,
* so both print the same slots, overflow and total under the same conditions.
*
* There are always eight slots. An unused slot has every field `""`, so test
* `{lines.invoices[0].number && …}` in the JSX, which compiles into a condition
* the engine settles per document.
*
* Installed by `dxcl add dunning-reminder`, with the arrangements.
*/
export interface DunningReminderLines {
/** The eight invoice slots, oldest first. */
invoices: Array<{
/** The invoice number, as given. `""` when the slot is unused. */
number: string;
/** The due date, formatted. */
dueDate: string;
/** Days overdue, as "1 day" or "N days". */
overdue: string;
/** The open amount, formatted. */
amount: string;
/** The whole invoice as one sentence, for a stacked layout. */
line: string;
}>;
/** The sentence covering invoices beyond the eighth, or `""` when there are none. */
overflow: string;
/** The formatted sum of every included invoice, overflow too. */
total: string;
} arrangements/dunning-reminder/table.arrangement.tsx import { Cell, Paragraph, Row, Table, type Yield } from "docxcelerate/template";
import type { DunningReminderLines } from "./lines.ts";
/**
* Number, due date, days overdue and amount in columns, with a total row. A
* reminder covering several invoices is read by scanning amounts down one
* column, which is why this is the default.
*/
export const table = (lines: DunningReminderLines): Yield => (
<>
<Table
id="dunning-reminder-invoices"
columns={[{ width: "auto" }, { width: 32 }, { width: 24 }, { width: 32, align: "right" }]}
>
<Row id="dunning-reminder-invoices-header" header>
<Cell>Invoice</Cell>
<Cell>Due date</Cell>
<Cell>Overdue</Cell>
<Cell>Amount</Cell>
</Row>
{lines.invoices[0].number && (
<Row id="dunning-reminder-invoice-1">
<Cell>{lines.invoices[0].number}</Cell>
<Cell>{lines.invoices[0].dueDate}</Cell>
<Cell>{lines.invoices[0].overdue}</Cell>
<Cell>{lines.invoices[0].amount}</Cell>
</Row>
)}
{lines.invoices[1].number && (
<Row id="dunning-reminder-invoice-2">
<Cell>{lines.invoices[1].number}</Cell>
<Cell>{lines.invoices[1].dueDate}</Cell>
<Cell>{lines.invoices[1].overdue}</Cell>
<Cell>{lines.invoices[1].amount}</Cell>
</Row>
)}
{lines.invoices[2].number && (
<Row id="dunning-reminder-invoice-3">
<Cell>{lines.invoices[2].number}</Cell>
<Cell>{lines.invoices[2].dueDate}</Cell>
<Cell>{lines.invoices[2].overdue}</Cell>
<Cell>{lines.invoices[2].amount}</Cell>
</Row>
)}
{lines.invoices[3].number && (
<Row id="dunning-reminder-invoice-4">
<Cell>{lines.invoices[3].number}</Cell>
<Cell>{lines.invoices[3].dueDate}</Cell>
<Cell>{lines.invoices[3].overdue}</Cell>
<Cell>{lines.invoices[3].amount}</Cell>
</Row>
)}
{lines.invoices[4].number && (
<Row id="dunning-reminder-invoice-5">
<Cell>{lines.invoices[4].number}</Cell>
<Cell>{lines.invoices[4].dueDate}</Cell>
<Cell>{lines.invoices[4].overdue}</Cell>
<Cell>{lines.invoices[4].amount}</Cell>
</Row>
)}
{lines.invoices[5].number && (
<Row id="dunning-reminder-invoice-6">
<Cell>{lines.invoices[5].number}</Cell>
<Cell>{lines.invoices[5].dueDate}</Cell>
<Cell>{lines.invoices[5].overdue}</Cell>
<Cell>{lines.invoices[5].amount}</Cell>
</Row>
)}
{lines.invoices[6].number && (
<Row id="dunning-reminder-invoice-7">
<Cell>{lines.invoices[6].number}</Cell>
<Cell>{lines.invoices[6].dueDate}</Cell>
<Cell>{lines.invoices[6].overdue}</Cell>
<Cell>{lines.invoices[6].amount}</Cell>
</Row>
)}
{lines.invoices[7].number && (
<Row id="dunning-reminder-invoice-8">
<Cell>{lines.invoices[7].number}</Cell>
<Cell>{lines.invoices[7].dueDate}</Cell>
<Cell>{lines.invoices[7].overdue}</Cell>
<Cell>{lines.invoices[7].amount}</Cell>
</Row>
)}
<Row id="dunning-reminder-total">
<Cell>Total overdue</Cell>
<Cell></Cell>
<Cell></Cell>
<Cell>{lines.total}</Cell>
</Row>
</Table>
{lines.overflow && <Paragraph id="dunning-reminder-overflow">{lines.overflow}</Paragraph>}
</>
); arrangements/dunning-reminder/stacked.arrangement.tsx import { Paragraph, type Yield } from "docxcelerate/template";
import type { DunningReminderLines } from "./lines.ts";
/**
* One sentence per invoice down the text column, then the total. Suits plain
* letters and narrow columns, where four table columns would crowd.
*/
export const stacked = (lines: DunningReminderLines): Yield => (
<>
{lines.invoices[0].number && (
<Paragraph id="dunning-reminder-invoice-1">{lines.invoices[0].line}</Paragraph>
)}
{lines.invoices[1].number && (
<Paragraph id="dunning-reminder-invoice-2">{lines.invoices[1].line}</Paragraph>
)}
{lines.invoices[2].number && (
<Paragraph id="dunning-reminder-invoice-3">{lines.invoices[2].line}</Paragraph>
)}
{lines.invoices[3].number && (
<Paragraph id="dunning-reminder-invoice-4">{lines.invoices[3].line}</Paragraph>
)}
{lines.invoices[4].number && (
<Paragraph id="dunning-reminder-invoice-5">{lines.invoices[4].line}</Paragraph>
)}
{lines.invoices[5].number && (
<Paragraph id="dunning-reminder-invoice-6">{lines.invoices[5].line}</Paragraph>
)}
{lines.invoices[6].number && (
<Paragraph id="dunning-reminder-invoice-7">{lines.invoices[6].line}</Paragraph>
)}
{lines.invoices[7].number && (
<Paragraph id="dunning-reminder-invoice-8">{lines.invoices[7].line}</Paragraph>
)}
{lines.overflow && <Paragraph id="dunning-reminder-overflow">{lines.overflow}</Paragraph>}
<Paragraph id="dunning-reminder-total">Total overdue: {lines.total}</Paragraph>
</>
);