Royalty reserve and advance recoupment
ClosingThe settlement from a period's earned royalties to the amount paid, reconciled line by line in integer minor units. A reserve against returns is held on physical formats only, never on e-books or digital audio, rounded once per title. Returns are charged against the reserves held for that title, oldest first; only returns beyond them reduce this period's royalties, and any reserve held for the contract's liquidation limit is released in full after returns are charged against it. The statement shows what was withheld and how each earlier reserve was applied or released. Recoupment pools only the titles an advance cross-collateralises; every other title recoups on its own, so one title's earnings never pay another's advance. Each advance is still unrecouped, earned out this period or already earned out, each in its own words, and an unrecouped advance is never called a debt. A total below the minimum payment is carried forward and the statement says so. All of it is one deriver.
npx dxcl add royalty-reserve-and-recoupment Данные предпросмотра
JSON, на котором построен этот предпросмотр{
"royalty": {
"currency": "USD",
"periodIndex": 9,
"periodLabel": "1 January to 30 June 2026",
"reservePercent": 25,
"reserveLiquidationPeriods": 4,
"minimumPaymentMinor": 2500,
"carriedForwardMinor": 1840,
"earned": [
{
"title": "The Cartographer's Daughter: A Novel of the Hudson Valley, 1849–1863",
"physicalMinor": 4812365,
"digitalMinor": 1975040
},
{
"title": "Saltmarsh and Other Stories from the Eastern Seaboard",
"physicalMinor": 1236710,
"digitalMinor": 402385
},
{
"title": "A Field Guide to Disappearing Places (Illustrated Anniversary Edition)",
"physicalMinor": 2104900,
"digitalMinor": 0
},
{
"title": "Tidewater: Essays on Rivers, Memory and the Shoreline",
"physicalMinor": 0,
"digitalMinor": 312480
}
],
"openReserves": [
{
"title": "The Cartographer's Daughter: A Novel of the Hudson Valley, 1849–1863",
"setInPeriod": 5,
"amountMinor": 1184220,
"label": "the statement to 30 June 2024"
},
{
"title": "The Cartographer's Daughter: A Novel of the Hudson Valley, 1849–1863",
"setInPeriod": 7,
"amountMinor": 965310,
"label": "the statement to 30 June 2025"
},
{
"title": "A Field Guide to Disappearing Places (Illustrated Anniversary Edition)",
"setInPeriod": 8,
"amountMinor": 610000,
"label": "the statement to 31 December 2025"
}
],
"returnsCharged": [
{
"title": "The Cartographer's Daughter: A Novel of the Hudson Valley, 1849–1863",
"amountMinor": 702560
},
{
"title": "A Field Guide to Disappearing Places (Illustrated Anniversary Edition)",
"amountMinor": 845900
}
],
"advances": [
{
"titles": [
"The Cartographer's Daughter: A Novel of the Hudson Valley, 1849–1863",
"Saltmarsh and Other Stories from the Eastern Seaboard"
],
"unrecoupedOpeningMinor": 5250000
},
{
"titles": [
"A Field Guide to Disappearing Places (Illustrated Anniversary Edition)"
],
"unrecoupedOpeningMinor": 7500000
}
]
}
} Отрисованный предпросмотр
компонент, отрисованный сам по себеРазрешённые узлы
что получает рендерер — узлов: 1royalty-reserve-and-recoupment section Файлы
что записывает установка; выбранный файл и есть компонентnodes/royalty-reserve-and-recoupment.node.tsx import { Cell, type Nodes, Paragraph, Row, Section, Table, useDeriver, useState } from "docxcelerate/template";
import royaltyReserveAndRecoupment from "../derivers/royalty-reserve-and-recoupment.deriver.ts";
/**
* A royalty statement's closing section: it takes the period's earned
* royalties and works down, line by line, to the amount actually paid.
*
* Decisions already made for you:
*
* - A reserve against returns is held on physical formats only. E-books and
* digital audio cannot be returned to a warehouse, so they carry none. The
* reserve is rounded once per title, so the rows add up to the total.
* - Returns are charged against the reserves held for that title, oldest first,
* not against this period's earnings. Only returns beyond them reduce this
* period's royalties.
* - A reserve held for the contract's liquidation limit is released in full,
* after returns are charged against it.
* - The statement shows its workings: what was withheld, and how each earlier
* reserve was used or released.
* - Recoupment pools only the titles an advance cross-collateralises. Every
* other title recoups on its own, so one title's earnings never pay another's
* advance.
* - An advance is still unrecouped, earned out this period or already earned
* out, each in its own words. An unrecouped advance is never printed as a
* negative balance or as a debt: it is recovered from royalties, never repaid.
* - A total below the minimum payment is carried forward and the statement says
* so. It is never silently zeroed.
* - Every amount is a whole number of minor units.
*
* All of it is decided in one deriver, because nearly every step is arithmetic,
* sorting or filtering on request data, and publishing refuses all of those.
* The node computes nothing: it prints the deriver's result into fixed slots
* and branches on its outcome, with every test written inline so a publish
* build keeps each arm.
*
* The rows 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 `.map()` over the deriver's rows would publish and then resolve to none.
*
* The node publishes 18 branches against the default `branchLimit` of 32: three
* outcomes, two settlement rows, the reserves table, six reserve rows, the
* note and five advance rows. A document that also uses plan-change-proration
* (14) needs `branchLimit` raised.
*
* Installed by `dxcl add royalty-reserve-and-recoupment`.
*/
/** What this component reads. Add these fields to your document data type. */
export interface RoyaltyReserveAndRecoupmentData {
royalty: {
/**
* ISO 4217 code every amount is in: `"USD"`, `"GBP"`, `"EUR"`. 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;
/**
* This statement's period number, counted the same way as `setInPeriod`
* on every open reserve (1 for the first statement, 2 for the next...). It is
* what a reserve's age is measured against. Required: throws when it is not
* an integer of 1 or more.
*/
periodIndex: number;
/**
* How the period is named in the opening line: `"1 January to 30 June 2026"`.
* Missing means `"period <periodIndex>"`.
*/
periodLabel?: string;
/**
* What each title earned this period, before any reserve or return, in
* integer minor units. Two entries for the same title are added together.
* Missing or empty means nothing was earned this period.
*/
earned?: Array<{
/** The title, as printed. Matched exactly against every other `title`. Required: throws when blank. */
title: string;
/**
* Royalties on physical formats (hardback, paperback, audio CD): the only
* royalties a reserve is held on. Missing means 0. Throws when not a
* non-negative integer.
*/
physicalMinor?: number;
/**
* Royalties on e-books and digital audio. No reserve is ever held on these.
* Missing means 0. Throws when not a non-negative integer.
*/
digitalMinor?: number;
}>;
/**
* The share of this period's physical royalties held back against returns,
* as a percentage: `25` for 25%. At most two decimals count (it is rounded to
* basis points). Missing means 0: no new reserve. Throws when not a finite
* number from 0 to 100.
*/
reservePercent?: number;
/**
* How many periods a reserve may be held before it must be released:
* `4` releases a reserve set in period 5 on the period-9 statement. Required
* whenever any reserve exists (an open reserve, or a `reservePercent` above
* 0 with physical royalties): throws then when it is missing or not an
* integer of 1 or more, because a reserve with no release date is exactly
* the mistake this component exists to prevent. Ignored when no reserve exists.
*/
reserveLiquidationPeriods?: number;
/**
* Reserves held on earlier statements and not yet used or released, one
* entry per title per period that set it. Missing or empty means none.
*/
openReserves?: Array<{
/** The title the reserve was held on. Required: throws when blank. */
title: string;
/**
* The `periodIndex` of the statement that set it. Required: throws when
* not an integer, or when it is not before `periodIndex` (this period's
* reserve is the one this component computes, so it is never "open").
*/
setInPeriod: number;
/** What is still held, in integer minor units. Required: throws when not a non-negative integer. */
amountMinor: number;
/**
* How the reserve's period is named in the note: `"the statement to 30 June 2024"`.
* Missing means `"period <setInPeriod>"`.
*/
label?: string;
}>;
/**
* Royalties on copies returned this period, by title, in integer minor
* units. Entries for the same title are added together. Missing or empty means no returns.
*/
returnsCharged?: Array<{
/** The title the returned copies belong to. Required: throws when blank. */
title: string;
/** Required: throws when not a non-negative integer. */
amountMinor: number;
}>;
/**
* One entry per advance: the titles it covers and what of it was unearned at
* the start of this period. Titles in one entry are pooled (joint accounting,
* cross-collateralised). A title in no entry has no advance and settles on
* its own. Missing or empty means no title has an advance.
*/
advances?: Array<{
/**
* The titles this advance covers, matched exactly. Required: throws when
* empty, when an entry is blank, or when a title appears in two advances.
*/
titles: string[];
/**
* The unearned part of the advance at the start of this period, in integer
* minor units. 0 means already earned out. Required: throws when not a
* non-negative integer.
*/
unrecoupedOpeningMinor: number;
}>;
/**
* The smallest amount the publisher pays out, in integer minor units. A total
* due below it is carried forward instead of paid. Missing means no threshold:
* any amount above 0 is paid. Throws when present and not a non-negative integer.
*/
minimumPaymentMinor?: number;
/**
* An amount carried forward from the last statement because it was under the
* minimum, in integer minor units. It is added to this period's total due.
* Missing means 0. Throws when present and not a non-negative integer.
*/
carriedForwardMinor?: number;
};
}
/**
* Prints the settlement from royalties earned to the amount paid, the reserve
* ledger with its note, and each advance's position. The section always prints.
*/
export const RoyaltyReserveAndRecoupment: Nodes = async () => {
const [royalty] = useState((data: RoyaltyReserveAndRecoupmentData) => data.royalty);
const r = await useDeriver(royaltyReserveAndRecoupment, [royalty]);
return (
<Section id="royalty-reserve-and-recoupment" title="Royalties, reserves and advances">
<Paragraph id="royalty-intro">{r.intro}</Paragraph>
{r.outcome === "payable" && (
<Paragraph id="royalty-payable">{r.payableNow} is payable to you for this period.</Paragraph>
)}
{r.outcome === "below-minimum" && (
<Paragraph id="royalty-below-minimum">
The {r.totalDue} due for this period is below the minimum payment of {r.minimum}, so it is carried forward to
your next statement rather than paid now. It is not lost: it is added to what is due then.
</Paragraph>
)}
{r.outcome === "nothing" && <Paragraph id="royalty-nothing-payable">Nothing is payable for this period.</Paragraph>}
<Table id="royalty-settlement" columns={[{ width: "auto" }, { width: 34, align: "right" }]}>
<Row id="royalty-settlement-header" header>
<Cell>This period</Cell>
<Cell>Amount</Cell>
</Row>
<Row id="royalty-settlement-physical">
<Cell>Royalties earned on physical formats</Cell>
<Cell>{r.physical}</Cell>
</Row>
<Row id="royalty-settlement-digital">
<Cell>Royalties earned on e-books and digital audio</Cell>
<Cell>{r.digital}</Cell>
</Row>
<Row id="royalty-settlement-reserve-held">
<Cell>{r.heldLabel}</Cell>
<Cell>{r.held}</Cell>
</Row>
<Row id="royalty-settlement-reserve-released">
<Cell>Earlier reserves released</Cell>
<Cell>{r.released}</Cell>
</Row>
<Row id="royalty-settlement-returns-beyond">
<Cell>Returns beyond the reserves held for them</Cell>
<Cell>{r.excess}</Cell>
</Row>
<Row id="royalty-settlement-net">
<Cell>Net royalties this period</Cell>
<Cell>{r.net}</Cell>
</Row>
<Row id="royalty-settlement-advances">
<Cell>Set against unearned balances</Cell>
<Cell>{r.advanceAdjustment}</Cell>
</Row>
{r.broughtForward && (
<Row id="royalty-settlement-brought-forward">
<Cell>Brought forward from your last statement</Cell>
<Cell>{r.broughtForward}</Cell>
</Row>
)}
<Row id="royalty-settlement-due">
<Cell>Due for this period</Cell>
<Cell>{r.totalDue}</Cell>
</Row>
{r.carriedForward && (
<Row id="royalty-settlement-carried-forward">
<Cell>Carried forward to your next statement</Cell>
<Cell>{r.carriedForward}</Cell>
</Row>
)}
<Row id="royalty-settlement-payable">
<Cell>Payable now</Cell>
<Cell>{r.payableNow}</Cell>
</Row>
</Table>
{r.showReserves && (
<Table
id="royalty-reserves"
columns={[
{ width: "auto" },
{ width: 24, align: "right" },
{ width: 24, align: "right" },
{ width: 24, align: "right" },
{ width: 24, align: "right" },
{ width: 24, align: "right" },
]}
>
<Row id="royalty-reserves-header" header>
<Cell>Title</Cell>
<Cell>Held at start</Cell>
<Cell>Returns charged</Cell>
<Cell>Released</Cell>
<Cell>Held this period</Cell>
<Cell>Held at end</Cell>
</Row>
{r.reserveRows[0].title && (
<Row id="royalty-reserve-1">
<Cell>{r.reserveRows[0].title}</Cell>
<Cell>{r.reserveRows[0].start}</Cell>
<Cell>{r.reserveRows[0].returns}</Cell>
<Cell>{r.reserveRows[0].released}</Cell>
<Cell>{r.reserveRows[0].held}</Cell>
<Cell>{r.reserveRows[0].end}</Cell>
</Row>
)}
{r.reserveRows[1].title && (
<Row id="royalty-reserve-2">
<Cell>{r.reserveRows[1].title}</Cell>
<Cell>{r.reserveRows[1].start}</Cell>
<Cell>{r.reserveRows[1].returns}</Cell>
<Cell>{r.reserveRows[1].released}</Cell>
<Cell>{r.reserveRows[1].held}</Cell>
<Cell>{r.reserveRows[1].end}</Cell>
</Row>
)}
{r.reserveRows[2].title && (
<Row id="royalty-reserve-3">
<Cell>{r.reserveRows[2].title}</Cell>
<Cell>{r.reserveRows[2].start}</Cell>
<Cell>{r.reserveRows[2].returns}</Cell>
<Cell>{r.reserveRows[2].released}</Cell>
<Cell>{r.reserveRows[2].held}</Cell>
<Cell>{r.reserveRows[2].end}</Cell>
</Row>
)}
{r.reserveRows[3].title && (
<Row id="royalty-reserve-4">
<Cell>{r.reserveRows[3].title}</Cell>
<Cell>{r.reserveRows[3].start}</Cell>
<Cell>{r.reserveRows[3].returns}</Cell>
<Cell>{r.reserveRows[3].released}</Cell>
<Cell>{r.reserveRows[3].held}</Cell>
<Cell>{r.reserveRows[3].end}</Cell>
</Row>
)}
{r.reserveRows[4].title && (
<Row id="royalty-reserve-5">
<Cell>{r.reserveRows[4].title}</Cell>
<Cell>{r.reserveRows[4].start}</Cell>
<Cell>{r.reserveRows[4].returns}</Cell>
<Cell>{r.reserveRows[4].released}</Cell>
<Cell>{r.reserveRows[4].held}</Cell>
<Cell>{r.reserveRows[4].end}</Cell>
</Row>
)}
{r.reserveRows[5].title && (
<Row id="royalty-reserve-6">
<Cell>{r.reserveRows[5].title}</Cell>
<Cell>{r.reserveRows[5].start}</Cell>
<Cell>{r.reserveRows[5].returns}</Cell>
<Cell>{r.reserveRows[5].released}</Cell>
<Cell>{r.reserveRows[5].held}</Cell>
<Cell>{r.reserveRows[5].end}</Cell>
</Row>
)}
<Row id="royalty-reserves-total">
<Cell>All titles</Cell>
<Cell>{r.reserveTotal.start}</Cell>
<Cell>{r.reserveTotal.returns}</Cell>
<Cell>{r.reserveTotal.released}</Cell>
<Cell>{r.reserveTotal.held}</Cell>
<Cell>{r.reserveTotal.end}</Cell>
</Row>
</Table>
)}
{r.reserveNote && <Paragraph id="royalty-reserves-note">{r.reserveNote}</Paragraph>}
<Table
id="royalty-advances"
columns={[
{ width: "auto" },
{ width: 26, align: "right" },
{ width: 26, align: "right" },
{ width: 26, align: "right" },
{ width: 26, align: "right" },
]}
>
<Row id="royalty-advances-header" header>
<Cell>Titles</Cell>
<Cell>Unearned at start</Cell>
<Cell>Net royalties</Cell>
<Cell>Unearned at end</Cell>
<Cell>Payable</Cell>
</Row>
<Row id="royalty-advance-1">
<Cell>
<Paragraph id="royalty-advance-1-titles">{r.units[0].titles}</Paragraph>
<Paragraph id="royalty-advance-1-status">{r.units[0].status}</Paragraph>
</Cell>
<Cell>{r.units[0].opening}</Cell>
<Cell>{r.units[0].net}</Cell>
<Cell>{r.units[0].closing}</Cell>
<Cell>{r.units[0].payable}</Cell>
</Row>
{r.units[1].titles && (
<Row id="royalty-advance-2">
<Cell>
<Paragraph id="royalty-advance-2-titles">{r.units[1].titles}</Paragraph>
<Paragraph id="royalty-advance-2-status">{r.units[1].status}</Paragraph>
</Cell>
<Cell>{r.units[1].opening}</Cell>
<Cell>{r.units[1].net}</Cell>
<Cell>{r.units[1].closing}</Cell>
<Cell>{r.units[1].payable}</Cell>
</Row>
)}
{r.units[2].titles && (
<Row id="royalty-advance-3">
<Cell>
<Paragraph id="royalty-advance-3-titles">{r.units[2].titles}</Paragraph>
<Paragraph id="royalty-advance-3-status">{r.units[2].status}</Paragraph>
</Cell>
<Cell>{r.units[2].opening}</Cell>
<Cell>{r.units[2].net}</Cell>
<Cell>{r.units[2].closing}</Cell>
<Cell>{r.units[2].payable}</Cell>
</Row>
)}
{r.units[3].titles && (
<Row id="royalty-advance-4">
<Cell>
<Paragraph id="royalty-advance-4-titles">{r.units[3].titles}</Paragraph>
<Paragraph id="royalty-advance-4-status">{r.units[3].status}</Paragraph>
</Cell>
<Cell>{r.units[3].opening}</Cell>
<Cell>{r.units[3].net}</Cell>
<Cell>{r.units[3].closing}</Cell>
<Cell>{r.units[3].payable}</Cell>
</Row>
)}
{r.units[4].titles && (
<Row id="royalty-advance-5">
<Cell>
<Paragraph id="royalty-advance-5-titles">{r.units[4].titles}</Paragraph>
<Paragraph id="royalty-advance-5-status">{r.units[4].status}</Paragraph>
</Cell>
<Cell>{r.units[4].opening}</Cell>
<Cell>{r.units[4].net}</Cell>
<Cell>{r.units[4].closing}</Cell>
<Cell>{r.units[4].payable}</Cell>
</Row>
)}
{r.units[5].titles && (
<Row id="royalty-advance-6">
<Cell>
<Paragraph id="royalty-advance-6-titles">{r.units[5].titles}</Paragraph>
<Paragraph id="royalty-advance-6-status">{r.units[5].status}</Paragraph>
</Cell>
<Cell>{r.units[5].opening}</Cell>
<Cell>{r.units[5].net}</Cell>
<Cell>{r.units[5].closing}</Cell>
<Cell>{r.units[5].payable}</Cell>
</Row>
)}
</Table>
</Section>
);
}; derivers/royalty-reserve-and-recoupment.deriver.ts // deno-lint-ignore-file no-explicit-any
import { deriver } from "docxcelerate/template";
/**
* Works a royalty statement down from what was earned to what is paid, and
* decides what each advance and the total mean. Installed by
* `dxcl add royalty-reserve-and-recoupment`.
*
* 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: "royaltyReserveAndRecoupment",
run: (royalty: unknown) => {
const roy = royalty as any;
const fail = (message: string): never => {
throw new Error(message);
};
// Currency first: the exponent decides how every amount is read and printed.
// Intl accepts any three letters, so a code it does not list is refused here.
const currency = roy?.currency;
let money: Intl.NumberFormat;
try {
money = new Intl.NumberFormat("en-GB", { style: "currency", currency });
const known = (Intl as any).supportedValuesOf?.("currency") as string[] | undefined;
if (known && !known.includes(String(currency).toUpperCase())) throw new Error("unknown");
} catch {
throw new Error("royalty.currency must be an ISO 4217 code");
}
const exponent = money.resolvedOptions().maximumFractionDigits as number;
const fmt = (minor: number) => money.format(minor / 10 ** exponent);
// A deduction is printed negative, but zero is never "-US$0.00".
const neg = (minor: number) => fmt(minor === 0 ? 0 : -minor);
const list = new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" });
const percent = new Intl.NumberFormat("en-GB", { maximumFractionDigits: 2 });
const nonNegative = (value: unknown, field: string): number => {
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
fail(field + " must be a non-negative integer of minor units");
}
return value as number;
};
const optionalMinor = (value: unknown, field: string): number =>
value === undefined || value === null ? 0 : nonNegative(value, field);
const titleOf = (value: unknown, field: string): string => {
if (typeof value !== "string" || value.trim() === "") fail(field + " is required");
return value as string;
};
const listOf = (value: unknown): any[] => (Array.isArray(value) ? value : []);
const periodIndex = roy.periodIndex;
if (typeof periodIndex !== "number" || !Number.isInteger(periodIndex) || periodIndex < 1) {
fail("royalty.periodIndex must be an integer of 1 or more");
}
const periodLabel = typeof roy.periodLabel === "string" && roy.periodLabel.trim() !== ""
? roy.periodLabel
: "period " + periodIndex;
const reservePercent = roy.reservePercent ?? 0;
if (typeof reservePercent !== "number" || !Number.isFinite(reservePercent) || reservePercent < 0 || reservePercent > 100) {
fail("royalty.reservePercent must be a number from 0 to 100");
}
const bp = Math.round(reservePercent * 100);
const minimum = roy.minimumPaymentMinor === undefined || roy.minimumPaymentMinor === null
? undefined
: nonNegative(roy.minimumPaymentMinor, "royalty.minimumPaymentMinor");
const broughtForward = optionalMinor(roy.carriedForwardMinor, "royalty.carriedForwardMinor");
// Titles in order of first appearance, with their summed figures.
const titles: string[] = [];
const figures = new Map<string, { P: number; D: number; R: number; reserves: any[] }>();
const figuresOf = (title: string) => {
let f = figures.get(title);
if (!f) {
f = { P: 0, D: 0, R: 0, reserves: [] };
figures.set(title, f);
titles.push(title);
}
return f;
};
listOf(roy.earned).forEach((e, i) => {
const f = figuresOf(titleOf(e?.title, "royalty.earned[" + i + "].title"));
f.P += optionalMinor(e.physicalMinor, "royalty.earned[" + i + "].physicalMinor");
f.D += optionalMinor(e.digitalMinor, "royalty.earned[" + i + "].digitalMinor");
});
const open = listOf(roy.openReserves);
open.forEach((o, i) => {
const at = "royalty.openReserves[" + i + "]";
const f = figuresOf(titleOf(o?.title, at + ".title"));
if (typeof o.setInPeriod !== "number" || !Number.isInteger(o.setInPeriod)) {
fail(at + ".setInPeriod must be an integer");
}
if (o.setInPeriod >= periodIndex) fail(at + ".setInPeriod must be before royalty.periodIndex");
f.reserves.push({
setIn: o.setInPeriod as number,
amount: nonNegative(o.amountMinor, at + ".amountMinor"),
label: typeof o.label === "string" && o.label.trim() !== "" ? o.label : "period " + o.setInPeriod,
});
});
listOf(roy.returnsCharged).forEach((r, i) => {
const at = "royalty.returnsCharged[" + i + "]";
figuresOf(titleOf(r?.title, at + ".title")).R += nonNegative(r.amountMinor, at + ".amountMinor");
});
const advanceInputs = listOf(roy.advances);
const advanceOf = new Map<string, number>();
advanceInputs.forEach((a, i) => {
const at = "royalty.advances[" + i + "]";
if (!Array.isArray(a?.titles) || a.titles.length === 0) fail(at + ".titles must not be empty");
a.titles.forEach((t: unknown, j: number) => {
figuresOf(titleOf(t, at + ".titles[" + j + "]"));
if (advanceOf.has(t as string)) fail(at + ".titles[" + j + "] is already in another advance");
advanceOf.set(t as string, i);
});
nonNegative(a.unrecoupedOpeningMinor, at + ".unrecoupedOpeningMinor");
});
if (titles.length === 0) fail("royalty has no titles");
const anyPhysical = titles.some((t) => figures.get(t)!.P > 0);
let liquidation = 0;
if (open.length > 0 || (bp > 0 && anyPhysical)) {
liquidation = roy.reserveLiquidationPeriods;
if (typeof liquidation !== "number" || !Number.isInteger(liquidation) || liquidation < 1) {
fail("royalty.reserveLiquidationPeriods must be an integer of 1 or more when a reserve exists");
}
}
// Per-title ledger: returns are charged oldest first, then aged reserves
// are released, so an aged reserve absorbs returns before its remainder goes.
const notes: string[] = [];
const ledgers = titles.map((title) => {
const f = figures.get(title)!;
const reserves = f.reserves.slice().sort((a, b) => a.setIn - b.setIn);
const start = reserves.reduce((s, r) => s + r.amount, 0);
const sentences: string[] = [];
let left = f.R;
let applied = 0;
for (const r of reserves) {
const take = Math.min(left, r.amount);
applied += take;
r.amount -= take;
left -= take;
if (take > 0) {
sentences.push("On " + title + ", returns of " + fmt(take) + " were charged against the reserve from " + r.label + ".");
}
}
const excess = left;
let released = 0;
for (const r of reserves) {
if (periodIndex - r.setIn >= liquidation && r.amount > 0) {
released += r.amount;
sentences.push(
"On " + title + ", the remaining " + fmt(r.amount) + " of the reserve from " + r.label +
" was released, having been held for " + (periodIndex - r.setIn) + " periods.",
);
r.amount = 0;
}
}
if (excess > 0) {
sentences.push(
"On " + title + ", returns of " + fmt(excess) +
" were more than the reserves held for them and were charged against this period's royalties.",
);
}
// Half up on integers, once per title, so the rows add up to the total.
if (!Number.isSafeInteger(f.P * bp)) fail("royalty.earned physical royalties are too large to reserve");
const held = Math.floor((f.P * bp + 5000) / 10000);
const end = start - applied - released + held;
notes.push(...sentences);
return { title, P: f.P, D: f.D, start, applied, released, held, excess, end, net: f.P + f.D - held - excess + released };
});
const reserveLedgers = ledgers.filter((l) => l.start > 0 || l.held > 0);
if (reserveLedgers.length > 6) {
fail("royaltyReserveAndRecoupment: " + reserveLedgers.length + " titles carry a reserve; this component prints at most 6");
}
// One accounting unit per advance, then each unadvanced title alone.
const netOf = new Map(ledgers.map((l) => [l.title, l.net]));
const rawUnits: Array<{ titles: string[]; U: number; noAdvance: boolean }> = [
...advanceInputs.map((a) => ({ titles: a.titles as string[], U: a.unrecoupedOpeningMinor as number, noAdvance: false })),
...titles.filter((t) => !advanceOf.has(t)).map((t) => ({ titles: [t], U: 0, noAdvance: true })),
];
if (rawUnits.length > 6) {
fail("royaltyReserveAndRecoupment: " + rawUnits.length + " accounts; this component prints at most 6");
}
const units = rawUnits.map((u) => {
const net = u.titles.reduce((s, t) => s + netOf.get(t)!, 0);
const closing = Math.max(0, u.U - net);
const payable = Math.max(0, net - u.U);
const state = u.U === 0 && net < 0
? "deficit"
: u.U > 0 && net < u.U
? "unrecouped"
: u.U > 0
? "earned-out-now"
: !u.noAdvance
? "earned-out"
: "no-advance";
const names = list.format(u.titles);
const status = state === "unrecouped"
? "The advance on " + names + " has " + fmt(closing) +
" still to earn from future royalties, so nothing is payable on it yet. This is not a debt: an advance is recovered only from royalties, never repaid."
: state === "earned-out-now"
? payable > 0
? "The advance on " + names + " earned out this period: " + fmt(u.U) + " of this period's royalties completed it, and the remaining " + fmt(payable) + " is payable."
: "The advance on " + names + " earned out exactly this period, so nothing more is payable on it yet; royalties from the next period are payable in full."
: state === "earned-out"
? net > 0
? "The advance on " + names + " has already earned out, so the " + fmt(net) + " earned this period is payable in full."
: "The advance on " + names + " has already earned out, and nothing was earned on it this period."
: state === "no-advance"
? net > 0
? "There is no advance on " + names + ", so the " + fmt(net) + " earned this period is payable in full."
: "There is no advance on " + names + ", and nothing was earned on it this period."
: "Returns on " + names + " this period were " + fmt(-net) + " more than its royalties. That is set against future royalties on it, and is not a debt.";
return { titles: u.titles, names, status, state, U: u.U, noAdvance: u.noAdvance, net, closing, payable };
});
const sum = (xs: number[]) => xs.reduce((s, x) => s + x, 0);
const physicalTotal = sum(ledgers.map((l) => l.P));
const digitalTotal = sum(ledgers.map((l) => l.D));
const heldTotal = sum(ledgers.map((l) => l.held));
const releasedTotal = sum(ledgers.map((l) => l.released));
const excessTotal = sum(ledgers.map((l) => l.excess));
const netTotal = physicalTotal + digitalTotal - heldTotal + releasedTotal - excessTotal;
if (netTotal !== sum(ledgers.map((l) => l.net))) fail("royaltyReserveAndRecoupment: settlement does not reconcile");
const payablesTotal = sum(units.map((u) => u.payable));
const totalDue = payablesTotal + broughtForward;
const outcome = totalDue === 0 ? "nothing" : minimum !== undefined && totalDue < minimum ? "below-minimum" : "payable";
const payableNow = outcome === "payable" ? totalDue : 0;
const carriedForward = outcome === "below-minimum" ? totalDue : 0;
const blankRow = { title: "", start: "", returns: "", released: "", held: "", end: "" };
const reserveRows = reserveLedgers.map((l) => ({
title: l.title,
start: fmt(l.start),
returns: fmt(l.applied),
released: fmt(l.released),
held: fmt(l.held),
end: fmt(l.end),
}));
while (reserveRows.length < 6) reserveRows.push({ ...blankRow });
const blankUnit = { titles: "", status: "", opening: "", net: "", closing: "", payable: "", state: "" };
const unitRows = units.map((u) => ({
titles: u.names,
status: u.status,
opening: u.noAdvance ? "None" : fmt(u.U),
net: fmt(u.net),
closing: fmt(u.state === "deficit" ? -u.net : u.closing),
payable: fmt(u.payable),
state: u.state,
}));
while (unitRows.length < 6) unitRows.push({ ...blankUnit });
const col = (pick: (l: (typeof ledgers)[number]) => number) => fmt(sum(reserveLedgers.map(pick)));
return {
intro: "Royalties for " + periodLabel +
", from what was earned to what is paid. A reserve against returns is held on physical formats only; e-books and digital audio carry none.",
outcome,
payableNow: fmt(payableNow),
totalDue: fmt(totalDue),
minimum: minimum === undefined ? "" : fmt(minimum),
physical: fmt(physicalTotal),
digital: fmt(digitalTotal),
heldLabel: "Reserve held against returns (" + percent.format(bp / 100) + "% of physical royalties)",
held: neg(heldTotal),
released: fmt(releasedTotal),
excess: neg(excessTotal),
net: fmt(netTotal),
advanceAdjustment: fmt(payablesTotal - netTotal),
broughtForward: broughtForward === 0 ? "" : fmt(broughtForward),
carriedForward: outcome === "below-minimum" ? neg(carriedForward) : "",
showReserves: reserveLedgers.length > 0,
reserveRows,
reserveTotal: {
start: col((l) => l.start),
returns: col((l) => l.applied),
released: col((l) => l.released),
held: col((l) => l.held),
end: col((l) => l.end),
},
reserveNote: notes.join(" "),
units: unitRows,
minor: {
physicalTotal,
digitalTotal,
heldTotal,
releasedTotal,
excessTotal,
netTotal,
payablesTotal,
totalDue,
payableNow,
carriedForward,
reserveRows: reserveLedgers.map((l) => ({
title: l.title,
startMinor: l.start,
appliedMinor: l.applied,
releasedMinor: l.released,
heldMinor: l.held,
endMinor: l.end,
})),
units: units.map((u) => ({
titles: u.titles,
state: u.state,
openingMinor: u.U,
netMinor: u.net,
closingMinor: u.state === "deficit" ? -u.net : u.closing,
payableMinor: u.payable,
})),
},
};
},
});