Voucher and coupon redemptions
BodyThe totals under an invoice's lines, with every voucher, coupon and gift card placed where its tax treatment puts it. A retailer's coupon, and in the US a free promotional card, reduces the taxable amount: it is spread across the VAT or sales-tax bands of the lines it applies to by largest remainder, so the parts add up to the coupon exactly, and it never takes a line below zero. A single-purpose voucher had its VAT accounted for when it was sold, so the part it covers is shown as paid by voucher and left out of the VAT analysis rather than taxed twice. A multi-purpose voucher and a gift card are payments: tax is charged on the full price and they reduce only the amount due. A US manufacturer's coupon leaves the pre-coupon price taxable unless the seller says its state treats it as a discount. Excess value on a voucher or card is printed as a remaining balance, never as change or a negative amount due. All of it is one deriver.
npx dxcl add voucher-redemption-lines sale.jurisdiction Vorschaudaten
das JSON, mit dem diese Vorschau gebaut wurde{
"sale": {
"currency": "GBP",
"jurisdiction": "UK",
"lines": [
{
"key": "spa-weekend",
"netMinor": 124999,
"ratePercent": 20
},
{
"key": "treatment-package",
"netMinor": 84950,
"ratePercent": 20
},
{
"key": "childrens-car-seat",
"netMinor": 18999,
"ratePercent": 5
},
{
"key": "printed-guidebooks",
"netMinor": 4500,
"ratePercent": 0
}
],
"redemptions": [
{
"kind": "discount-coupon",
"amountMinor": 25000,
"code": "LOYALTY-ANNIVERSARY-25-OFF-2026",
"appliesToLineKeys": [
"spa-weekend",
"treatment-package",
"childrens-car-seat"
]
},
{
"kind": "spv",
"amountMinor": 60000,
"appliesToLineKeys": [
"spa-weekend"
],
"spvRatePercent": 20,
"code": "SPA-GIFT-VOUCHER-0004817-UK"
},
{
"kind": "mpv",
"amountMinor": 200000,
"code": "HIGH-STREET-GIFT-CARD-9921-3348-7710"
}
]
}
} {
"sale": {
"currency": "GBP",
"jurisdiction": "EU",
"lines": [
{
"key": "spa-weekend",
"netMinor": 124999,
"ratePercent": 20
},
{
"key": "treatment-package",
"netMinor": 84950,
"ratePercent": 20
},
{
"key": "childrens-car-seat",
"netMinor": 18999,
"ratePercent": 5
},
{
"key": "printed-guidebooks",
"netMinor": 4500,
"ratePercent": 0
}
],
"redemptions": [
{
"kind": "discount-coupon",
"amountMinor": 25000,
"code": "LOYALTY-ANNIVERSARY-25-OFF-2026",
"appliesToLineKeys": [
"spa-weekend",
"treatment-package",
"childrens-car-seat"
]
},
{
"kind": "spv",
"amountMinor": 60000,
"appliesToLineKeys": [
"spa-weekend"
],
"spvRatePercent": 20,
"code": "SPA-GIFT-VOUCHER-0004817-UK"
},
{
"kind": "mpv",
"amountMinor": 200000,
"code": "HIGH-STREET-GIFT-CARD-9921-3348-7710"
}
]
}
} Aufgelöste Nodes
was ein Renderer erhält — 3 Nodesvoucher-redemption-lines table voucher-redemption-note-spv paragraph · static VAT on the part paid by voucher was accounted for when the voucher was sold, so it is not charged again here. voucher-redemption-note-mpv paragraph · static VAT is charged on the full price. A voucher that can be spent across different VAT rates is a form of payment, so it reduces the amount to pay, not the VAT. voucher-redemption-lines table voucher-redemption-note-spv paragraph · static VAT on the part paid by voucher was accounted for when the voucher was sold, so it is not charged again here. voucher-redemption-note-mpv paragraph · static VAT is charged on the full price. A voucher that can be spent across different VAT rates is a form of payment, so it reduces the amount to pay, not the VAT. Die Dateien
was die Installation schreibt; die gewählte Datei ist die Komponentenodes/voucher-redemption-lines.node.tsx import { Cell, type Nodes, Paragraph, Row, Table, useDeriver, useState } from "docxcelerate/template";
import voucherRedemptionLines from "../derivers/voucher-redemption-lines.deriver.ts";
/**
* The totals block under an invoice's or receipt's line items, with every
* voucher, coupon and gift card where its tax treatment requires, so the VAT or
* sales tax shown is the tax actually due. No heading, so it can sit directly
* under the line table.
*
* Decisions already made for you:
*
* - A voucher is not always a discount. A retailer's coupon, and in the US a
* free promotional card, reduce the taxable amount and print above the tax. A
* multi-purpose voucher, a gift card and (unless the seller's state treats it
* as a discount) a US manufacturer's coupon are payments: tax is charged on
* the full price and they print below the total.
* - A single-purpose voucher had its VAT accounted for when it was sold. The
* part it covers is shown as paid by voucher and left out of the VAT
* analysis, so VAT is not charged twice.
* - A coupon is spread across the VAT bands of the lines it applies to by
* largest remainder, so the parts add up to the coupon exactly and no line
* goes below zero.
* - Value left on a voucher or card is a remaining balance. It is never change
* and the amount due is never negative.
*
* The node computes nothing. One deriver validates, allocates, taxes, sorts,
* caps and formats, because all of that is arithmetic or filtering on request
* data and publishing refuses it. The node reads the result and branches on it.
*
* Each group is four fixed 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 the deriver's rows would publish and then resolve to no
* rows. Every test is written inline, never hoisted into a `const`.
*
* A publish build emits 15 branches against the default `branchLimit` of 32:
* 12 slot rows and 3 notes.
*
* Installed by `dxcl add voucher-redemption-lines`.
*/
/** What this component reads. Add these fields to your document data type. */
export interface VoucherRedemptionData {
sale: {
/**
* ISO 4217 code every amount is in: `"GBP"`, `"EUR"`, `"USD"`. It also sets
* how many minor units make one major unit. Required: the deriver throws
* when it is missing or not a code `Intl` knows.
*/
currency: string;
/**
* Whose rules apply. `UK` and `EU` share the VAT voucher rules (Directive
* 2016/1065; VATA 1994 Sch 10A) and print "VAT". `US` prints "Sales tax".
* It also decides which redemption kinds are allowed. Required: anything
* else throws.
*/
jurisdiction: "UK" | "EU" | "US";
/**
* US only. True when the seller's state treats a manufacturer's coupon as
* a discount that reduces the taxable price (Texas, for one). Missing or
* false means the majority rule: sales tax is charged on the pre-coupon
* price, and the coupon reduces only the amount due. Ignored outside the US.
*/
manufacturerCouponsReduceBase?: boolean;
/**
* The sale's lines, used only for their amounts and rates. This component
* does not print them; the line-item table is a separate component.
* Required: a missing or empty list throws.
*/
lines: Array<{
/**
* Identifies the line for `appliesToLineKeys`. It is never printed.
* Required, non-empty and unique: a duplicate throws.
*/
key: string;
/**
* The line's price before tax, in integer minor units (12999 for 129.99),
* after any line-level discount. Required: throws unless it is an integer
* from 0 to 90,000,000,000. Zero is allowed: the line takes no part in any
* allocation.
*/
netMinor: number;
/**
* The VAT rate (UK/EU) or the combined sales-tax rate (US) for this line,
* as a percentage: `20`, `5.5`, `8.875`. `0` is a zero-rated or untaxed
* line. Lines that share a rate share a band. Required: throws unless it
* is a finite number from 0 to 100 with no more than three decimal places.
*/
ratePercent: number;
}>;
/**
* Every voucher, coupon or card used on the sale, in the order they were
* presented. That order breaks ties within a group, but it does not decide
* the group: discounts always come before tax and payments after.
* Missing or empty prints the totals with no redemption rows.
*/
redemptions?: Array<{
/**
* What it is. UK/EU: `spv` (single-purpose voucher: place of supply and
* VAT rate known when it was sold), `mpv` (multi-purpose voucher),
* `discount-coupon` (retailer's money-off coupon). US: `retailer-coupon`,
* `manufacturer-coupon` (the manufacturer reimburses the seller),
* `gift-card` (bought for money), `promo-card` (a card given away free).
* Required: a kind from the other jurisdiction, or an unknown kind, throws.
* A gift card in the UK is an `mpv`.
*/
kind:
| "spv"
| "mpv"
| "discount-coupon"
| "retailer-coupon"
| "manufacturer-coupon"
| "gift-card"
| "promo-card";
/**
* Face value in integer minor units. For coupons and promo cards it is on
* the same tax-exclusive basis as `netMinor`. For `spv`, `mpv` and
* `gift-card` it is money the customer already paid, so it is set against
* the tax-inclusive total. Required: throws unless it is a non-negative
* integer up to 90,000,000,000. `0` is skipped and prints no row.
*/
amountMinor: number;
/**
* The lines it may be used against, by `key`. Missing means every line.
* Read for coupons, promo cards and `spv`. Ignored for `mpv` and
* `gift-card`, which pay the whole total. Throws when it is an empty array
* or names a key that is not on the sale.
*/
appliesToLineKeys?: string[];
/**
* The code printed after the description: "Coupon SAVE10". Missing prints
* the description alone.
*/
code?: string;
/**
* `spv` only: the VAT rate fixed when the voucher was sold. When given,
* every line the voucher applies to must be at this rate. When missing,
* those lines must all share one rate, and that rate is used. Either
* mismatch throws, because a voucher that spans rates is multi-purpose by
* definition. Ignored on other kinds.
*/
spvRatePercent?: number;
}>;
};
}
/**
* Prints the subtotal, the discounts, the tax per band, the total, the payments
* and the amount due, then a note for each treatment that was used.
*/
export const VoucherRedemptionLines: Nodes = async () => {
const [sale] = useState((data: VoucherRedemptionData) => data.sale);
const r = await useDeriver(voucherRedemptionLines, [sale]);
return (
<>
<Table id="voucher-redemption-lines" columns={[{ width: "auto" }, { width: 35, align: "right" }]}>
<Row id="voucher-redemption-subtotal">
<Cell>Subtotal</Cell>
<Cell>{r.subtotal}</Cell>
</Row>
{r.discounts[0].description && (
<Row id="voucher-redemption-discount-1">
<Cell>{r.discounts[0].description}</Cell>
<Cell>{r.discounts[0].amount}</Cell>
</Row>
)}
{r.discounts[1].description && (
<Row id="voucher-redemption-discount-2">
<Cell>{r.discounts[1].description}</Cell>
<Cell>{r.discounts[1].amount}</Cell>
</Row>
)}
{r.discounts[2].description && (
<Row id="voucher-redemption-discount-3">
<Cell>{r.discounts[2].description}</Cell>
<Cell>{r.discounts[2].amount}</Cell>
</Row>
)}
{r.discounts[3].description && (
<Row id="voucher-redemption-discount-4">
<Cell>{r.discounts[3].description}</Cell>
<Cell>{r.discounts[3].amount}</Cell>
</Row>
)}
{r.bands[0].description && (
<Row id="voucher-redemption-tax-1">
<Cell>{r.bands[0].description}</Cell>
<Cell>{r.bands[0].amount}</Cell>
</Row>
)}
{r.bands[1].description && (
<Row id="voucher-redemption-tax-2">
<Cell>{r.bands[1].description}</Cell>
<Cell>{r.bands[1].amount}</Cell>
</Row>
)}
{r.bands[2].description && (
<Row id="voucher-redemption-tax-3">
<Cell>{r.bands[2].description}</Cell>
<Cell>{r.bands[2].amount}</Cell>
</Row>
)}
{r.bands[3].description && (
<Row id="voucher-redemption-tax-4">
<Cell>{r.bands[3].description}</Cell>
<Cell>{r.bands[3].amount}</Cell>
</Row>
)}
<Row id="voucher-redemption-total">
<Cell>Total</Cell>
<Cell>{r.total}</Cell>
</Row>
{r.tenders[0].description && (
<Row id="voucher-redemption-tender-1">
<Cell>{r.tenders[0].description}</Cell>
<Cell>{r.tenders[0].amount}</Cell>
</Row>
)}
{r.tenders[1].description && (
<Row id="voucher-redemption-tender-2">
<Cell>{r.tenders[1].description}</Cell>
<Cell>{r.tenders[1].amount}</Cell>
</Row>
)}
{r.tenders[2].description && (
<Row id="voucher-redemption-tender-3">
<Cell>{r.tenders[2].description}</Cell>
<Cell>{r.tenders[2].amount}</Cell>
</Row>
)}
{r.tenders[3].description && (
<Row id="voucher-redemption-tender-4">
<Cell>{r.tenders[3].description}</Cell>
<Cell>{r.tenders[3].amount}</Cell>
</Row>
)}
<Row id="voucher-redemption-amount-due">
<Cell>Amount due</Cell>
<Cell>{r.amountDue}</Cell>
</Row>
</Table>
{r.spvNote && (
<Paragraph id="voucher-redemption-note-spv">
VAT on the part paid by voucher was accounted for when the voucher was sold, so it is not charged again here.
</Paragraph>
)}
{r.mpvNote && (
<Paragraph id="voucher-redemption-note-mpv">
VAT is charged on the full price. A voucher that can be spent across different VAT rates is a form of payment,
so it reduces the amount to pay, not the VAT.
</Paragraph>
)}
{r.manufacturerNote && (
<Paragraph id="voucher-redemption-note-manufacturer">
Sales tax is charged on the price before the manufacturer's coupon, because the manufacturer reimburses its
value to us.
</Paragraph>
)}
</>
);
}; derivers/voucher-redemption-lines.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Places every voucher, coupon and gift card where its tax treatment puts it
* and works out the tax that is actually due. Installed by
* `dxcl add voucher-redemption-lines`.
*
* It is self-contained on purpose: it travels to the engine as source text, so
* a module-level constant or helper would be a ReferenceError there. Every
* helper is declared inside `run`.
*/
export default deriver({
name: "voucherRedemptionLines",
run: (sale: unknown) => {
const s = sale as any;
const MAX = 90_000_000_000;
// Exact integer rounding, half away from zero. BigInt because a coupon times a
// line can pass 2^53 well before either is unreasonable.
const roundHalfAway = (numerator: number, denominator: number): number => {
const n = BigInt(numerator);
const d = BigInt(denominator);
const abs = n < BigInt(0) ? -n : n;
const q = (BigInt(2) * abs + d) / (BigInt(2) * d);
return Number(n < BigInt(0) ? -q : q);
};
// Largest remainder: floors first, the leftover units one each to the largest
// remainders, ties to the earlier line. A <= sum, so no share exceeds its line.
const allocate = (amount: number, remaining: number[]): number[] => {
const total = remaining.reduce((a, b) => a + b, 0);
if (amount === 0 || total === 0) return remaining.map(() => 0);
const A = BigInt(amount);
const N = BigInt(total);
const shares = remaining.map((r) => (A * BigInt(r)) / N);
const rems = remaining.map((r) => (A * BigInt(r)) % N);
let left = Number(A - shares.reduce((a, b) => a + b, BigInt(0)));
const order = remaining.map((_, i) => i).sort((a, b) => (rems[a] === rems[b] ? a - b : rems[a] > rems[b] ? -1 : 1));
const out = shares.map((x) => Number(x));
for (const i of order) {
if (left <= 0) break;
out[i] += 1;
left -= 1;
}
return out;
};
const minorOf = (value: unknown, field: string): number => {
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > MAX) {
throw new Error(field + " must be an integer of minor units from 0 to " + MAX);
}
return value;
};
const rateOf = (value: unknown, field: string): number => {
if (
typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 100 ||
Math.abs(value * 1000 - Math.round(value * 1000)) > 1e-6
) {
throw new Error(field + " must be a number from 0 to 100 with at most three decimal places");
}
return Math.round(value * 1000);
};
const currency = s?.currency;
const jurisdiction = s?.jurisdiction;
if (jurisdiction !== "UK" && jurisdiction !== "EU" && jurisdiction !== "US") {
throw new Error('sale.jurisdiction must be "UK", "EU" or "US"');
}
const us = jurisdiction === "US";
let money: Intl.NumberFormat;
try {
if (typeof currency !== "string" || !/^[A-Za-z]{3}$/.test(currency)) throw new Error();
if (!(Intl as any).supportedValuesOf("currency").includes(currency.toUpperCase())) throw new Error();
money = new Intl.NumberFormat(us ? "en-US" : "en-GB", { style: "currency", currency });
} catch {
throw new Error("sale.currency must be an ISO 4217 code");
}
const exponent = money.resolvedOptions().maximumFractionDigits as number;
const fmt = (minor: number) => money.format(minor / 10 ** exponent);
const rateLabel = (milli: number) => new Intl.NumberFormat("en-GB", { maximumFractionDigits: 3 }).format(milli / 1000);
const taxName = us ? "Sales tax" : "VAT";
if (!Array.isArray(s.lines) || s.lines.length === 0) throw new Error("sale.lines must be a non-empty array");
const seen = new Set<string>();
const lines = s.lines.map((l: any, i: number) => {
const f = "sale.lines[" + i + "]";
if (typeof l?.key !== "string" || l.key === "") throw new Error(f + ".key must be a non-empty string");
if (seen.has(l.key)) throw new Error(f + ".key is a duplicate of an earlier line: " + l.key);
seen.add(l.key);
return {
key: l.key as string,
net: minorOf(l.netMinor, f + ".netMinor"),
rate: rateOf(l.ratePercent, f + ".ratePercent"),
};
});
const remaining: number[] = lines.map((l: any) => l.net);
const allowed = us
? ["retailer-coupon", "manufacturer-coupon", "gift-card", "promo-card"]
: ["spv", "mpv", "discount-coupon"];
const rawRedemptions = s.redemptions === undefined || s.redemptions === null ? [] : s.redemptions;
if (!Array.isArray(rawRedemptions)) throw new Error("sale.redemptions must be an array");
const reduceBase = us && s.manufacturerCouponsReduceBase === true;
const reds = rawRedemptions.map((r: any, i: number) => {
const f = "sale.redemptions[" + i + "]";
if (!allowed.includes(r?.kind)) {
throw new Error(f + ".kind must be one of " + allowed.join(", ") + " for " + jurisdiction);
}
const amount = minorOf(r.amountMinor, f + ".amountMinor");
let eligible: number[] = lines.map((_: any, k: number) => k);
if (r.appliesToLineKeys !== undefined) {
if (!Array.isArray(r.appliesToLineKeys) || r.appliesToLineKeys.length === 0) {
throw new Error(f + ".appliesToLineKeys must be a non-empty array of line keys");
}
eligible = r.appliesToLineKeys.map((key: unknown, k: number) => {
const at = lines.findIndex((l: any) => l.key === key);
if (at < 0) throw new Error(f + ".appliesToLineKeys[" + k + "] is not a line key on the sale: " + String(key));
return at;
});
const dup = eligible.findIndex((at, k) => eligible.indexOf(at) !== k);
if (dup >= 0) throw new Error(f + ".appliesToLineKeys[" + dup + "] is a duplicate");
// Ties in the allocation go to the earlier sale line, not the earlier listed key.
eligible.sort((a, b) => a - b);
}
let rate = 0;
if (r.kind === "spv") {
const rates = [...new Set(eligible.map((k) => lines[k].rate))];
if (r.spvRatePercent !== undefined) {
rate = rateOf(r.spvRatePercent, f + ".spvRatePercent");
if (rates.some((x) => x !== rate)) {
throw new Error(f + ".spvRatePercent differs from the rate of a line the voucher applies to");
}
} else {
if (rates.length !== 1) {
throw new Error(f + " is a single-purpose voucher over lines at different rates; it would be multi-purpose");
}
rate = rates[0];
}
}
const code = typeof r.code === "string" && r.code !== "" ? " " + r.code : "";
return { kind: r.kind as string, amount, eligible, rate, code };
});
const subtotalMinor = lines.reduce((a: number, l: any) => a + l.net, 0);
// Discounts: before tax, each against what earlier ones left.
const discounts: Array<{ description: string; amount: string }> = [];
for (const r of reds) {
const isDiscount = r.kind === "discount-coupon" || r.kind === "retailer-coupon" || r.kind === "promo-card" ||
(r.kind === "manufacturer-coupon" && reduceBase);
if (!isDiscount || r.amount === 0) continue;
const room = r.eligible.reduce((a: number, k: number) => a + remaining[k], 0);
const applied = Math.min(r.amount, room);
const shares = allocate(applied, r.eligible.map((k: number) => remaining[k]));
r.eligible.forEach((k: number, j: number) => (remaining[k] -= shares[j]));
if (applied === 0) continue;
const name = r.kind === "promo-card"
? "Promotional card"
: r.kind === "manufacturer-coupon"
? "Manufacturer coupon"
: "Coupon";
const suffix = applied === r.amount
? ""
: r.kind === "promo-card"
? " (remaining balance " + fmt(r.amount - applied) + ")"
: " (applied " + fmt(applied) + " of " + fmt(r.amount) + ")";
discounts.push({ description: name + r.code + suffix, amount: fmt(-applied) });
}
if (discounts.length > 4) {
throw new Error("voucherRedemptionLines: " + discounts.length + " discount rows; this component prints at most 4");
}
// What a manufacturer coupon on the majority rule may still be set against.
const afterDiscounts = remaining.slice();
// Single-purpose vouchers: their VAT was accounted for at sale, so the part
// they cover leaves the taxable amount and comes back as a payment.
const spvTenders: Array<{ description: string; minor: number }> = [];
for (const r of reds) {
if (r.kind !== "spv" || r.amount === 0) continue;
const E = r.eligible.reduce((a: number, k: number) => a + remaining[k], 0);
const Eg = E + roundHalfAway(E * r.rate, 100000);
let coveredNet: number;
let coveredGross: number;
let balance = 0;
if (r.amount >= Eg) {
coveredNet = E;
coveredGross = Eg;
balance = r.amount - Eg;
} else {
coveredNet = Math.min(E, roundHalfAway(r.amount * 100000, 100000 + r.rate));
coveredGross = r.amount;
}
const shares = allocate(coveredNet, r.eligible.map((k: number) => remaining[k]));
r.eligible.forEach((k: number, j: number) => (remaining[k] -= shares[j]));
if (coveredGross === 0) continue;
spvTenders.push({
description: "Paid by voucher" + r.code + (balance > 0 ? " (remaining balance " + fmt(balance) + ")" : ""),
minor: coveredGross,
});
}
// Tax per band, rounded once per band, highest rate first.
const byRate = new Map<number, number>();
lines.forEach((l: any, k: number) => byRate.set(l.rate, (byRate.get(l.rate) ?? 0) + remaining[k]));
const bandRows = [...byRate.entries()].filter(([, taxable]) => taxable > 0).sort((a, b) => b[0] - a[0])
.map(([rate, taxable]) => ({ rate, taxable, tax: roundHalfAway(taxable * rate, 100000) }));
if (bandRows.length > 4) {
throw new Error("voucherRedemptionLines: " + bandRows.length + " tax bands; this component prints at most 4");
}
const bands = bandRows.map((b) => ({
description: taxName + " at " + rateLabel(b.rate) + "% on " + fmt(b.taxable),
amount: fmt(b.tax),
}));
const taxMinor = bandRows.reduce((a, b) => a + b.tax, 0);
const spvPaid = spvTenders.reduce((a, t) => a + t.minor, 0);
const totalMinor = bandRows.reduce((a, b) => a + b.taxable, 0) + taxMinor + spvPaid;
// Payments, after the total. Each is capped at what is still due.
let due = totalMinor;
const tenders: Array<{ description: string; amount: string }> = [];
let mpvNote = false;
let manufacturerNote = false;
for (const t of spvTenders) {
due -= t.minor;
tenders.push({ description: t.description, amount: fmt(-t.minor) });
}
for (const r of reds) {
const pays = r.kind === "mpv" || r.kind === "gift-card" || (r.kind === "manufacturer-coupon" && !reduceBase);
if (!pays || r.amount === 0) continue;
if (r.kind === "manufacturer-coupon") {
const room = r.eligible.reduce((a: number, k: number) => a + afterDiscounts[k], 0);
const a = Math.min(r.amount, room, due);
if (a === 0) continue;
due -= a;
manufacturerNote = true;
tenders.push({
description: "Manufacturer coupon" + r.code + (a < r.amount ? " (applied " + fmt(a) + " of " + fmt(r.amount) + ")" : ""),
amount: fmt(-a),
});
continue;
}
const a = Math.min(r.amount, due);
if (a === 0) continue;
due -= a;
if (r.kind === "mpv") mpvNote = true;
tenders.push({
description: (r.kind === "mpv" ? "Paid by voucher" : "Paid by gift card") + r.code +
(r.amount > a ? " (remaining balance " + fmt(r.amount - a) + ")" : ""),
amount: fmt(-a),
});
}
if (tenders.length > 4) {
throw new Error("voucherRedemptionLines: " + tenders.length + " payment rows; this component prints at most 4");
}
const pad = (rows: Array<{ description: string; amount: string }>) => {
const out = rows.slice();
while (out.length < 4) out.push({ description: "", amount: "" });
return out;
};
return {
subtotal: fmt(subtotalMinor),
discounts: pad(discounts),
bands: pad(bands),
total: fmt(totalMinor),
tenders: pad(tenders),
amountDue: fmt(due),
spvNote: spvTenders.length > 0,
mpvNote,
manufacturerNote,
subtotalMinor,
taxMinor,
totalMinor,
amountDueMinor: due,
};
},
});