Credit note totals
BodyCredits are worked from the original invoice, never from today's settings. Each credited line keeps the VAT rate the invoice charged, and a foreign-currency invoice keeps its sterling exchange rate, so a rate change since cannot credit the wrong VAT. A full cancellation copies the original band figures exactly rather than recomputing them, so the two documents net to zero. A partial return credits quantity times the original unit price, with VAT rounded per band. A goodwill amount is spread across the original VAT bands pro rata by largest remainder, so no band is credited more VAT than it charged. Earlier credit notes are subtracted first, and a credit larger than what remains in any band fails the document. Amounts print positive under a Credit heading, as Peppol 381 expects, never as negative invoice lines.
npx dxcl add credit-note-totals creditNote.credit.mode Данные предпросмотра
JSON, на котором построен этот предпросмотр{
"creditNote": {
"original": {
"number": "SI-2026-09-004817/REV-2",
"issueDate": "2026-09-30",
"currency": "EUR",
"fxToGBP": 0.8567,
"vatGBP": 223790.6,
"bands": [
{
"vatRate": 20,
"net": 1283650,
"vat": 256730
},
{
"vatRate": 5,
"net": 89880,
"vat": 4494
},
{
"vatRate": 0,
"net": 18500,
"vat": 0
}
],
"lines": [
{
"id": "L1",
"description": "Annual enterprise licence, Docxcelerate Document Engine, 2,500 seats, unlimited recipients",
"qty": 2500,
"unitNet": 412.75,
"vatRate": 20
},
{
"id": "L2",
"description": "Implementation and data migration services, phase two (statement and arrears templates)",
"qty": 186.5,
"unitNet": 1350,
"vatRate": 20
},
{
"id": "L3",
"description": "Printed welcome packs on recycled board, posted to every registered recipient",
"qty": 48000,
"unitNet": 1.8725,
"vatRate": 5
},
{
"id": "L4",
"description": "Accessibility audit of published templates by an accredited third party",
"qty": 1,
"unitNet": 18500,
"vatRate": 0
}
]
},
"previousCredits": [
{
"bands": [
{
"vatRate": 20,
"net": 41275,
"vat": 8255
}
]
}
],
"credit": {
"mode": "full",
"lines": [
{
"id": "L1",
"qty": 300
},
{
"id": "L3",
"qty": 12000
},
{
"id": "L2",
"qty": 12.5
}
]
}
}
} {
"creditNote": {
"original": {
"number": "SI-2026-09-004817/REV-2",
"issueDate": "2026-09-30",
"currency": "EUR",
"fxToGBP": 0.8567,
"vatGBP": 223790.6,
"bands": [
{
"vatRate": 20,
"net": 1283650,
"vat": 256730
},
{
"vatRate": 5,
"net": 89880,
"vat": 4494
},
{
"vatRate": 0,
"net": 18500,
"vat": 0
}
],
"lines": [
{
"id": "L1",
"description": "Annual enterprise licence, Docxcelerate Document Engine, 2,500 seats, unlimited recipients",
"qty": 2500,
"unitNet": 412.75,
"vatRate": 20
},
{
"id": "L2",
"description": "Implementation and data migration services, phase two (statement and arrears templates)",
"qty": 186.5,
"unitNet": 1350,
"vatRate": 20
},
{
"id": "L3",
"description": "Printed welcome packs on recycled board, posted to every registered recipient",
"qty": 48000,
"unitNet": 1.8725,
"vatRate": 5
},
{
"id": "L4",
"description": "Accessibility audit of published templates by an accredited third party",
"qty": 1,
"unitNet": 18500,
"vatRate": 0
}
]
},
"previousCredits": [
{
"bands": [
{
"vatRate": 20,
"net": 41275,
"vat": 8255
}
]
}
],
"credit": {
"mode": "lines",
"lines": [
{
"id": "L1",
"qty": 300
},
{
"id": "L3",
"qty": 12000
},
{
"id": "L2",
"qty": 12.5
}
]
}
}
} Разрешённые узлы
что получает рендерер — узлов: 1credit-note-totals section credit-note-totals section Файлы
что записывает установка; выбранный файл и есть компонентnodes/credit-note-totals.node.tsx import { Cell, Paragraph, Row, Section, type Section as SectionComponent, Table, useDeriver, useState } from "docxcelerate/template";
import creditNoteTotals from "../derivers/credit-note-totals.deriver.ts";
/**
* What a credit note credits, by VAT band, worked from the invoice it undoes.
*
* Credits are worked from the original invoice, never from today's settings.
* Each credited line keeps the VAT rate the invoice charged, and a
* foreign-currency invoice keeps its sterling exchange rate, so a rate change
* since cannot credit the wrong VAT. There is deliberately no input for a
* current rate.
*
* A full cancellation copies the original band figures exactly rather than
* recomputing them, so the two documents net to zero with no penny residue.
* A partial return credits quantity times the original unit price, each line
* rounded once, with VAT rounded per band the way the original was. A goodwill
* amount is spread across the original VAT bands pro rata by largest
* remainder, so the figures add up to the penny and no band is credited more
* VAT than it charged.
*
* Earlier credit notes are subtracted first, and a credit larger than what
* remains in any band fails the document, naming the band, rather than
* issuing a credit note for money that was never charged.
*
* Amounts print positive under a "Credit" heading, never as negative invoice
* lines. That is what Peppol BIS document type 381 expects: the document type
* carries the sign.
*
* All of it is one deriver, because arithmetic on request data throws at
* publish. The node does none: it prints the deriver's strings and loops over
* its rows. The mode is not a branch, it only changes the derived `basis`
* sentence, so four conditionals and two loops are published.
*
* Every line is a figure the reader checks against the original invoice, so
* they stand in right-aligned columns and there is no `arrangement` prop.
*
* Installed by `dxcl add credit-note-totals`, which also installs its deriver.
*/
/** What this component reads. Add these fields to your document data type. */
export interface CreditNoteTotalsData {
creditNote: {
/**
* The invoice being credited, exactly as it was issued. Every rate, price
* and exchange rate is read from here. There is deliberately no field for
* a current rate. Required: missing throws.
*/
original: {
/**
* The original invoice number, printed as given (trimmed). Required:
* missing or blank throws. A credit note must identify what it credits.
*/
number: string;
/**
* The original invoice's date of issue, ISO 8601 (`2026-09-30`). Anything
* after the tenth character is ignored. Printed, formatted en-GB long, in UTC.
* Required: missing, or not starting with YYYY-MM-DD, throws.
*/
issueDate: string;
/**
* ISO 4217 code of the original invoice: "GBP", "EUR", "JPY". The credit
* is in the same currency. The exponent (decimal places) comes from Intl.
* Required: missing or a code Intl rejects throws, naming
* `creditNote.original.currency`.
*/
currency: string;
/**
* Pounds sterling per ONE unit of the invoice currency, as used on the
* original invoice: 0.8567 for EUR. This is NOT the "units per £1" figure
* HMRC publishes (1.1673). Up to 6 decimal places, honoured exactly.
* Given and currency is not GBP: a "VAT credited in sterling" row prints.
* Missing: no sterling row. The invoice did not carry UK VAT.
* Ignored when currency is GBP. Zero, negative or not finite throws.
*/
fxToGBP?: number;
/**
* The total VAT in sterling exactly as printed on the original invoice.
* Read only for a full cancellation with no earlier credits, where it is
* copied rather than recomputed. Missing: computed from `fxToGBP`.
* Ignored when `fxToGBP` is not in play.
*/
vatGBP?: number;
/**
* The original invoice's VAT analysis: one entry per rate, in the order
* that invoice printed them. The credit note prints bands in this order.
* Required and non-empty: missing or empty throws.
*/
bands: Array<{
/**
* VAT rate as a percentage: 20, 5, 12.5, 0. Up to 2 decimal places.
* `null` is exempt or outside the scope of VAT. 0 is zero-rated, a
* different treatment, and prints as "0%". Two bands with the same
* rate throw. `undefined`, negative or not finite throws.
*/
vatRate: number | null;
/**
* Printed instead of the rate for a `null` band: "Exempt", "Outside the
* scope of VAT". Missing on a null band prints "No VAT". Ignored on a
* rated band, which is always labelled "20%".
*/
label?: string;
/**
* The band's net as printed on the original, in major units. No more
* decimals than the currency's exponent: more throws. Negative or not
* finite throws.
*/
net: number;
/**
* The band's VAT as printed on the original, same rules as `net`.
* Non-zero on a `null` band throws.
*/
vat: number;
}>;
/**
* The original invoice's lines. Required only for `credit.mode: "lines"`,
* where missing throws. Ignored otherwise.
*/
lines?: Array<{
/** The line's identifier, unique on the invoice. Duplicates throw. */
id: string;
/** What was supplied, printed on the credited line. Wraps; never truncated. */
description: string;
/**
* How many were invoiced. Up to 4 decimal places. Caps what one credit
* may return of this line. Not finite or ≤ 0 throws.
*/
qty: number;
/**
* Net unit price in major units, as invoiced. Up to 4 decimal places,
* honoured exactly. Negative or not finite throws.
*/
unitNet: number;
/**
* The rate this line was invoiced at. It must equal some
* `bands[].vatRate`; one that does not throws.
*/
vatRate: number | null;
}>;
};
/**
* Credit notes already issued against this invoice, in any order. Each
* one's band figures are subtracted from the original before this credit
* is checked. Missing or empty: nothing has been credited yet.
*/
previousCredits?: Array<{
/**
* The figures that credit note credited, one per rate it touched. A rate
* not on the original throws. Same number rules as `original.bands`.
*/
bands: Array<{ vatRate: number | null; net: number; vat: number }>;
}>;
/** What this credit note credits. Required: missing throws. */
credit: {
/**
* `"full"`: cancels everything still creditable, copying the figures.
* `"lines"`: returns some quantity of named original lines.
* `"amount"`: a lump sum spread across the original bands.
* Anything else throws.
*/
mode: "full" | "lines" | "amount";
/**
* For `"lines"`: what is returned, in the order it should print. Missing
* or empty there throws. Ignored for other modes.
*/
lines?: Array<{
/** An `original.lines[].id`. Unknown throws; the same id twice throws. */
id: string;
/**
* How many are credited. Up to 4 decimal places. ≤ 0, not finite, or
* more than the original line's `qty` throws.
*/
qty: number;
}>;
/**
* For `"amount"`: the VAT-INCLUSIVE sum credited, in major units of the
* invoice currency. No more decimals than the exponent. Missing, ≤ 0, or
* more than the total still creditable (gross) throws. Ignored for
* other modes.
*/
amount?: number;
};
};
}
/**
* Prints what a credit note credits: how it was worked out, the credited lines
* when lines were returned, the VAT analysis when more than one band is
* credited, and the net, VAT and total.
*/
export const CreditNoteTotals: SectionComponent = async () => {
const [note] = useState((d: CreditNoteTotalsData) => d.creditNote);
const totals = await useDeriver(creditNoteTotals, [note]);
return (
<Section id="credit-note-totals" title="Credit">
<Paragraph id="credit-note-totals-basis">{totals.basis}</Paragraph>
<Paragraph id="credit-note-totals-original">{totals.original}</Paragraph>
{totals.previouslyCredited && (
<Paragraph id="credit-note-totals-previous">{totals.previouslyCredited}</Paragraph>
)}
{totals.hasLines && (
<Table
id="credit-note-totals-lines"
columns={[
{ width: "auto" },
{ width: 22, align: "right" },
{ width: 26, align: "right" },
{ width: 18, align: "right" },
{ width: 28, align: "right" },
]}
>
<Row id="credit-note-totals-lines-head" header>
<Cell>Description</Cell>
<Cell>Qty</Cell>
<Cell>Unit price</Cell>
<Cell>VAT</Cell>
<Cell>Credited</Cell>
</Row>
{totals.lines.map((line) => (
<Row id="credit-note-totals-line">
<Cell>{line.description}</Cell>
<Cell>{line.quantity}</Cell>
<Cell>{line.unitPrice}</Cell>
<Cell>{line.rate}</Cell>
<Cell>{line.amount}</Cell>
</Row>
))}
</Table>
)}
{totals.multipleBands && (
<Table
id="credit-note-totals-analysis"
columns={[{ width: "auto" }, { width: 34, align: "right" }, { width: 34, align: "right" }]}
>
<Row id="credit-note-totals-analysis-head" header>
<Cell>Rate</Cell>
<Cell>Net</Cell>
<Cell>VAT</Cell>
</Row>
{totals.bands.map((band) => (
<Row id="credit-note-totals-band">
<Cell>{band.label}</Cell>
<Cell>{band.net}</Cell>
<Cell>{band.vat}</Cell>
</Row>
))}
</Table>
)}
<Table id="credit-note-totals-summary" columns={[{ width: "auto" }, { width: 40, align: "right" }]}>
<Row id="credit-note-totals-net">
<Cell>Net credited</Cell>
<Cell>{totals.net}</Cell>
</Row>
<Row id="credit-note-totals-vat">
<Cell>VAT credited</Cell>
<Cell>{totals.vat}</Cell>
</Row>
{totals.vatGBP && (
<Row id="credit-note-totals-vat-gbp">
<Cell>VAT credited in sterling</Cell>
<Cell>{totals.vatGBP}</Cell>
</Row>
)}
<Row id="credit-note-totals-total">
<Cell>Total credited</Cell>
<Cell>{totals.total}</Cell>
</Row>
</Table>
</Section>
);
}; derivers/credit-note-totals.deriver.ts // deno-lint-ignore-file no-explicit-any -- the input is request data nobody has checked.
import { deriver } from "docxcelerate/template";
/**
* What a credit note credits, worked from the invoice it undoes. Installed by
* `dxcl add credit-note-totals`.
*
* Every rate, price and exchange rate comes off the original invoice, never
* from today's settings. Money is exact: each decimal is parsed from its
* string into a scaled BigInt, a line is rounded once and VAT once per band,
* half away from zero, so no float is ever multiplied.
*
* 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. Every
* helper is declared inside `run`. No placeholder: it is cheap, so previews
* run it and show real figures.
*/
export default deriver({
name: "creditNoteTotals",
run: (creditNote: unknown) => {
const note = creditNote as any;
const fail = (message: string): never => {
throw new Error("creditNoteTotals: " + message);
};
// A number to a scaled BigInt, from its own string, so nothing is rounded
// by a float. Exponent notation (1e21) and excess decimals are refused.
const parse = (value: unknown, places: number, field: string): bigint => {
if (typeof value !== "number" || !Number.isFinite(value)) return fail(field + " must be a finite number");
const text = String(value);
if (!/^-?\d+(\.\d+)?$/.test(text)) return fail(field + " must be a plain decimal, got " + text);
const [whole, fraction = ""] = text.replace("-", "").split(".");
if (fraction.length > places) return fail(field + " has more than " + places + " decimal places");
const scaled = BigInt(whole + fraction.padEnd(places, "0"));
return text.startsWith("-") ? -scaled : scaled;
};
const nonNegative = (value: unknown, places: number, field: string): bigint => {
const scaled = parse(value, places, field);
return scaled < 0n ? fail(field + " must not be negative") : scaled;
};
// Half away from zero; b is positive.
const divRound = (a: bigint, b: bigint): bigint => {
const magnitude = (2n * (a < 0n ? -a : a) + b) / (2n * b);
return a < 0n ? -magnitude : magnitude;
};
const min = (a: bigint, b: bigint) => (a < b ? a : b);
const max = (a: bigint, b: bigint) => (a > b ? a : b);
const original = note?.original;
if (original === undefined || original === null || typeof original !== "object") {
fail("creditNote.original is required");
}
const credit = note.credit;
if (credit === undefined || credit === null || typeof credit !== "object") {
fail("creditNote.credit is required");
}
const mode: string = credit.mode;
if (mode !== "full" && mode !== "lines" && mode !== "amount") {
fail('creditNote.credit.mode must be "full", "lines" or "amount"');
}
if (typeof original.number !== "string" || original.number.trim() === "") {
fail("creditNote.original.number is required");
}
const number: string = original.number.trim();
if (typeof original.issueDate !== "string" || !/^\d{4}-\d{2}-\d{2}/.test(original.issueDate)) {
fail("creditNote.original.issueDate must be an ISO 8601 date");
}
const issued = new Date(original.issueDate.slice(0, 10) + "T00:00:00Z");
if (Number.isNaN(issued.getTime())) fail("creditNote.original.issueDate must be an ISO 8601 date");
// UTC, so the date does not shift by a day on the engine.
const issueDate = new Intl.DateTimeFormat("en-GB", { dateStyle: "long", timeZone: "UTC" }).format(issued);
const currency: string = typeof original.currency === "string" ? original.currency.toUpperCase() : "";
let exponent = 0;
try {
exponent = new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits ??
2;
} catch (error) {
if (error instanceof RangeError) fail("creditNote.original.currency is not an ISO 4217 code: " + original.currency);
throw error;
}
const scale = 10n ** BigInt(exponent);
const money = (value: unknown, field: string) => nonNegative(value, exponent, field);
const currencyFormat = new Intl.NumberFormat("en-GB", { style: "currency", currency });
const fmt = (minor: bigint) => currencyFormat.format(Number(minor) / 10 ** exponent);
const priceFormat = new Intl.NumberFormat("en-GB", {
style: "currency",
currency,
minimumFractionDigits: exponent,
maximumFractionDigits: 4,
});
const quantityFormat = new Intl.NumberFormat("en-GB", { maximumFractionDigits: 4 });
const sterling = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" });
const sterlingRate = new Intl.NumberFormat("en-GB", {
style: "currency",
currency: "GBP",
minimumFractionDigits: 2,
maximumFractionDigits: 6,
});
// Bands, keyed by rate in hundredths of a percent, or "null".
if (!Array.isArray(original.bands) || original.bands.length === 0) {
fail("creditNote.original.bands must be a non-empty array");
}
const keyOf = (rate: unknown, field: string): { key: string; hundredths: bigint | null } => {
if (rate === null) return { key: "null", hundredths: null };
const hundredths = nonNegative(rate, 2, field);
return { key: String(hundredths), hundredths };
};
const bands: Array<{
key: string;
rate: bigint | null;
label: string;
net: bigint;
vat: bigint;
prevNet: bigint;
prevVat: bigint;
remNet: bigint;
remVat: bigint;
remGross: bigint;
}> = [];
original.bands.forEach((band: any, i: number) => {
const at = "creditNote.original.bands[" + i + "]";
const { key, hundredths } = keyOf(band?.vatRate, at + ".vatRate");
if (bands.some((b) => b.key === key)) fail(at + ".vatRate repeats a rate already on the invoice");
const net = money(band.net, at + ".net");
const vat = money(band.vat, at + ".vat");
if (hundredths === null && vat !== 0n) fail(at + ".vat must be 0 on a band with no VAT");
const label = hundredths === null
? (typeof band.label === "string" && band.label.trim() !== "" ? band.label : "No VAT")
: String(band.vatRate) + "%";
bands.push({
key,
rate: hundredths,
label,
net,
vat,
prevNet: 0n,
prevVat: 0n,
remNet: 0n,
remVat: 0n,
remGross: 0n,
});
});
const bandOf = (key: string) => bands.find((b) => b.key === key);
// Earlier credit notes come off before anything is checked.
const previous = (note.previousCredits ?? []) as any[];
if (!Array.isArray(previous)) fail("creditNote.previousCredits must be an array");
let previousGross = 0n;
previous.forEach((earlier: any, i: number) => {
const at = "creditNote.previousCredits[" + i + "]";
if (!Array.isArray(earlier?.bands)) fail(at + ".bands must be an array");
earlier.bands.forEach((band: any, j: number) => {
const field = at + ".bands[" + j + "]";
const target = bandOf(keyOf(band?.vatRate, field + ".vatRate").key);
if (target === undefined) return fail(field + ".vatRate is not a rate on the original invoice");
const net = money(band.net, field + ".net");
const vat = money(band.vat, field + ".vat");
target.prevNet += net;
target.prevVat += vat;
previousGross += net + vat;
});
});
for (const band of bands) {
band.remNet = band.net - band.prevNet;
band.remVat = band.vat - band.prevVat;
if (band.remNet < 0n || band.remVat < 0n) {
fail("earlier credits exceed what invoice " + number + " charged in the " + band.label + " band");
}
band.remGross = band.remNet + band.remVat;
}
const credited = bands.map(() => ({ net: 0n, vat: 0n }));
const lineRows: Array<{ description: string; quantity: string; unitPrice: string; rate: string; amount: string }> =
[];
if (mode === "full") {
bands.forEach((b, i) => {
credited[i] = { net: b.remNet, vat: b.remVat };
});
if (bands.every((b) => b.remGross === 0n)) fail("nothing is left to credit on invoice " + number);
} else if (mode === "lines") {
if (!Array.isArray(original.lines)) fail("creditNote.original.lines is required for a credit of lines");
if (!Array.isArray(credit.lines) || credit.lines.length === 0) {
fail("creditNote.credit.lines must list at least one line");
}
const originals = new Map<string, { description: string; qty: bigint; unitNet: bigint; key: string }>();
original.lines.forEach((line: any, i: number) => {
const at = "creditNote.original.lines[" + i + "]";
if (typeof line?.id !== "string" || line.id === "") fail(at + ".id is required");
if (originals.has(line.id)) fail(at + ".id repeats " + line.id);
if (typeof line.description !== "string") fail(at + ".description is required");
const qty = parse(line.qty, 4, at + ".qty");
if (qty <= 0n) fail(at + ".qty must be more than 0");
const { key } = keyOf(line.vatRate, at + ".vatRate");
if (bandOf(key) === undefined) fail(at + ".vatRate is not a rate on the original invoice's bands");
originals.set(line.id, {
description: line.description,
qty,
unitNet: nonNegative(line.unitNet, 4, at + ".unitNet"),
key,
});
});
const returned = new Map<string, bigint>();
const bandNet = new Map<string, bigint>();
credit.lines.forEach((line: any, i: number) => {
const at = "creditNote.credit.lines[" + i + "]";
const source = originals.get(line?.id);
if (source === undefined) return fail(at + ".id is not a line on the original invoice");
if (returned.has(line.id)) fail(at + ".id repeats " + line.id);
const qty = parse(line.qty, 4, at + ".qty");
if (qty <= 0n) fail(at + ".qty must be more than 0");
if (qty > source.qty) fail(at + ".qty is more than the " + quantityFormat.format(Number(source.qty) / 1e4) + " invoiced");
returned.set(line.id, qty);
// Quantity and price are both in ten-thousandths; rounded once, here.
const net = divRound(qty * source.unitNet * scale, 10n ** 8n);
bandNet.set(source.key, (bandNet.get(source.key) ?? 0n) + net);
lineRows.push({
description: source.description,
quantity: quantityFormat.format(Number(qty) / 1e4),
unitPrice: priceFormat.format(Number(source.unitNet) / 1e4),
rate: bandOf(source.key)!.label,
amount: fmt(net),
});
});
bands.forEach((b, i) => {
const net = bandNet.get(b.key);
if (net === undefined) return;
// Every line at this rate returned whole: copy what is left, so a full
// return at one rate cannot drift a penny from the original.
const whole = b.prevNet === 0n && b.prevVat === 0n &&
[...originals].every(([id, line]) => line.key !== b.key || returned.get(id) === line.qty);
credited[i] = whole
? { net: b.remNet, vat: b.remVat }
: { net, vat: b.rate === null ? 0n : divRound(net * b.rate, 10000n) };
});
} else {
const amount = money(credit.amount, "creditNote.credit.amount");
if (amount <= 0n) fail("creditNote.credit.amount must be more than 0");
const eligible = bands.map((b, i) => ({ b, i })).filter(({ b }) => b.remGross > 0n);
const pool = eligible.reduce((sum, { b }) => sum + b.remGross, 0n);
if (amount > pool) {
fail("creditNote.credit.amount " + fmt(amount) + " is more than the " + fmt(pool) + " still creditable");
}
// Largest remainder: floors first, then one minor unit each to the biggest
// remainders, the earlier band winning a tie, so the shares add up exactly.
const shares = eligible.map(({ b, i }) => ({
i,
share: amount * b.remGross / pool,
remainder: amount * b.remGross % pool,
}));
const leftover = Number(amount - shares.reduce((sum, s) => sum + s.share, 0n));
[...shares].sort((x, y) => (x.remainder === y.remainder ? x.i - y.i : x.remainder > y.remainder ? -1 : 1))
.slice(0, leftover).forEach((s) => s.share += 1n);
for (const { i, share } of shares) {
const b = bands[i];
if (share === b.remGross) {
credited[i] = { net: b.remNet, vat: b.remVat };
continue;
}
// Back the VAT out of the gross, then keep both halves inside what the
// band has left: that interval is never empty.
const backed = b.rate === null ? 0n : divRound(share * b.rate, 10000n + b.rate);
const vat = max(max(0n, share - b.remNet), min(min(b.remVat, share), backed));
credited[i] = { net: share - vat, vat };
}
}
bands.forEach((b, i) => {
if (credited[i].net > b.remNet || credited[i].vat > b.remVat) {
fail(
"the " + b.label + " band can take at most " + fmt(b.remNet) + " net and " + fmt(b.remVat) +
" VAT after earlier credits; this credit is " + fmt(credited[i].net) + " net and " +
fmt(credited[i].vat) + " VAT.",
);
}
});
const netMinor = credited.reduce((sum, c) => sum + c.net, 0n);
const vatMinor = credited.reduce((sum, c) => sum + c.vat, 0n);
const totalMinor = netMinor + vatMinor;
if (totalMinor === 0n) fail("nothing to credit");
// Sterling: only when the invoice carried UK VAT in another currency. One
// conversion of the total, because summing converted bands would not agree.
let vatGBPMinor: bigint | null = null;
if (currency !== "GBP" && original.fxToGBP !== undefined && original.fxToGBP !== null) {
const fx = parse(original.fxToGBP, 6, "creditNote.original.fxToGBP");
if (fx <= 0n) fail("creditNote.original.fxToGBP must be more than 0");
const firstFull = mode === "full" && previous.length === 0 && original.vatGBP !== undefined &&
original.vatGBP !== null;
vatGBPMinor = firstFull
? nonNegative(original.vatGBP, 2, "creditNote.original.vatGBP")
: divRound(vatMinor * fx * 100n, scale * 10n ** 6n);
}
const basis = mode === "full"
? previous.length === 0
? "This credit note cancels invoice " + number + " in full."
: "This credit note cancels what remained of invoice " + number + " after earlier credits."
: mode === "lines"
? "This credit note credits the items listed below from invoice " + number + "."
: "This credit note is a credit of " + fmt(totalMinor) + " against invoice " + number +
", spread across its VAT rates in proportion to what was charged at each.";
const converted = vatGBPMinor === null
? ""
: " VAT is converted to sterling at that invoice's rate of " +
sterlingRate.format(Number(parse(original.fxToGBP, 6, "creditNote.original.fxToGBP")) / 1e6) + " to 1 " +
currency + ".";
const shown = bands.map((b, i) => ({ b, c: credited[i] })).filter(({ c }) => c.net !== 0n || c.vat !== 0n);
return {
basis,
original: "Credited against invoice " + number + " of " + issueDate + ", at the VAT rates that invoice charged." +
converted,
previouslyCredited: previous.length === 0 ? null : "Earlier credit notes against this invoice: " + fmt(previousGross) + ".",
hasLines: mode === "lines",
lines: lineRows,
multipleBands: shown.length > 1,
bands: shown.map(({ b, c }) => ({
label: b.label,
net: fmt(c.net),
vat: fmt(c.vat),
netMinor: Number(c.net),
vatMinor: Number(c.vat),
})),
net: fmt(netMinor),
vat: fmt(vatMinor),
total: fmt(totalMinor),
netMinor: Number(netMinor),
vatMinor: Number(vatMinor),
totalMinor: Number(totalMinor),
vatGBP: vatGBPMinor === null ? null : sterling.format(Number(vatGBPMinor) / 100),
vatGBPMinor: vatGBPMinor === null ? null : Number(vatGBPMinor),
};
},
});