Advance payment invoice
BodyA deposit or prepayment invoice against an order: the order total, what has already been requested, the share requested now and what is left to invoice. A percentage is taken of the order gross, never of the net plus VAT, because the customer expects the figure on the quote and the two routes differ by a cent. On a mixed-rate order the deposit is spread across the rates by largest remainder in minor units, so the shares add up to the deposit and deposits plus balance add up to the order, exactly. Requesting more than 100% of the order fails the document. UK and EU prepayments are charged VAT now, because the payment is a tax point, and the date of payment prints when it differs from the issue date. Germany says it is an Anzahlungsrechnung. A US deposit carries no sales tax until the final invoice, and a refundable security deposit carries no VAT and says so. Every figure comes from one deriver.
npx dxcl add advance-payment-invoice deposit.kind Datos de vista previa
el JSON con el que se construyó esta vista previa{
"order": {
"reference": "SO-2026-11-004817/FACILITIES-NORTH-REFIT/REV-3",
"date": "2026-10-14",
"currency": "GBP",
"lines": [
{
"gross": 1284750,
"vatRate": 20
},
{
"net": 412333.33,
"vatRate": 5
},
{
"gross": 96410.07,
"vatRate": 0
}
]
},
"deposit": {
"percent": 30,
"kind": "prepayment",
"receivedDate": "2026-11-28"
},
"previousDeposits": [
{
"number": "ADV-2026-11-000417-A",
"amount": 250000
},
{
"number": "ADV-2026-11-000418-B",
"amount": 125000
}
],
"invoice": {
"jurisdiction": "UK",
"issueDate": "2026-11-30"
}
} {
"order": {
"reference": "SO-2026-11-004817/FACILITIES-NORTH-REFIT/REV-3",
"date": "2026-10-14",
"currency": "GBP",
"lines": [
{
"gross": 1284750,
"vatRate": 20
},
{
"net": 412333.33,
"vatRate": 5
},
{
"gross": 96410.07,
"vatRate": 0
}
]
},
"deposit": {
"percent": 30,
"kind": "security",
"receivedDate": "2026-11-28"
},
"previousDeposits": [
{
"number": "ADV-2026-11-000417-A",
"amount": 250000
},
{
"number": "ADV-2026-11-000418-B",
"amount": 125000
}
],
"invoice": {
"jurisdiction": "UK",
"issueDate": "2026-11-30"
}
} Vista previa renderizada
cada disposición renderizada por su cuentaarrangement="table" predeterminada arrangement="stacked" arrangement="table" predeterminada arrangement="stacked" Nodos resueltos
lo que recibe un renderizador — 1 nodosadvance-payment section advance-payment section Los archivos
lo que escribe la instalación; el archivo seleccionado es el componentenodes/advance-payment-invoice.node.tsx import { arrange, Paragraph, Section, type Section as SectionComponent, useDeriver, useState } from "docxcelerate/template";
import type { AdvancePaymentInvoiceLines } from "../arrangements/advance-payment-invoice/lines.ts";
import { stacked } from "../arrangements/advance-payment-invoice/stacked.arrangement.tsx";
import { table } from "../arrangements/advance-payment-invoice/table.arrangement.tsx";
import advancePaymentInvoice from "../derivers/advance-payment-invoice.deriver.ts";
/**
* The body of a deposit or prepayment invoice raised against an identified
* order: the order total, each deposit already requested, the share requested
* now and what is left to invoice, with a per-rate VAT analysis of this
* deposit when VAT applies.
*
* A percentage is taken of the order gross, never of net plus VAT. The
* customer expects the figure on the quote, and the two routes differ by a
* cent (30% of 100.05 gross at 20% is 30.02; of net plus VAT it is 30.01).
*
* A mixed-rate order is spread across its rates by largest remainder in minor
* units, so the band shares add up to the deposit exactly and previous
* deposits plus this one plus what is left add up to the order total. No
* remainder cent goes missing. Previous deposits are not split by rate, only
* this one: largest remainder is not monotone, so a per-rate balance could go
* a cent negative.
*
* Previous deposits (at most 8) and rate bands (at most 4) are fixed slots
* rather than a `.map()`: the resolver reads a published loop's collection
* from request data and ignores the derived scope, so a loop over the
* deriver's lists would publish and then print no rows. More than that throws.
*
* Requests are capped at the order total: more than 100% fails the document
* rather than printing a balance that is negative.
*
* Each kind of deposit gets its own tax wording. A UK or EU prepayment is
* charged VAT now, because the payment is a tax point, and the date of payment
* prints when it differs from the issue date. Germany says it is an
* Anzahlungsrechnung. A US deposit carries no sales tax until the final
* invoice. A refundable security deposit is not a payment for the supply, so
* it carries no VAT and says so. Which wording applies is an ordinary
* conditional with an id per arm, so a resolved document records which one a
* recipient got; every test is written inline against `deposit.kind` and
* `invoice.jurisdiction`, never hoisted into a `const`, because while
* publishing a hoisted `===` is settled to a plain boolean and every recipient
* gets the same arm.
*
* Every figure comes from one deriver, because arithmetic on request data
* throws at publish. The invoice number, issue date and heading belong to
* `invoice-document-type`, which reads the same `invoice.jurisdiction` and
* `invoice.issueDate`.
*
* Arrangement: this file decides every line; each arrangement, in
* `arrangements/advance-payment-invoice/`, only places them.
*
* Not covered: the final invoice that deducts these deposits, exempt order
* lines, non-refundable US deposits that some states tax on receipt, and
* supplies where an advance payment does not make VAT chargeable (reverse
* charge, intra-Community supplies of goods, margin scheme). The statute
* references are not checked against primary sources: have an adviser look.
*
* Installed by `dxcl add advance-payment-invoice`, which also installs its deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface AdvancePaymentInvoiceData {
order: {
/**
* The order, quote or contract this deposit is raised against, printed as
* given (trimmed) so the customer can match it. Required: the deriver
* throws when it is missing or blank, because a deposit that names no
* order cannot be reconciled.
*/
reference: string;
/**
* When the order was placed, ISO 8601 (`2026-10-14`). Anything after the
* tenth character is ignored. Missing or empty means the line is not
* printed. Throws when present but not an ISO date.
*/
date?: string;
/**
* ISO 4217 code: "GBP", "EUR", "USD", "JPY". Required, with no default.
* Its exponent (number of decimal places) comes from Intl. A code Intl
* rejects throws, naming `order.currency`.
*/
currency: string;
/**
* The order's lines, enough to give the total at each rate. Required and
* non-empty: missing or empty throws, because there is no order total to
* take a deposit of. Descriptions are not needed and not printed.
*/
lines: Array<{
/**
* The line's VAT-inclusive amount in major units (pounds, not pence). Give
* exactly one of `gross` or `net`: both, or neither, throws. It is
* rounded once to minor units, half away from zero. May be negative (a
* discount), as long as its rate band stays at zero or above.
*/
gross?: number;
/**
* The line's amount excluding VAT, in major units. VAT is added once per
* band on the sum of that band's net lines, not once per line. Same
* rules as `gross`. In the US, give the pre-tax amount here.
*/
net?: number;
/**
* The VAT rate as a percentage: 20, 5, 0, 7.7. 0 is zero-rated and
* prints as "0%". Required outside the US: missing, negative or not
* finite throws. Not read in the US, where no tax is charged on a
* deposit. Exempt (no-rate) lines are not supported.
*/
vatRate?: number;
}>;
};
deposit: {
/**
* The share of the order gross requested on this invoice, as a percentage
* (30, 12.5). Must be greater than 0 and no more than 100. Give exactly one
* of `percent` or `amount`: both, or neither, throws.
*/
percent?: number;
/**
* A fixed amount requested on this invoice, gross, in major units. Must be
* greater than 0. Rounded to minor units, half away from zero.
*/
amount?: number;
/**
* `prepayment` is part of the price, paid in advance and deducted from the
* final invoice. `security` is a refundable security deposit, returned at
* the end of the hire: no VAT, no VAT analysis, and it does not reduce
* what is left to invoice. Required: anything else throws. Read as a
* prepayment by mistake, a security deposit would be charged VAT. Read as
* a security deposit by mistake, a prepayment would go without the VAT
* that is due.
*/
kind: "prepayment" | "security";
/**
* When the payment was received (or will be), ISO 8601. Read only for a
* prepayment outside the US. Printed when given and on a different day
* from `invoice.issueDate`. Missing or empty means no line. Throws when
* present but not an ISO date.
*/
receivedDate?: string;
};
/**
* Prepayments already requested against this order, in the order they were
* issued. Missing or empty means none. Each is printed on its own line and
* counts towards the 100% cap.
*/
previousDeposits?: Array<{
/** The earlier deposit invoice's number, printed as given (trimmed). Missing or blank throws. */
number: string;
/** What it requested, gross, in major units. Must be greater than 0. */
amount: number;
}>;
invoice: {
/**
* Whose rules apply. `EU` means a member state with no rules of its own
* here, which gets the Directive's defaults. `FR` gets the EU wording.
* `US` has no VAT: no rate is read, no VAT analysis is printed. Required:
* anything else throws.
*/
jurisdiction: "UK" | "EU" | "DE" | "FR" | "US";
/**
* This invoice's date of issue, ISO 8601. Required: throws when missing or
* not YYYY-MM-DD. It is only compared against `deposit.receivedDate` and
* is not printed here; `invoice-document-type` prints it.
*/
issueDate: string;
};
}
/**
* Where the lines sit.
*
* - `table`: labels in a column with the figures right-aligned beside them, so
* the subtraction can be checked down the page. The default.
* - `stacked`: one labelled line under another, down the text column.
*/
export type AdvancePaymentInvoiceArrangement = "table" | "stacked";
/** Props for {@linkcode AdvancePaymentInvoice}. */
export interface AdvancePaymentInvoiceProps {
/** Where the lines sit. Defaults to `"table"`. */
arrangement?: AdvancePaymentInvoiceArrangement;
}
export const AdvancePaymentInvoice: SectionComponent<AdvancePaymentInvoiceProps> = async ({ arrangement }) => {
const [order] = useState((data: AdvancePaymentInvoiceData) => data.order);
const [deposit] = useState((data: AdvancePaymentInvoiceData) => data.deposit);
const [previousDeposits] = useState((data: AdvancePaymentInvoiceData) => data.previousDeposits);
const [invoice] = useState((data: AdvancePaymentInvoiceData) => data.invoice);
const figures = await useDeriver(advancePaymentInvoice, [order, deposit, previousDeposits, invoice]);
const lines: AdvancePaymentInvoiceLines = {
orderReference: figures.orderReference,
orderDate: figures.orderDate,
orderTotal: figures.orderTotal,
previous: figures.previousSlots,
depositLabel: figures.depositLabel,
deposit: figures.deposit,
leftToInvoice: figures.leftToInvoice,
paymentDateLabel: figures.paymentDateLabel,
paymentDate: figures.paymentDate,
vatApplies: figures.vatApplies,
bands: figures.bandSlots,
netTotal: figures.netTotal,
vatTotal: figures.vatTotal,
};
return (
<Section id="advance-payment" title={figures.title}>
{arrange(arrangement, {
table: () => table(lines),
stacked: () => stacked(lines),
})}
{deposit.kind === "security" && (
<Paragraph id="advance-payment-tax-security">
This is a refundable security deposit, returned at the end of the hire. It is not a payment for the supply
and is not deducted from the order, so no VAT or sales tax is charged on it.
</Paragraph>
)}
{deposit.kind !== "security" && invoice.jurisdiction === "UK" && (
<Paragraph id="advance-payment-tax-uk">
VAT is charged on this payment now. A payment received before the supply is made creates a tax point at the
earlier of the date of this invoice and the date the payment is received (VATA 1994 s6(4)).
</Paragraph>
)}
{deposit.kind !== "security" && (invoice.jurisdiction === "EU" || invoice.jurisdiction === "FR") && (
<Paragraph id="advance-payment-tax-eu">
VAT is charged on this payment on account now: it becomes chargeable when the payment is received (Art. 65
Directive 2006/112/EC).
</Paragraph>
)}
{deposit.kind !== "security" && invoice.jurisdiction === "DE" && (
<Paragraph id="advance-payment-tax-de">
Anzahlungsrechnung über eine noch nicht ausgeführte Leistung. Die Umsatzsteuer entsteht mit Vereinnahmung der
Anzahlung (§ 13 Abs. 1 Nr. 1 Buchst. a Satz 4 UStG).
</Paragraph>
)}
{deposit.kind !== "security" && invoice.jurisdiction === "US" && (
<Paragraph id="advance-payment-tax-us">
This deposit is refundable and no sales tax is charged on it. Sales tax will be charged on the final invoice.
</Paragraph>
)}
</Section>
);
}; derivers/advance-payment-invoice.deriver.ts import { deriver } from "docxcelerate/template";
/** What the deriver hands the node: every display string, and the same figures as integers. */
export interface AdvancePaymentInvoiceFigures {
/** The section heading: "Advance payment", "Anzahlung" or "Security deposit". */
title: string;
/** The order reference, trimmed. */
orderReference: string;
/** The order date, formatted, or null when none was given. */
orderDate: string | null;
/** The order gross, formatted. */
orderTotal: string;
/** One per previous deposit, in input order. */
previous: Array<{
/** The earlier deposit's invoice number, trimmed. */
number: string;
/** The earlier deposit, formatted. */
amount: string;
}>;
/**
* `previous` padded with empty entries (`number` is "") to 8 slots. The page
* prints fixed slots because the resolver cannot loop over a derived list.
*/
previousSlots: Array<{ number: string; amount: string }>;
/** What the deposit line says, naming the percentage when one was given. */
depositLabel: string;
/** This request, formatted. */
deposit: string;
/** What is left to invoice, formatted. */
leftToInvoice: string;
/** "Date of payment" or "Zeitpunkt der Vereinnahmung"; null when no date prints. */
paymentDateLabel: string | null;
/** The date payment was received, formatted; null when no date prints. */
paymentDate: string | null;
/** True when the VAT analysis is printed: a prepayment outside the US. */
vatApplies: boolean;
/** This deposit's VAT analysis, one per rate; empty when `vatApplies` is false. */
bands: Array<{
/** The band's rate, formatted: "20%". */
label: string;
/** This deposit's net in the band, formatted. */
net: string;
/** This deposit's VAT in the band, formatted. */
vat: string;
/** This deposit's share of the band, gross, formatted. */
gross: string;
/** This deposit's share of the band, gross, in minor units. */
shareMinor: number;
/** This deposit's net in the band, in minor units. */
netMinor: number;
/** This deposit's VAT in the band, in minor units. */
vatMinor: number;
}>;
/**
* `bands` padded with empty entries (`label` is "") to 4 slots, for the same
* reason as `previousSlots`.
*/
bandSlots: Array<{ label: string; net: string; vat: string; gross: string }>;
/** Net total of the analysis, formatted; "" when `vatApplies` is false. */
netTotal: string;
/** VAT total of the analysis, formatted; "" when `vatApplies` is false. */
vatTotal: string;
/** The order gross in minor units, so tests assert on integers rather than Intl strings. */
orderTotalMinor: number;
/** This deposit in minor units. */
depositMinor: number;
/** All previous deposits in minor units. */
previousMinor: number;
/** What is left to invoice, in minor units. */
leftMinor: number;
/** The analysis net total in minor units; 0 when `vatApplies` is false. */
netTotalMinor: number;
/** The analysis VAT total in minor units; 0 when `vatApplies` is false. */
vatTotalMinor: number;
}
/**
* Every figure on a deposit invoice, worked once, so the page adds up to the
* penny: previous deposits plus this one plus what is left is the order total.
*
* Money is integer minor units at the currency's own exponent (taken from
* `Intl`), and every decimal is parsed exactly into a BigInt: no float is ever
* multiplied and `toFixed` is never used. A percentage is taken of the order
* gross, never of net plus VAT, because that is the figure on the customer's
* quote. A mixed-rate deposit is spread across the rates by largest remainder,
* so the shares add up to the deposit, and VAT is backed out of each share.
*
* It lives in a deriver because arithmetic on request data throws at publish.
* It is self-contained on purpose: it travels to the engine as source text, so
* a module-level helper or constant would be a ReferenceError there.
*
* Installed by `dxcl add advance-payment-invoice`.
*/
export default deriver({
name: "advancePaymentInvoice",
run: (order: unknown, deposit: unknown, previousDeposits: unknown, invoice: unknown): AdvancePaymentInvoiceFigures => {
// deno-lint-ignore no-explicit-any
const ord = order as any;
// deno-lint-ignore no-explicit-any
const dep = deposit as any;
// deno-lint-ignore no-explicit-any
const inv = invoice as any;
const DECIMAL = /^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/;
// String(n) is the shortest round-trip form, which is what the caller wrote.
const decimal = (n: number): { int: bigint; scale: number } => {
const match = DECIMAL.exec(String(n));
if (!match) throw new Error("cannot read " + n + " as a decimal");
const [, sign, whole, frac = "", exp = "0"] = match;
let int = BigInt(whole + frac);
let scale = frac.length - Number(exp);
if (scale < 0) {
int *= 10n ** BigInt(-scale);
scale = 0;
}
return { int: sign ? -int : int, scale };
};
/** round(n / d) half away from zero, for d > 0. */
const round = (n: bigint, d: bigint): bigint => {
const abs = n < 0n ? -n : n;
const out = (2n * abs + d) / (2n * d);
return n < 0n ? -out : out;
};
const isDay = (v: unknown): v is string => {
return typeof v === "string" && /^\d{4}-\d{2}-\d{2}/.test(v) &&
!Number.isNaN(new Date(v.slice(0, 10) + "T00:00:00Z").getTime());
};
const finite = (v: unknown, path: string): number => {
if (typeof v !== "number" || !Number.isFinite(v)) throw new Error(path + " must be a finite number");
return v;
};
const present = (v: unknown) => v !== undefined && v !== null && v !== "";
// 1. Validate, in the documented order.
const jurisdictions = ["UK", "EU", "DE", "FR", "US"];
if (!jurisdictions.includes(inv?.jurisdiction)) {
throw new Error("invoice.jurisdiction must be one of " + jurisdictions.join(", "));
}
if (!isDay(inv.issueDate)) throw new Error("invoice.issueDate must be an ISO 8601 date");
if (typeof ord?.reference !== "string" || ord.reference.trim() === "") {
throw new Error("order.reference is required");
}
const jurisdiction: string = inv.jurisdiction;
const us = jurisdiction === "US";
const de = jurisdiction === "DE";
let exponent = 2;
try {
if (typeof ord.currency !== "string") throw new Error("not a string");
exponent = new Intl.NumberFormat("en-GB", { style: "currency", currency: ord.currency }).resolvedOptions()
.maximumFractionDigits as number;
} catch {
throw new Error("order.currency must be an ISO 4217 code");
}
if (!Array.isArray(ord.lines) || ord.lines.length === 0) {
throw new Error("order.lines is required and must not be empty");
}
const unit = 10n ** BigInt(exponent);
/** A major-unit amount as minor units, rounded once. */
const minor = (n: number): bigint => {
const d = decimal(n);
return round(d.int * unit, 10n ** BigInt(d.scale));
};
const lineRows: Array<{ gross: bigint | null; net: bigint | null; rate: number }> = [];
ord.lines.forEach((line: { gross?: unknown; net?: unknown; vatRate?: unknown }, i: number) => {
const at = "order.lines[" + i + "]";
const hasGross = present(line?.gross);
const hasNet = present(line?.net);
if (hasGross === hasNet) throw new Error(at + " needs exactly one of gross or net");
const amount = finite(hasGross ? line.gross : line.net, at + (hasGross ? ".gross" : ".net"));
let rate = 0;
if (!us) {
rate = finite(line.vatRate, at + ".vatRate");
if (rate < 0) throw new Error(at + ".vatRate must not be negative");
}
lineRows.push({ gross: hasGross ? minor(amount) : null, net: hasNet ? minor(amount) : null, rate });
});
const kinds = ["prepayment", "security"];
if (!kinds.includes(dep?.kind)) throw new Error("deposit.kind must be one of " + kinds.join(", "));
const prepayment = dep.kind === "prepayment";
const hasPercent = present(dep.percent);
const hasAmount = present(dep.amount);
if (hasPercent === hasAmount) throw new Error("deposit needs exactly one of percent or amount");
if (hasPercent) {
const p = finite(dep.percent, "deposit.percent");
if (!(p > 0 && p <= 100)) throw new Error("deposit.percent must be over 0 and at most 100");
} else if (!(finite(dep.amount, "deposit.amount") > 0)) {
throw new Error("deposit.amount must be greater than 0");
}
const prevInput: unknown[] = present(previousDeposits) ? (previousDeposits as unknown[]) : [];
if (!Array.isArray(prevInput)) throw new Error("previousDeposits must be a list");
const previous = prevInput.map((entry, i) => {
// deno-lint-ignore no-explicit-any
const p = entry as any;
const at = "previousDeposits[" + i + "]";
if (typeof p?.number !== "string" || p.number.trim() === "") throw new Error(at + ".number is required");
if (!(finite(p.amount, at + ".amount") > 0)) throw new Error(at + ".amount must be greater than 0");
return { number: p.number.trim() as string, amount: minor(p.amount) };
});
const dayOf = (v: unknown, path: string): string | null => {
if (!present(v)) return null;
if (!isDay(v)) throw new Error(path + " must be an ISO 8601 date");
return v.slice(0, 10);
};
const orderDay = dayOf(ord.date, "order.date");
const receivedDay = dayOf(dep.receivedDate, "deposit.receivedDate");
const issueDay = inv.issueDate.slice(0, 10) as string;
// 3. Bands, in the order their rate first appears.
const bandGross: Array<{ rate: number; gross: bigint }> = [];
if (us) {
let sum = 0n;
for (const l of lineRows) sum += (l.net ?? l.gross) as bigint;
bandGross.push({ rate: 0, gross: sum });
} else {
const groups = new Map<number, { gross: bigint; net: bigint }>();
for (const l of lineRows) {
const g = groups.get(l.rate) ?? { gross: 0n, net: 0n };
g.gross += l.gross ?? 0n;
g.net += l.net ?? 0n;
groups.set(l.rate, g);
}
for (const [rate, g] of groups) {
const r = decimal(rate);
// VAT on net lines is worked once per band, on the band's net sum.
const vat = round(g.net * r.int, 100n * 10n ** BigInt(r.scale));
const total = g.gross + g.net + vat;
if (total < 0n) throw new Error("order.lines: the " + rate + "% band is negative");
if (total > 0n) bandGross.push({ rate, gross: total });
}
}
let G = 0n;
for (const b of bandGross) G += b.gross;
if (G <= 0n) throw new Error("order.lines must total more than zero");
// 4. This deposit.
let D: bigint;
if (hasPercent) {
const p = decimal(dep.percent);
D = round(G * p.int, 100n * 10n ** BigInt(p.scale));
} else {
D = minor(dep.amount);
}
// Formatting needs the locale, so the cap message can print money.
const locale = us ? "en-US" : "en-GB";
const moneyFormat = new Intl.NumberFormat(locale, {
style: "currency",
currency: ord.currency,
minimumFractionDigits: exponent,
maximumFractionDigits: exponent,
});
const money = (n: bigint) => moneyFormat.format(Number(n) / Number(unit));
if (D <= 0n) throw new Error("deposit rounds to zero: it must be at least one minor unit");
// 5. Cap. The page prints 8 previous deposits and 4 rate bands in fixed slots.
if (previous.length > 8) throw new Error("previousDeposits has " + previous.length + " entries; at most 8 print");
if (bandGross.length > 4) throw new Error("order.lines has " + bandGross.length + " VAT rates; at most 4 print");
let P = 0n;
for (const p of previous) P += p.amount;
if (P > G) {
throw new Error("deposits requested (" + money(P) + ") exceed the order total (" + money(G) + ")");
}
if (prepayment && P + D > G) {
throw new Error("deposits requested (" + money(P + D) + ") exceed the order total (" + money(G) + ")");
}
const L = prepayment ? G - P - D : G - P;
// 6. Label.
const pct = (n: number) => new Intl.NumberFormat("en-GB", { maximumFractionDigits: 4 }).format(n);
const base = prepayment ? "Deposit requested" : "Security deposit";
const depositLabel = hasPercent ? base + " (" + pct(dep.percent) + "% of the order total)" : base;
// 7. Spread the deposit across the bands, by largest remainder.
const vatApplies = prepayment && !us;
const bands: AdvancePaymentInvoiceFigures["bands"] = [];
let netTotal = 0n;
let vatTotal = 0n;
if (vatApplies) {
const shares = bandGross.map((b) => (D * b.gross) / G);
const rems = bandGross.map((b) => (D * b.gross) % G);
let leftover = D;
for (const s of shares) leftover -= s;
const order = rems.map((_, i) => i).sort((a, b) => (rems[b] > rems[a] ? 1 : rems[b] < rems[a] ? -1 : a - b));
for (let k = 0; k < Number(leftover); k++) shares[order[k]] += 1n;
bandGross.forEach((b, i) => {
const r = decimal(b.rate);
const vat = round(shares[i] * r.int, 100n * 10n ** BigInt(r.scale) + r.int);
const net = shares[i] - vat;
netTotal += net;
vatTotal += vat;
bands.push({
label: pct(b.rate) + "%",
net: money(net),
vat: money(vat),
gross: money(shares[i]),
shareMinor: Number(shares[i]),
netMinor: Number(net),
vatMinor: Number(vat),
});
});
}
// 8. Dates, in UTC so the day cannot shift on the engine.
const dateFormat = new Intl.DateTimeFormat(locale, { dateStyle: "long", timeZone: "UTC" });
const fmtDay = (d: string) => dateFormat.format(new Date(d + "T00:00:00Z"));
const showPayment = vatApplies && receivedDay !== null && receivedDay !== issueDay;
const slots = <T extends { number?: string; label?: string }>(rows: T[], n: number, empty: T): T[] => {
const out = rows.slice();
while (out.length < n) out.push(empty);
return out;
};
return {
title: !prepayment ? "Security deposit" : de ? "Anzahlung" : "Advance payment",
orderReference: ord.reference.trim(),
orderDate: orderDay === null ? null : fmtDay(orderDay),
orderTotal: money(G),
previous: previous.map((p) => ({ number: p.number, amount: money(p.amount) })),
previousSlots: slots(previous.map((p) => ({ number: p.number, amount: money(p.amount) })), 8, { number: "", amount: "" }),
depositLabel,
deposit: money(D),
leftToInvoice: money(L),
paymentDateLabel: showPayment ? (de ? "Zeitpunkt der Vereinnahmung" : "Date of payment") : null,
paymentDate: showPayment ? fmtDay(receivedDay as string) : null,
vatApplies,
bands,
bandSlots: slots(bands.map((b) => ({ label: b.label, net: b.net, vat: b.vat, gross: b.gross })), 4, {
label: "",
net: "",
vat: "",
gross: "",
}),
netTotal: vatApplies ? money(netTotal) : "",
vatTotal: vatApplies ? money(vatTotal) : "",
orderTotalMinor: Number(G),
depositMinor: Number(D),
previousMinor: Number(P),
leftMinor: Number(L),
netTotalMinor: Number(netTotal),
vatTotalMinor: Number(vatTotal),
};
},
}); arrangements/advance-payment-invoice/lines.ts /**
* What the advance payment invoice hands each of its arrangements: every line
* it may print, already decided. An arrangement places these and decides
* nothing, so both print the same lines under the same conditions.
*
* A field that is `null` is a line this invoice does not carry. Test it in the
* JSX, `{lines.orderDate && …}`, so the test is compiled into a condition the
* engine settles per document. The two lists are fixed slots, 8 previous
* deposits and 4 rate bands, each printed when its first field is not empty:
* the resolver reads a loop's collection from request data and ignores the
* derived scope, so a `.map()` over them would publish and then print no rows.
*
* Installed by `dxcl add advance-payment-invoice`, with the arrangements.
*/
export interface AdvancePaymentInvoiceLines {
/** The order the deposit is against, as given (trimmed). */
orderReference: string;
/** The order date, formatted, or null when none was given. */
orderDate: string | null;
/** The order gross, formatted. */
orderTotal: string;
/** Eight slots: a deposit already requested, in the order issued, then empty ones (`number` is ""). */
previous: Array<{
/** The earlier deposit's invoice number; "" in an unused slot. */
number: string;
/** The earlier deposit, formatted. */
amount: string;
}>;
/** What the deposit line says: "Deposit requested (30% of the order total)", "Security deposit". */
depositLabel: string;
/** This request, formatted. */
deposit: string;
/** What is left to invoice, formatted. */
leftToInvoice: string;
/** "Date of payment" or "Zeitpunkt der Vereinnahmung"; null when no date prints. */
paymentDateLabel: string | null;
/** The date payment was received, formatted; null when no date prints. */
paymentDate: string | null;
/** Whether the VAT analysis is printed. */
vatApplies: boolean;
/** Four slots: this deposit's VAT analysis, one per rate, then empty ones (`label` is ""). */
bands: Array<{
/** The band's rate, formatted; "" in an unused slot. */
label: string;
/** This deposit's net in the band, formatted. */
net: string;
/** This deposit's VAT in the band, formatted. */
vat: string;
/** This deposit's share of the band, formatted. */
gross: string;
}>;
/** The analysis net total; "" when `vatApplies` is false. */
netTotal: string;
/** The analysis VAT total; "" when `vatApplies` is false. */
vatTotal: string;
} arrangements/advance-payment-invoice/table.arrangement.tsx import { Cell, Row, Table, type Yield } from "docxcelerate/template";
import type { AdvancePaymentInvoiceLines } from "./lines.ts";
/**
* Labels in a column with the figures right-aligned beside them, so the
* subtraction (previous plus this plus what is left is the order) can be
* checked down the page. The default.
*/
export const table = (lines: AdvancePaymentInvoiceLines): Yield => (
<>
<Table id="advance-payment-figures" columns={[{ width: "auto" }, { width: 40, align: "right" }]}>
<Row id="advance-payment-order-reference">
<Cell>Order reference</Cell>
<Cell>{lines.orderReference}</Cell>
</Row>
{lines.orderDate && (
<Row id="advance-payment-order-date">
<Cell>Order date</Cell>
<Cell>{lines.orderDate}</Cell>
</Row>
)}
<Row id="advance-payment-order-total">
<Cell>Order total</Cell>
<Cell>{lines.orderTotal}</Cell>
</Row>
{lines.previous[0].number && (
<Row id="advance-payment-previous-1">
<Cell>Previously requested ({lines.previous[0].number})</Cell>
<Cell>{lines.previous[0].amount}</Cell>
</Row>
)}
{lines.previous[1].number && (
<Row id="advance-payment-previous-2">
<Cell>Previously requested ({lines.previous[1].number})</Cell>
<Cell>{lines.previous[1].amount}</Cell>
</Row>
)}
{lines.previous[2].number && (
<Row id="advance-payment-previous-3">
<Cell>Previously requested ({lines.previous[2].number})</Cell>
<Cell>{lines.previous[2].amount}</Cell>
</Row>
)}
{lines.previous[3].number && (
<Row id="advance-payment-previous-4">
<Cell>Previously requested ({lines.previous[3].number})</Cell>
<Cell>{lines.previous[3].amount}</Cell>
</Row>
)}
{lines.previous[4].number && (
<Row id="advance-payment-previous-5">
<Cell>Previously requested ({lines.previous[4].number})</Cell>
<Cell>{lines.previous[4].amount}</Cell>
</Row>
)}
{lines.previous[5].number && (
<Row id="advance-payment-previous-6">
<Cell>Previously requested ({lines.previous[5].number})</Cell>
<Cell>{lines.previous[5].amount}</Cell>
</Row>
)}
{lines.previous[6].number && (
<Row id="advance-payment-previous-7">
<Cell>Previously requested ({lines.previous[6].number})</Cell>
<Cell>{lines.previous[6].amount}</Cell>
</Row>
)}
{lines.previous[7].number && (
<Row id="advance-payment-previous-8">
<Cell>Previously requested ({lines.previous[7].number})</Cell>
<Cell>{lines.previous[7].amount}</Cell>
</Row>
)}
<Row id="advance-payment-deposit">
<Cell>{lines.depositLabel}</Cell>
<Cell>{lines.deposit}</Cell>
</Row>
<Row id="advance-payment-left">
<Cell>Left to invoice</Cell>
<Cell>{lines.leftToInvoice}</Cell>
</Row>
{lines.paymentDate && (
<Row id="advance-payment-payment-date">
<Cell>{lines.paymentDateLabel}</Cell>
<Cell>{lines.paymentDate}</Cell>
</Row>
)}
</Table>
{lines.vatApplies && (
<Table
id="advance-payment-vat"
columns={[{ width: "auto" }, { width: 34, align: "right" }, { width: 34, align: "right" }, {
width: 34,
align: "right",
}]}
>
<Row header>
<Cell>Rate</Cell>
<Cell>Net</Cell>
<Cell>VAT</Cell>
<Cell>Gross</Cell>
</Row>
{lines.bands[0].label && (
<Row id="advance-payment-vat-band-1">
<Cell>{lines.bands[0].label}</Cell>
<Cell>{lines.bands[0].net}</Cell>
<Cell>{lines.bands[0].vat}</Cell>
<Cell>{lines.bands[0].gross}</Cell>
</Row>
)}
{lines.bands[1].label && (
<Row id="advance-payment-vat-band-2">
<Cell>{lines.bands[1].label}</Cell>
<Cell>{lines.bands[1].net}</Cell>
<Cell>{lines.bands[1].vat}</Cell>
<Cell>{lines.bands[1].gross}</Cell>
</Row>
)}
{lines.bands[2].label && (
<Row id="advance-payment-vat-band-3">
<Cell>{lines.bands[2].label}</Cell>
<Cell>{lines.bands[2].net}</Cell>
<Cell>{lines.bands[2].vat}</Cell>
<Cell>{lines.bands[2].gross}</Cell>
</Row>
)}
{lines.bands[3].label && (
<Row id="advance-payment-vat-band-4">
<Cell>{lines.bands[3].label}</Cell>
<Cell>{lines.bands[3].net}</Cell>
<Cell>{lines.bands[3].vat}</Cell>
<Cell>{lines.bands[3].gross}</Cell>
</Row>
)}
<Row id="advance-payment-vat-total">
<Cell>Total</Cell>
<Cell>{lines.netTotal}</Cell>
<Cell>{lines.vatTotal}</Cell>
<Cell>{lines.deposit}</Cell>
</Row>
</Table>
)}
</>
); arrangements/advance-payment-invoice/stacked.arrangement.tsx import { Paragraph, type Yield } from "docxcelerate/template";
import type { AdvancePaymentInvoiceLines } from "./lines.ts";
/**
* One labelled line under another, down the text column. For a narrow column,
* where four figures side by side would not fit.
*/
export const stacked = (lines: AdvancePaymentInvoiceLines): Yield => (
<>
<Paragraph id="advance-payment-order-reference">Order reference: {lines.orderReference}</Paragraph>
{lines.orderDate && <Paragraph id="advance-payment-order-date">Order date: {lines.orderDate}</Paragraph>}
<Paragraph id="advance-payment-order-total">Order total: {lines.orderTotal}</Paragraph>
{lines.previous[0].number && (
<Paragraph id="advance-payment-previous-1">
Previously requested ({lines.previous[0].number}): {lines.previous[0].amount}
</Paragraph>
)}
{lines.previous[1].number && (
<Paragraph id="advance-payment-previous-2">
Previously requested ({lines.previous[1].number}): {lines.previous[1].amount}
</Paragraph>
)}
{lines.previous[2].number && (
<Paragraph id="advance-payment-previous-3">
Previously requested ({lines.previous[2].number}): {lines.previous[2].amount}
</Paragraph>
)}
{lines.previous[3].number && (
<Paragraph id="advance-payment-previous-4">
Previously requested ({lines.previous[3].number}): {lines.previous[3].amount}
</Paragraph>
)}
{lines.previous[4].number && (
<Paragraph id="advance-payment-previous-5">
Previously requested ({lines.previous[4].number}): {lines.previous[4].amount}
</Paragraph>
)}
{lines.previous[5].number && (
<Paragraph id="advance-payment-previous-6">
Previously requested ({lines.previous[5].number}): {lines.previous[5].amount}
</Paragraph>
)}
{lines.previous[6].number && (
<Paragraph id="advance-payment-previous-7">
Previously requested ({lines.previous[6].number}): {lines.previous[6].amount}
</Paragraph>
)}
{lines.previous[7].number && (
<Paragraph id="advance-payment-previous-8">
Previously requested ({lines.previous[7].number}): {lines.previous[7].amount}
</Paragraph>
)}
<Paragraph id="advance-payment-deposit">{lines.depositLabel}: {lines.deposit}</Paragraph>
<Paragraph id="advance-payment-left">Left to invoice: {lines.leftToInvoice}</Paragraph>
{lines.paymentDate && (
<Paragraph id="advance-payment-payment-date">{lines.paymentDateLabel}: {lines.paymentDate}</Paragraph>
)}
{lines.vatApplies && (
<>
{lines.bands[0].label && (
<Paragraph id="advance-payment-vat-band-1">
VAT at {lines.bands[0].label}: {lines.bands[0].vat} on a net {lines.bands[0].net} (gross{" "}
{lines.bands[0].gross}).
</Paragraph>
)}
{lines.bands[1].label && (
<Paragraph id="advance-payment-vat-band-2">
VAT at {lines.bands[1].label}: {lines.bands[1].vat} on a net {lines.bands[1].net} (gross{" "}
{lines.bands[1].gross}).
</Paragraph>
)}
{lines.bands[2].label && (
<Paragraph id="advance-payment-vat-band-3">
VAT at {lines.bands[2].label}: {lines.bands[2].vat} on a net {lines.bands[2].net} (gross{" "}
{lines.bands[2].gross}).
</Paragraph>
)}
{lines.bands[3].label && (
<Paragraph id="advance-payment-vat-band-4">
VAT at {lines.bands[3].label}: {lines.bands[3].vat} on a net {lines.bands[3].net} (gross{" "}
{lines.bands[3].gross}).
</Paragraph>
)}
<Paragraph id="advance-payment-vat-total">
VAT on this deposit: {lines.vatTotal} on a net {lines.netTotal}.
</Paragraph>
</>
)}
</>
);