@diy-accounting-uk/diya-submit 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,285 @@
1
+ <!doctype html>
2
+ <!-- SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0 -->
3
+ <!-- Copyright (C) 2006-2026 DIY Accounting Limited -->
4
+ <html lang="en-GB">
5
+ <head>
6
+ <meta charset="utf-8" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
8
+ <meta name="color-scheme" content="light dark" />
9
+ <title>VAT return review</title>
10
+ <style>
11
+ :root {
12
+ --text: #1b1f23;
13
+ --muted: #57606a;
14
+ --surface: #ffffff;
15
+ --line: #d0d7de;
16
+ --accent: #0b5cad;
17
+ --accent-text: #ffffff;
18
+ }
19
+ @media (prefers-color-scheme: dark) {
20
+ :root {
21
+ --text: #e6edf3;
22
+ --muted: #9aa4af;
23
+ --surface: #161b22;
24
+ --line: #30363d;
25
+ --accent: #4493f8;
26
+ --accent-text: #0d1117;
27
+ }
28
+ }
29
+ * {
30
+ box-sizing: border-box;
31
+ }
32
+ body {
33
+ margin: 0;
34
+ padding: 16px;
35
+ font:
36
+ 15px/1.45 system-ui,
37
+ -apple-system,
38
+ "Segoe UI",
39
+ sans-serif;
40
+ color: var(--text);
41
+ background: var(--surface);
42
+ }
43
+ h1 {
44
+ margin: 0 0 2px;
45
+ font-size: 17px;
46
+ }
47
+ .period,
48
+ .note {
49
+ margin: 0 0 12px;
50
+ color: var(--muted);
51
+ font-size: 13px;
52
+ }
53
+ table {
54
+ width: 100%;
55
+ border-collapse: collapse;
56
+ }
57
+ th,
58
+ td {
59
+ padding: 6px 8px;
60
+ border-bottom: 1px solid var(--line);
61
+ text-align: left;
62
+ vertical-align: top;
63
+ }
64
+ td.amount {
65
+ text-align: right;
66
+ font-variant-numeric: tabular-nums;
67
+ white-space: nowrap;
68
+ }
69
+ th.box {
70
+ width: 3.5em;
71
+ color: var(--muted);
72
+ font-weight: 600;
73
+ }
74
+ .actions {
75
+ margin-top: 14px;
76
+ }
77
+ button {
78
+ padding: 9px 14px;
79
+ border: 0;
80
+ border-radius: 6px;
81
+ font: inherit;
82
+ font-weight: 600;
83
+ color: var(--accent-text);
84
+ background: var(--accent);
85
+ cursor: pointer;
86
+ }
87
+ button:focus-visible {
88
+ outline: 3px solid var(--text);
89
+ outline-offset: 2px;
90
+ }
91
+ #status {
92
+ margin: 8px 0 0;
93
+ color: var(--muted);
94
+ font-size: 13px;
95
+ }
96
+ </style>
97
+ </head>
98
+ <body>
99
+ <main id="card" aria-live="polite">
100
+ <p class="note" id="waiting">Waiting for the VAT return.</p>
101
+ </main>
102
+ <script>
103
+ (function () {
104
+ "use strict";
105
+
106
+ var PROTOCOL_VERSION = "2026-01-26";
107
+ var BOXES = [
108
+ ["box1", "VAT due on sales and other outputs", 2],
109
+ ["box2", "VAT due on acquisitions from the EU", 2],
110
+ ["box3", "Total VAT due", 2],
111
+ ["box4", "VAT reclaimed on purchases and other inputs", 2],
112
+ ["box5", "Net VAT to pay HMRC or reclaim", 2],
113
+ ["box6", "Total value of sales, excluding VAT", 0],
114
+ ["box7", "Total value of purchases, excluding VAT", 0],
115
+ ["box8", "Total value of supplies to the EU, excluding VAT", 0],
116
+ ["box9", "Total value of acquisitions from the EU, excluding VAT", 0],
117
+ ];
118
+
119
+ var nextId = 1;
120
+ var pending = {};
121
+ var handoffLink = null;
122
+
123
+ function send(message) {
124
+ window.parent.postMessage(message, "*");
125
+ }
126
+
127
+ function request(method, params) {
128
+ var id = nextId++;
129
+ return new Promise(function (resolve, reject) {
130
+ pending[id] = { resolve: resolve, reject: reject };
131
+ send({ jsonrpc: "2.0", id: id, method: method, params: params });
132
+ });
133
+ }
134
+
135
+ function money(value, decimals) {
136
+ return "£" + value.toLocaleString("en-GB", { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
137
+ }
138
+
139
+ function pence(value) {
140
+ return Math.round(value * 100) / 100;
141
+ }
142
+
143
+ // The derive tool answers the nine boxes. The prepare tool answers the seven figures the
144
+ // form takes, and the form works out boxes 3 and 5 from them.
145
+ function boxesOf(result) {
146
+ if (result.boxes && typeof result.boxes === "object") return result.boxes;
147
+ var figures = result.figures;
148
+ if (!figures || typeof figures !== "object") return null;
149
+ var box3 = pence(figures.vatDueSales + figures.vatDueAcquisitions);
150
+ return {
151
+ box1: figures.vatDueSales,
152
+ box2: figures.vatDueAcquisitions,
153
+ box3: box3,
154
+ box4: figures.vatReclaimedCurrPeriod,
155
+ box5: pence(Math.abs(box3 - figures.vatReclaimedCurrPeriod)),
156
+ box6: figures.totalValueSalesExVAT,
157
+ box7: figures.totalValuePurchasesExVAT,
158
+ box8: figures.totalValueGoodsSuppliedExVAT,
159
+ box9: figures.totalAcquisitionsExVAT,
160
+ };
161
+ }
162
+
163
+ function element(tag, text, className) {
164
+ var node = document.createElement(tag);
165
+ if (text !== undefined) node.textContent = text;
166
+ if (className) node.className = className;
167
+ return node;
168
+ }
169
+
170
+ function httpsLink(value) {
171
+ try {
172
+ var url = new URL(value);
173
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
174
+ } catch (error) {
175
+ return null;
176
+ }
177
+ }
178
+
179
+ function openLink() {
180
+ var status = document.getElementById("status");
181
+ request("ui/open-link", { url: handoffLink }).then(
182
+ function () {
183
+ status.textContent = "The form is open in your browser. Check the figures there and file the return there.";
184
+ },
185
+ function () {
186
+ status.textContent = "Your assistant cannot open links from here. Ask it to show you the link.";
187
+ },
188
+ );
189
+ }
190
+
191
+ function renderError(message) {
192
+ var card = document.getElementById("card");
193
+ card.replaceChildren(element("p", message, "note"));
194
+ }
195
+
196
+ function render(result) {
197
+ var boxes = boxesOf(result);
198
+ if (!boxes) {
199
+ renderError("This result holds no VAT return.");
200
+ return;
201
+ }
202
+ var card = document.getElementById("card");
203
+ card.replaceChildren();
204
+ card.appendChild(element("h1", "VAT return to check"));
205
+ var period = result.period || result;
206
+ if (period.periodStart && period.periodEnd) {
207
+ card.appendChild(element("p", period.periodStart + " to " + period.periodEnd, "period"));
208
+ }
209
+ var table = document.createElement("table");
210
+ var caption = element("caption", "The nine VAT boxes");
211
+ caption.style.position = "absolute";
212
+ caption.style.left = "-9999px";
213
+ table.appendChild(caption);
214
+ var body = document.createElement("tbody");
215
+ BOXES.forEach(function (box) {
216
+ var value = boxes[box[0]];
217
+ var row = document.createElement("tr");
218
+ var head = element("th", "Box " + box[0].slice(3), "box");
219
+ head.scope = "row";
220
+ row.appendChild(head);
221
+ row.appendChild(element("td", box[1]));
222
+ row.appendChild(element("td", typeof value === "number" ? money(value, box[2]) : "", "amount"));
223
+ body.appendChild(row);
224
+ });
225
+ table.appendChild(body);
226
+ card.appendChild(table);
227
+ card.appendChild(element("p", "Nothing has been filed. You check the figures, declare and file in the browser.", "note"));
228
+ handoffLink = typeof result.link === "string" ? httpsLink(result.link) : null;
229
+ if (handoffLink) {
230
+ var actions = element("div", undefined, "actions");
231
+ var button = element("button", "Open the VAT form to check and file");
232
+ button.type = "button";
233
+ button.id = "open-form";
234
+ button.addEventListener("click", openLink);
235
+ actions.appendChild(button);
236
+ actions.appendChild(element("p", "", "")).id = "status";
237
+ card.appendChild(actions);
238
+ }
239
+ send({
240
+ jsonrpc: "2.0",
241
+ method: "ui/notifications/size-changed",
242
+ params: { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight },
243
+ });
244
+ }
245
+
246
+ window.addEventListener("message", function (event) {
247
+ if (event.source !== window.parent) return;
248
+ var message = event.data;
249
+ if (!message || message.jsonrpc !== "2.0") return;
250
+ if (message.id !== undefined && !message.method && pending[message.id]) {
251
+ var entry = pending[message.id];
252
+ delete pending[message.id];
253
+ if (message.error) entry.reject(message.error);
254
+ else entry.resolve(message.result);
255
+ return;
256
+ }
257
+ if (message.method === "ui/notifications/tool-result") {
258
+ var params = message.params || {};
259
+ if (params.isError) {
260
+ var first = params.content && params.content[0];
261
+ renderError((first && first.text) || "The tool answered with an error.");
262
+ } else if (params.structuredContent) {
263
+ render(params.structuredContent);
264
+ } else {
265
+ renderError("This result holds no VAT return.");
266
+ }
267
+ }
268
+ });
269
+
270
+ request("ui/initialize", {
271
+ appInfo: { name: "diya-submit-vat-review-card", version: "1.0.0" },
272
+ appCapabilities: {},
273
+ protocolVersion: PROTOCOL_VERSION,
274
+ }).then(
275
+ function () {
276
+ send({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
277
+ },
278
+ function () {
279
+ renderError("Your assistant did not start the card.");
280
+ },
281
+ );
282
+ })();
283
+ </script>
284
+ </body>
285
+ </html>
@@ -0,0 +1,59 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // @capability MCP-25 Show a VAT return as a card inside the assistant
5
+ // - **Use when:** an assistant that renders MCP Apps views should show the nine VAT boxes as a card with a button that opens the VAT form.
6
+ // - **Does:** vat-review-card.js serves vat-review-card.html as the ui:// resource that derive_vat_return and prepare_vat_return name in their _meta. The page is static HTML and script with no network call; it reads the tool result the host posts to it and draws the nine boxes, and for prepare_vat_return it asks the host to open the link.
7
+ // - **Run:** no command; an MCP Apps host reads the resource when it lists the tools
8
+ // - **Entry:** `mcp/lib/vat-review-card.js:registerVatReviewCard`; `mcp/lib/vat-review-card.html`
9
+ // - **Files:** mcp/lib/vat-review-card.js, mcp/lib/vat-review-card.html, mcp/test/vat-review-card.test.js
10
+ // - **Keywords:** mcp apps, ui resource, review card, vat boxes card, ui://, text/html;profile=mcp-app
11
+ // - **Related:** MCP-01, MCP-05, MCP-24
12
+ // @end-capability
13
+
14
+ // vat-review-card.js -- the review card's resource and the _meta the two VAT tools carry to name it.
15
+
16
+ import { readFileSync } from "node:fs";
17
+ import { dirname, resolve } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ export const VAT_REVIEW_CARD_URI = "ui://diya-submit/vat-review-card.html";
21
+ export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
22
+
23
+ // The tools that show the card; the resource is registered only when one of them is.
24
+ export const VAT_REVIEW_CARD_TOOLS = ["derive_vat_return", "prepare_vat_return"];
25
+
26
+ export const VAT_REVIEW_CARD_TOOL_META = { ui: { resourceUri: VAT_REVIEW_CARD_URI } };
27
+
28
+ const CARD_HTML_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "vat-review-card.html");
29
+
30
+ export function vatReviewCardHtml() {
31
+ return readFileSync(CARD_HTML_PATH, "utf8");
32
+ }
33
+
34
+ /**
35
+ * Registers the card's ui:// resource on the server. The empty domain lists state the card's
36
+ * content security policy: it loads nothing and connects to nothing.
37
+ * @param {import("@modelcontextprotocol/sdk/server/mcp.js").McpServer} server
38
+ */
39
+ export function registerVatReviewCard(server) {
40
+ server.registerResource(
41
+ "vat-review-card",
42
+ VAT_REVIEW_CARD_URI,
43
+ {
44
+ title: "VAT return review card",
45
+ description: "The nine VAT boxes of a derived return as a card, with a button that opens the VAT form to check and file.",
46
+ mimeType: MCP_APP_MIME_TYPE,
47
+ },
48
+ async (uri) => ({
49
+ contents: [
50
+ {
51
+ uri: uri.href,
52
+ mimeType: MCP_APP_MIME_TYPE,
53
+ text: vatReviewCardHtml(),
54
+ _meta: { ui: { prefersBorder: true, csp: { connectDomains: [], resourceDomains: [] } } },
55
+ },
56
+ ],
57
+ }),
58
+ );
59
+ }
package/lib/vat-tools.js CHANGED
@@ -13,10 +13,20 @@
13
13
 
14
14
  // vat-tools.js -- derive_vat_return: the nine VAT boxes for one obligation
15
15
  // period from the session's loaded book. The derivation is the diya-gl
16
- // package's own; this module adds only the session's "no book loaded" check.
16
+ // package's own; this module adds the session's "no book loaded" check and
17
+ // keeps of each journal line only what a person checks a box against.
17
18
 
18
19
  import { deriveVatReturn as deriveVatReturnFromBook } from "@diy-accounting-uk/diya-gl";
19
20
 
21
+ // The fields of a journal line behind a box. The engine also answers the line's entry and line
22
+ // numbers, which are the book's own keys (a bank or Stripe transaction id among them), so the
23
+ // tool leaves them out: the date, reference, counterparty and amount find the line in the book.
24
+ const LINE_FIELDS = ["date", "account", "reference", "counterparty", "gross", "contributes"];
25
+
26
+ function lineForPerson(line) {
27
+ return Object.fromEntries(LINE_FIELDS.map((field) => [field, line[field] ?? null]));
28
+ }
29
+
20
30
  /**
21
31
  * derive_vat_return: the nine boxes for the quarter ending on periodEnd,
22
32
  * from the session's loaded book.
@@ -27,5 +37,7 @@ export async function deriveVatReturn(session, params = {}) {
27
37
  if (!session.book || !session.lines) {
28
38
  throw new Error("No book is loaded. Call open_book first.");
29
39
  }
30
- return deriveVatReturnFromBook(session.book, session.lines, params);
40
+ const derived = await deriveVatReturnFromBook(session.book, session.lines, params);
41
+ const lines = Object.fromEntries(Object.entries(derived.lines).map(([box, boxLines]) => [box, boxLines.map(lineForPerson)]));
42
+ return { ...derived, lines };
31
43
  }
@@ -26,8 +26,8 @@ import {
26
26
  financialYearsInPeriod,
27
27
  } from "@diy-accounting-uk/diya-gl/dist/app/lib/tax/corporation-tax.js";
28
28
 
29
- export const EARLIEST_PERIOD_START = "2015-04-01";
30
- export const WORKING_SHEET_TOLERANCE_POUNDS = 5;
29
+ const EARLIEST_PERIOD_START = "2015-04-01";
30
+ const WORKING_SHEET_TOLERANCE_POUNDS = 5;
31
31
 
32
32
  const EXCEL_EPOCH_MS = Date.UTC(1899, 11, 30);
33
33
  const DAY_MS = 86_400_000;
@@ -52,7 +52,38 @@ function isIsoDate(value) {
52
52
  return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && utcDate(value).toISOString().slice(0, 10) === value;
53
53
  }
54
54
 
55
- function lastDayOfTwelveMonths(isoStart) {
55
+ export function daysInclusive(isoStart, isoEnd) {
56
+ return Math.round((utcDate(isoEnd).getTime() - utcDate(isoStart).getTime()) / DAY_MS) + 1;
57
+ }
58
+
59
+ /**
60
+ * The most annual investment allowance a return can claim: 1,000,000 for a year, increased or
61
+ * reduced in proportion to the return's days over the days in the 12 months from its start
62
+ * (CAA 2001 section 51A(6)). The books bundle re-exports it (`scripts/build-books-bundle.mjs`).
63
+ * @public
64
+ */
65
+ export function annualInvestmentAllowanceMaximum(periodStart, periodEnd) {
66
+ const daysInTwelveMonths = daysInclusive(periodStart, lastDayOfTwelveMonths(periodStart));
67
+ return (1_000_000 * daysInclusive(periodStart, periodEnd)) / daysInTwelveMonths;
68
+ }
69
+
70
+ /**
71
+ * Each financial year's small profits and marginal relief limits, scaled to the accounting period
72
+ * (CTA 2010 section 18D(4)). The apportioning code multiplies a year's limits by that year's share
73
+ * of the period, so the limits here carry the period's days over the larger of the financial year's
74
+ * days and the period's days: a period of 90 days gets 90/365 of each limit, and a period of 12
75
+ * months or more keeps the full limits. This is HMRC's marginal relief calculator's ratio.
76
+ */
77
+ function limitsScaledToPeriod(perYear, years, totalDays) {
78
+ return perYear.map((rates, index) => {
79
+ const financialYear = years[index].year;
80
+ const daysInFinancialYear = daysInclusive(`${financialYear}-04-01`, `${financialYear + 1}-03-31`);
81
+ const scale = totalDays / Math.max(daysInFinancialYear, totalDays);
82
+ return { ...rates, lowerLimit: rates.lowerLimit * scale, upperLimit: rates.upperLimit * scale };
83
+ });
84
+ }
85
+
86
+ export function lastDayOfTwelveMonths(isoStart) {
56
87
  const date = utcDate(isoStart);
57
88
  date.setUTCFullYear(date.getUTCFullYear() + 1);
58
89
  date.setUTCDate(date.getUTCDate() - 1);
@@ -107,6 +138,8 @@ const WHOLE_POUND_FIELDS = [
107
138
  ["lossCarriedBack", "Trading loss carried back against the previous period's profits"],
108
139
  ["priorPeriodChargeableProfits", "The previous period's chargeable profits (box 315 of its return)"],
109
140
  ["frankedInvestmentIncome", "Franked investment income or exempt ABGH distributions (box 620)"],
141
+ ["donationsPaid", "Qualifying donations paid in the period (box 305)"],
142
+ ["lossCarriedBackFromLaterPeriod", "Trading loss carried back from the next accounting period (box 275)"],
110
143
  ];
111
144
 
112
145
  const PENCE_FIELDS = [
@@ -201,6 +234,16 @@ function figureProblems(figures, { today } = {}) {
201
234
  ) {
202
235
  problem("donations", "Donations added back are more than the cost of sales and administrative expenses");
203
236
  }
237
+ if (isIsoDate(figures.periodStart) && isIsoDate(figures.periodEnd) && figures.periodEnd >= figures.periodStart) {
238
+ const maximum = Math.floor(annualInvestmentAllowanceMaximum(figures.periodStart, figures.periodEnd));
239
+ if (numberOrZero(figures.annualInvestmentAllowance) > maximum) {
240
+ problem(
241
+ "annualInvestmentAllowance",
242
+ `The annual investment allowance of a ${daysInclusive(figures.periodStart, figures.periodEnd)}-day period can be ${maximum.toLocaleString("en-GB")} at most.`,
243
+ true,
244
+ );
245
+ }
246
+ }
204
247
  if (numberOrZero(figures.specialRatePoolAnnualInvestmentAllowance) > numberOrZero(figures.annualInvestmentAllowance)) {
205
248
  problem(
206
249
  "specialRatePoolAnnualInvestmentAllowance",
@@ -278,7 +321,11 @@ function capitalAllowanceClassLines(figures) {
278
321
  * above it, so the computation adds up.
279
322
  *
280
323
  * @param {object} figures
281
- * @returns {{profitLossPerAccounts: number, nonTradingLoanRelationshipCredits: number, depreciation: number, amortisation: number, entertaining: number, donations: number, adjustedProfitBeforeCapitalAllowances: number, totalCapitalAllowances: number, adjustedProfit: number}} a loss is a negative adjustedProfit
324
+ * A return that is one accounting period of a longer period of account (figures.periodOfAccount)
325
+ * keeps the lines of the whole period of account down to adjustedProfitBeforeAccountingPeriodAdjustments,
326
+ * then timeApportionment takes the profit to the accounting period's share of it.
327
+ *
328
+ * @returns {{profitLossPerAccounts: number, nonTradingLoanRelationshipCredits: number, depreciation: number, amortisation: number, entertaining: number, donations: number, adjustedProfitBeforeAccountingPeriodAdjustments?: number, timeApportionment?: number, adjustedProfitBeforeCapitalAllowances: number, totalCapitalAllowances: number, adjustedProfit: number}} a loss is a negative adjustedProfit
282
329
  */
283
330
  export function computationLinesFromFigures(figures) {
284
331
  const lines = {
@@ -291,6 +338,12 @@ export function computationLinesFromFigures(figures) {
291
338
  };
292
339
  lines.adjustedProfitBeforeCapitalAllowances =
293
340
  lines.profitLossPerAccounts + COMPUTATION_ADJUSTMENTS.reduce((total, [key, effect]) => total + effect * lines[key], 0);
341
+ if (figures.periodOfAccount) {
342
+ const apportioned = figures.periodOfAccount.apportioned.adjustedProfitBeforeCapitalAllowances;
343
+ lines.adjustedProfitBeforeAccountingPeriodAdjustments = lines.adjustedProfitBeforeCapitalAllowances;
344
+ lines.timeApportionment = apportioned - lines.adjustedProfitBeforeCapitalAllowances;
345
+ lines.adjustedProfitBeforeCapitalAllowances = apportioned;
346
+ }
294
347
  Object.assign(lines, capitalAllowanceClassLines(figures));
295
348
  lines.totalCapitalAllowances =
296
349
  numberOrZero(figures.annualInvestmentAllowance) +
@@ -440,7 +493,11 @@ function workLosses({ figures, tradingLoss, profitsBeforeOtherDeductions, losses
440
493
  }
441
494
 
442
495
  function corporationTaxPenceOn(profits, years, totalDays, { taxData, fileFinancialYear, associatedCompanies }) {
443
- const perYear = years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days));
496
+ const perYear = limitsScaledToPeriod(
497
+ years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days)),
498
+ years,
499
+ totalDays,
500
+ );
444
501
  const charge = apportionCorporationTax(profits, years, totalDays, { perYear, associatedCompanies });
445
502
  const firstShare = years[1].days > 0 ? Math.round((profits * years[0].days) / totalDays) : profits;
446
503
  const shares = [firstShare, profits - firstShare];
@@ -512,7 +569,7 @@ function rimRateOn(isoDate) {
512
569
  return rate;
513
570
  }
514
571
 
515
- function addDays(isoDate, days) {
572
+ export function addDays(isoDate, days) {
516
573
  const date = utcDate(isoDate);
517
574
  date.setUTCDate(date.getUTCDate() + days);
518
575
  return date.toISOString().slice(0, 10);
@@ -523,7 +580,7 @@ function isMonthEnd(isoDate) {
523
580
  }
524
581
 
525
582
  // The same day of the month `months` later, or its last day when that month is shorter.
526
- function addMonths(isoDate, months) {
583
+ export function addMonths(isoDate, months) {
527
584
  const date = utcDate(isoDate);
528
585
  const day = date.getUTCDate();
529
586
  date.setUTCDate(1);
@@ -696,6 +753,7 @@ function section455RateOf(taxDataByYear, year) {
696
753
  * @param {string} periodEnd - ISO date
697
754
  * @param {Record<number, object>} taxDataByYear
698
755
  * @returns {string|undefined}
756
+ * @public The books bundle re-exports it (`scripts/build-books-bundle.mjs`).
699
757
  */
700
758
  export function section455RateChangeDate(periodStart, periodEnd, taxDataByYear) {
701
759
  const startYear = taxYearStartOf(periodStart);
@@ -751,7 +809,7 @@ function rimRate() {
751
809
  * @param {{today?: string}} [options] - ISO date; a repayment cannot come after it
752
810
  * @returns {{ct600a: object|undefined, a80Pence: number}}
753
811
  */
754
- export function workLoansToParticipators(figures, boxes, worked, taxDataByYear, { today } = {}) {
812
+ function workLoansToParticipators(figures, boxes, worked, taxDataByYear, { today } = {}) {
755
813
  const loans = figures.loansToParticipators;
756
814
  if (!loans) return { ct600a: undefined, a80Pence: 0 };
757
815
  const problems = loansProblems(figures, { today });
@@ -963,7 +1021,9 @@ function workProfitsAndReliefs(figures, computationLines, boxes, worked) {
963
1021
  boxes[165] = tradingProfit - broughtForwardUsedAgainstTrading;
964
1022
  worked[165] = workedEntry(["155", "160"]);
965
1023
  }
966
- const bankInterest = computationLines.nonTradingLoanRelationshipCredits;
1024
+ const bankInterest = figures.periodOfAccount
1025
+ ? figures.periodOfAccount.apportioned.nonTradingLoanRelationshipCredits
1026
+ : computationLines.nonTradingLoanRelationshipCredits;
967
1027
  if (bankInterest > 0) boxes[170] = bankInterest;
968
1028
  const profitsBeforeOtherDeductions = (boxes[165] ?? 0) + (boxes[170] ?? 0);
969
1029
  if (profitsBeforeOtherDeductions > 0) {
@@ -979,19 +1039,32 @@ function workProfitsAndReliefs(figures, computationLines, boxes, worked) {
979
1039
  "The loss arising is the computation's adjusted loss",
980
1040
  );
981
1041
  }
982
- if (losses.usedAgainstTotalProfits > 0) boxes[275] = losses.usedAgainstTotalProfits;
1042
+ const lossFromLaterPeriod = numberOrZero(figures.lossCarriedBackFromLaterPeriod);
1043
+ if (lossFromLaterPeriod > profitsBeforeOtherDeductions - losses.usedAgainstTotalProfits - losses.broughtForwardAgainstTotalProfits) {
1044
+ refuseLoss(
1045
+ `The loss carried back from the next accounting period ${lossFromLaterPeriod} is more than the profits this period's other claims leave`,
1046
+ "lossCarriedBackFromLaterPeriod",
1047
+ );
1048
+ }
1049
+ const claimedAgainstTotalProfits = losses.usedAgainstTotalProfits + lossFromLaterPeriod;
1050
+ if (claimedAgainstTotalProfits > 0) boxes[275] = claimedAgainstTotalProfits;
1051
+ if (lossFromLaterPeriod > 0) boxes[280] = "yes";
983
1052
  if (losses.broughtForwardAgainstTotalProfits > 0) boxes[285] = losses.broughtForwardAgainstTotalProfits;
984
- const deductionsAndReliefs = losses.usedAgainstTotalProfits + losses.broughtForwardAgainstTotalProfits;
1053
+ const deductionsAndReliefs = claimedAgainstTotalProfits + losses.broughtForwardAgainstTotalProfits;
985
1054
  if (deductionsAndReliefs > 0) {
986
1055
  boxes[295] = deductionsAndReliefs;
987
- worked[295] = workedEntry(["lossAgainstTotalProfits", "lossesBroughtForwardAgainstTotalProfits"], "Box 295 is boxes 275 and 285");
1056
+ worked[295] = workedEntry(
1057
+ ["lossAgainstTotalProfits", "lossCarriedBackFromLaterPeriod", "lossesBroughtForwardAgainstTotalProfits"],
1058
+ "Box 295 is boxes 275 and 285",
1059
+ );
988
1060
  }
989
1061
  const profitsBeforeDonations = profitsBeforeOtherDeductions - deductionsAndReliefs;
990
1062
  if (profitsBeforeOtherDeductions > 0) {
991
1063
  boxes[300] = profitsBeforeDonations;
992
1064
  worked[300] = workedEntry(["235", "295"], "Box 300 is box 235 less box 295");
993
1065
  }
994
- const qualifyingDonations = Math.min(computationLines.donations, Math.max(profitsBeforeDonations, 0));
1066
+ const donationsPaid = figures.donationsPaid === undefined ? computationLines.donations : figures.donationsPaid;
1067
+ const qualifyingDonations = Math.min(donationsPaid, Math.max(profitsBeforeDonations, 0));
995
1068
  if (qualifyingDonations > 0) {
996
1069
  boxes[305] = qualifyingDonations;
997
1070
  worked[305] = workedEntry(["donations", "300"], "Donations are claimed up to the profits in box 300");
@@ -1013,7 +1086,7 @@ function workProfitsAndReliefs(figures, computationLines, boxes, worked) {
1013
1086
  * @param {Record<number, object>} taxDataByYear - parsed ltd-<FY>.toml files by financial year; the one named for the period end's financial year is required
1014
1087
  * @param {object} [options]
1015
1088
  * @param {string} [options.today] - ISO date; a repayment of a loan to a participator cannot come after it
1016
- * @returns {{boxes: Record<number, string|number>, ct600a: object|undefined, computationLines: object, losses: object, carryBack: object|undefined, worked: Record<number, {sources: string[], rule?: string}>, periodStart: string, periodEnd: string}}
1089
+ * @returns {{boxes: Record<number|string, string|number>, ct600a: object|undefined, computationLines: object, losses: object, carryBack: object|undefined, worked: Record<number, {sources: string[], rule?: string}>, periodStart: string, periodEnd: string, periodOfAccount?: {periodStart: string, periodEnd: string, days: number}}}
1017
1090
  */
1018
1091
  export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
1019
1092
  const problems = figureProblems(figures);
@@ -1032,11 +1105,16 @@ export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
1032
1105
  4: numberOrZero(figures.companyType),
1033
1106
  30: periodStart,
1034
1107
  35: periodEnd,
1035
- 145: figures.profitAndLoss.current.turnover,
1108
+ 145: figures.periodOfAccount ? figures.periodOfAccount.apportioned.turnover : figures.profitAndLoss.current.turnover,
1036
1109
  975: figures.declarantName.trim(),
1037
1110
  985: figures.declarantStatus.trim(),
1038
1111
  };
1039
1112
 
1113
+ if (figures.periodOfAccount) {
1114
+ boxes[50] = "yes";
1115
+ boxes["85A"] = "yes";
1116
+ }
1117
+
1040
1118
  const workingSheet = figures.workingSheet;
1041
1119
  if (workingSheet && Math.abs(computationLines.adjustedProfit - workingSheet.tradingProfit) > WORKING_SHEET_TOLERANCE_POUNDS) {
1042
1120
  throw new Ct600RefusedError(
@@ -1069,7 +1147,11 @@ export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
1069
1147
  const fileFinancialYear = financialYearNumber(utcDate(periodEnd));
1070
1148
  const taxData = taxDataByYear?.[fileFinancialYear];
1071
1149
  if (!taxData) throw new Ct600RefusedError(`No tax data is held for the financial year ${fileFinancialYear}`, "period");
1072
- const perYear = years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days));
1150
+ const perYear = limitsScaledToPeriod(
1151
+ years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days)),
1152
+ years,
1153
+ totalDays,
1154
+ );
1073
1155
  const charge = apportionCorporationTax(chargeableProfits, years, totalDays, { perYear, associatedCompanies, frankedInvestmentIncome });
1074
1156
  const firstShare = straddles ? Math.round((chargeableProfits * years[0].days) / totalDays) : chargeableProfits;
1075
1157
  const shares = [firstShare, chargeableProfits - firstShare];
@@ -1171,5 +1253,18 @@ export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
1171
1253
  worked[600] = workedEntry(["525", "595"]);
1172
1254
 
1173
1255
  const carryBack = workCarryBack(figures, losses, taxDataByYear);
1174
- return { boxes, ct600a, computationLines, losses, carryBack, worked, periodStart, periodEnd };
1256
+ const periodOfAccount = figures.periodOfAccount
1257
+ ? { periodStart: figures.periodOfAccount.periodStart, periodEnd: figures.periodOfAccount.periodEnd, days: figures.periodOfAccount.days }
1258
+ : undefined;
1259
+ return {
1260
+ boxes,
1261
+ ct600a,
1262
+ computationLines,
1263
+ losses,
1264
+ carryBack,
1265
+ worked,
1266
+ periodStart,
1267
+ periodEnd,
1268
+ ...(periodOfAccount ? { periodOfAccount } : {}),
1269
+ };
1175
1270
  }
@@ -39,9 +39,20 @@ export async function deriveCompanyBookFigures(session, { requireDirectorsNote =
39
39
  return {
40
40
  accounts: microEntityAccountsFromResults(book, results, scenario, { requireDirectorsNote }),
41
41
  cashAtBank: cashAtBankFromResults(results),
42
+ cashAsOf: lastPostingDate(lines),
42
43
  };
43
44
  }
44
45
 
46
+ /** The date of the book's last transaction, as YYYY-MM-DD, or null when no line carries a posting date. */
47
+ export function lastPostingDate(lines) {
48
+ let latest = null;
49
+ for (const line of lines) {
50
+ const day = typeof line.postingDate === "string" ? line.postingDate.slice(0, 10) : null;
51
+ if (day && (latest === null || day > latest)) latest = day;
52
+ }
53
+ return latest;
54
+ }
55
+
45
56
  /**
46
57
  * derive_micro_entity_accounts: the figures the accounts filing takes, from
47
58
  * the session's loaded book.
@@ -210,7 +210,7 @@ export function roundSmallCompanyBalanceSheet(lines) {
210
210
  * notes, in whole pounds with each class's closing net book value rounded from its own movements.
211
211
  * @param {Object} sheet - results.PubNotes
212
212
  */
213
- export function fixedAssetNoteFromPublishedNotes(sheet) {
213
+ function fixedAssetNoteFromPublishedNotes(sheet) {
214
214
  const note = {};
215
215
  for (const className of Object.keys(NOTE_COLUMN_OF_CLASS)) {
216
216
  const column = NOTE_COLUMN_OF_CLASS[className];