@diy-accounting-uk/diya-gl 1.0.0

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.
Files changed (157) hide show
  1. package/README.md +63 -0
  2. package/bin/diya-gl-mcp.js +10 -0
  3. package/bin/diya-gl-read-workbook.js +11 -0
  4. package/bin/diya-gl-recalc.js +10 -0
  5. package/bin/diya-gl-write-workbook.js +12 -0
  6. package/bin/diya-gl.js +24 -0
  7. package/bin/run-dist-bin.js +23 -0
  8. package/dist/app/bin/build-diya-gl-spec.js +680 -0
  9. package/dist/app/bin/build-packages.js +149 -0
  10. package/dist/app/bin/build-reconciliation-pages.js +1052 -0
  11. package/dist/app/bin/build-sitemaps.js +51 -0
  12. package/dist/app/bin/compliance-report.js +125 -0
  13. package/dist/app/bin/cross-package-reconciliation.js +92 -0
  14. package/dist/app/bin/diya-gl-mcp.js +27 -0
  15. package/dist/app/bin/export.js +318 -0
  16. package/dist/app/bin/extract-scenarios.js +1348 -0
  17. package/dist/app/bin/generate.js +353 -0
  18. package/dist/app/bin/judge-reconciliation.js +649 -0
  19. package/dist/app/bin/reconcile.js +247 -0
  20. package/dist/app/bin/report.js +291 -0
  21. package/dist/app/bin/verify-roundtrip.js +941 -0
  22. package/dist/app/bin/verify-stability.js +429 -0
  23. package/dist/app/bin/write-workbook.js +106 -0
  24. package/dist/app/data/filing/ct-computation-v1.1.toml +1033 -0
  25. package/dist/app/data/filing/ct600-v3.toml +2329 -0
  26. package/dist/app/data/filing/frs105-formats.toml +244 -0
  27. package/dist/app/data/fixture-master-gaps.json +247 -0
  28. package/dist/app/data/hmrc/SOURCE.md +14 -0
  29. package/dist/app/data/hmrc/form-layouts/bst.json +116 -0
  30. package/dist/app/data/hmrc/form-layouts/ltd.json +452 -0
  31. package/dist/app/data/hmrc/form-layouts/se.json +485 -0
  32. package/dist/app/data/hmrc/form-layouts/taxi.json +117 -0
  33. package/dist/app/data/hmrc/sa103-mtd-mapping.json +1078 -0
  34. package/dist/app/data/hmrc/sa103f_mapping_v3.csv +111 -0
  35. package/dist/app/data/judge-rubric.md +52 -0
  36. package/dist/app/data/ltd-2020.toml +49 -0
  37. package/dist/app/data/ltd-2021.toml +49 -0
  38. package/dist/app/data/ltd-2022.toml +49 -0
  39. package/dist/app/data/ltd-2023.toml +49 -0
  40. package/dist/app/data/ltd-2024.toml +49 -0
  41. package/dist/app/data/ltd-2025.toml +49 -0
  42. package/dist/app/data/ltd-2026.toml +53 -0
  43. package/dist/app/data/ltd-2027.toml +51 -0
  44. package/dist/app/data/render-unrepresentable/bst.json +24 -0
  45. package/dist/app/data/render-unrepresentable/ltd.json +863 -0
  46. package/dist/app/data/render-unrepresentable/se.json +455 -0
  47. package/dist/app/data/render-unrepresentable/taxi.json +16 -0
  48. package/dist/app/data/roundtrip-budget.json +38 -0
  49. package/dist/app/data/roundtrip-matrix-budget.json +26 -0
  50. package/dist/app/data/roundtrip-unrepresentable.json +401 -0
  51. package/dist/app/data/se-2020-2021.toml +52 -0
  52. package/dist/app/data/se-2021-2022.toml +52 -0
  53. package/dist/app/data/se-2022-2023.toml +55 -0
  54. package/dist/app/data/se-2023-2024.toml +54 -0
  55. package/dist/app/data/se-2024-2025.toml +51 -0
  56. package/dist/app/data/se-2025-2026.toml +51 -0
  57. package/dist/app/data/se-2026-2027.toml +51 -0
  58. package/dist/app/data/volatile-cells.json +16 -0
  59. package/dist/app/lib/anchors/bst.js +79 -0
  60. package/dist/app/lib/anchors/ltd.js +626 -0
  61. package/dist/app/lib/anchors/run.js +100 -0
  62. package/dist/app/lib/anchors/se.js +456 -0
  63. package/dist/app/lib/anchors/taxi.js +164 -0
  64. package/dist/app/lib/app-resources.js +80 -0
  65. package/dist/app/lib/book-checks/ltd.js +408 -0
  66. package/dist/app/lib/book-checks/se.js +687 -0
  67. package/dist/app/lib/book-checks/taxi.js +215 -0
  68. package/dist/app/lib/book-checks.js +872 -0
  69. package/dist/app/lib/books-engine.js +197 -0
  70. package/dist/app/lib/books-interchange.js +533 -0
  71. package/dist/app/lib/calculators/bst.js +381 -0
  72. package/dist/app/lib/calculators/ltd.js +1938 -0
  73. package/dist/app/lib/calculators/se.js +1239 -0
  74. package/dist/app/lib/calculators/shared.js +131 -0
  75. package/dist/app/lib/calculators/taxi.js +461 -0
  76. package/dist/app/lib/canonical-report-value.js +77 -0
  77. package/dist/app/lib/compliance-report.js +341 -0
  78. package/dist/app/lib/diya-gl-calculator.js +52 -0
  79. package/dist/app/lib/diya-gl-canonical.js +355 -0
  80. package/dist/app/lib/diya-gl-edits-ltd.js +144 -0
  81. package/dist/app/lib/diya-gl-edits.js +361 -0
  82. package/dist/app/lib/diya-gl-loader.js +774 -0
  83. package/dist/app/lib/diya-gl-schema.js +212 -0
  84. package/dist/app/lib/generator.js +1912 -0
  85. package/dist/app/lib/guide.js +33 -0
  86. package/dist/app/lib/headlines.js +293 -0
  87. package/dist/app/lib/link-caches.js +421 -0
  88. package/dist/app/lib/ltd-layout.js +139 -0
  89. package/dist/app/lib/mcp/diya-gl-tools.js +330 -0
  90. package/dist/app/lib/mcp/jsonrpc-stdio.js +66 -0
  91. package/dist/app/lib/mcp/server.js +65 -0
  92. package/dist/app/lib/overtype-sidecar.js +180 -0
  93. package/dist/app/lib/package-builder.js +202 -0
  94. package/dist/app/lib/payslips-date-chain.js +481 -0
  95. package/dist/app/lib/payslips-layout.js +235 -0
  96. package/dist/app/lib/period-shift.js +111 -0
  97. package/dist/app/lib/product-workbook.js +317 -0
  98. package/dist/app/lib/products.js +27 -0
  99. package/dist/app/lib/provenance-data.js +36 -0
  100. package/dist/app/lib/provenance.js +92 -0
  101. package/dist/app/lib/report-generator.js +374 -0
  102. package/dist/app/lib/report-indicators.js +468 -0
  103. package/dist/app/lib/report-serializer.js +392 -0
  104. package/dist/app/lib/scenario-extractor.js +1403 -0
  105. package/dist/app/lib/scenario-loader.js +84 -0
  106. package/dist/app/lib/sitemap-builder.js +59 -0
  107. package/dist/app/lib/spreadsheet-runner.js +566 -0
  108. package/dist/app/lib/tax/capital-allowances.js +77 -0
  109. package/dist/app/lib/tax/corporation-tax.js +144 -0
  110. package/dist/app/lib/tax/income-tax.js +122 -0
  111. package/dist/app/lib/tax/mileage.js +69 -0
  112. package/dist/app/lib/tax/national-insurance.js +31 -0
  113. package/dist/app/lib/tax/vat.js +188 -0
  114. package/dist/app/lib/tax-year.js +31 -0
  115. package/dist/app/lib/template-formula-map.js +253 -0
  116. package/dist/app/lib/workbook-set.js +153 -0
  117. package/dist/app/lib/xlsx-exporter.js +2815 -0
  118. package/dist/app/lib/xlsx-parts.js +111 -0
  119. package/dist/app/lib/xlsx-reader.js +84 -0
  120. package/dist/app/products/bst.js +727 -0
  121. package/dist/app/products/ltd.js +4270 -0
  122. package/dist/app/products/se.js +3403 -0
  123. package/dist/app/products/taxi.js +912 -0
  124. package/dist/app/templates/bst/bst-excel.xlsx +0 -0
  125. package/dist/app/templates/bst/meta.toml +27 -0
  126. package/dist/app/templates/ltd/Cashaccount.xlsx +0 -0
  127. package/dist/app/templates/ltd/Companysecretary.xlsx +0 -0
  128. package/dist/app/templates/ltd/Creditcardaccount.xlsx +0 -0
  129. package/dist/app/templates/ltd/Currentaccount.xlsx +0 -0
  130. package/dist/app/templates/ltd/Dividend Voucher.docx +0 -0
  131. package/dist/app/templates/ltd/Financialaccounts.xlsx +0 -0
  132. package/dist/app/templates/ltd/Fixedassets.xlsx +0 -0
  133. package/dist/app/templates/ltd/Payslips.xlsx +0 -0
  134. package/dist/app/templates/ltd/Purchases.xlsx +0 -0
  135. package/dist/app/templates/ltd/Sales.xlsx +0 -0
  136. package/dist/app/templates/ltd/Salesinvoice.xlsx +0 -0
  137. package/dist/app/templates/ltd/Savingaccount.xlsx +0 -0
  138. package/dist/app/templates/ltd/Vatreturns.xlsx +0 -0
  139. package/dist/app/templates/ltd/expensesform.xlsx +0 -0
  140. package/dist/app/templates/ltd/meta.toml +54 -0
  141. package/dist/app/templates/meta.toml +12 -0
  142. package/dist/app/templates/se/Bank.xlsx +0 -0
  143. package/dist/app/templates/se/Cash.xlsx +0 -0
  144. package/dist/app/templates/se/Financialaccounts.xlsx +0 -0
  145. package/dist/app/templates/se/Fixedassets.xlsx +0 -0
  146. package/dist/app/templates/se/Payslips.xlsx +0 -0
  147. package/dist/app/templates/se/Purchases.xlsx +0 -0
  148. package/dist/app/templates/se/Sales.xlsx +0 -0
  149. package/dist/app/templates/se/Salesinvoice.xlsx +0 -0
  150. package/dist/app/templates/se/Vat.xlsx +0 -0
  151. package/dist/app/templates/se/meta.toml +43 -0
  152. package/dist/app/templates/taxi/meta.toml +43 -0
  153. package/dist/app/templates/taxi/taxi-excel.xlsx +0 -0
  154. package/dist/web/spreadsheets.diyaccounting.co.uk/public/schema/diya-gl-book-v2.schema.json +713 -0
  155. package/dist/web/spreadsheets.diyaccounting.co.uk/public/schema/diya-gl-docs.md +930 -0
  156. package/dist/web/spreadsheets.diyaccounting.co.uk/public/schema/diya-gl-lines-v2.schema.json +220 -0
  157. package/package.json +37 -0
@@ -0,0 +1,1239 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // se.js — JS calculation engine for the Self Employed product.
5
+ //
6
+ // The package is nine workbooks joined by external links, and this module
7
+ // computes every cell the reconciliation reads, the way those workbooks compute
8
+ // it. Each formula here was read out of the template XML: the journal month
9
+ // tabs' analysis columns, the profit and loss account's monthly grid, the fixed
10
+ // asset schedule, the payroll interface and calendar, the VAT interface and its
11
+ // five return forms, and the two self assessment returns.
12
+ //
13
+ // It works from the scenario, which is what the writer puts into the workbooks,
14
+ // so both engines start from the same figures and only the arithmetic between
15
+ // them is under test.
16
+
17
+ import { MONTH_SHEETS, extractTaxYearStart } from "../scenario-loader.js";
18
+ import { shiftMonths, periodShiftMonths } from "../period-shift.js";
19
+ import { standardReads, multiFileOptions, SE_YEAR_END_MONTH } from "../../products/se.js";
20
+ import { generateAdminDates, seVatPaymentDueDate, generatePayslipsCalendar } from "../generator.js";
21
+ import { calculateIncomeTax } from "../tax/income-tax.js";
22
+ import { calculateMileageAllowance } from "../tax/mileage.js";
23
+ import {
24
+ buildVatinterface,
25
+ splitVat,
26
+ straddlingPeriodTotals,
27
+ vatReturnBoxes,
28
+ vatReturnPeriodEnds,
29
+ VATINTERFACE_FIRST_ROW,
30
+ VATINTERFACE_LAST_ROW,
31
+ } from "../tax/vat.js";
32
+ import {
33
+ monthlyPayrollBlockRow,
34
+ PAYE_SCHEDULE_MONTH_TAB_CELLS,
35
+ payeTaxMonthDates,
36
+ payrollYearStart,
37
+ PAYSLIP_PRINT_CELLS,
38
+ PAYSLIP_PRINT_FIRST_PAYROLL_NUMBER,
39
+ PAYSLIP_PRINT_MONTHLY_HEADING,
40
+ PAYSLIP_PRINT_PERIOD,
41
+ PAYSLIP_PRINT_PERIOD_CELLS,
42
+ PAYSLIP_PRINT_SHEET,
43
+ PAYSLIP_PRINT_TO_DATE_CELLS,
44
+ PAYSLIPS_DIRECTLY_READ_MONTH_INDEXES,
45
+ PAYSLIPS_ENTRY_COLUMNS,
46
+ PAYSLIPS_ZERO_FILLED_COLUMNS,
47
+ payslipsMonthEntryRows,
48
+ payslipsWagesPaidCell,
49
+ } from "../payslips-layout.js";
50
+ import { SHEET_BLANK, sheetNumber, sheetSum, excelSerial, dateFromExcelSerial } from "./shared.js";
51
+
52
+ // The twelve month tabs, in the order the package lays them out, and the profit
53
+ // and loss account column each one feeds.
54
+ const MONTH_KEYS = ["apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "jan", "feb", "mar"];
55
+ const MONTH_COLS = ["C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"];
56
+
57
+ // Wagesinterface and Payslips!Payment both hold one row per month, April at row
58
+ // 4 through March at row 15.
59
+ const WAGES_MONTH_ROWS = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
60
+
61
+ // The rate a Sales month tab charges, held in H2 as a percentage. A business
62
+ // that is not registered writes nil there and the whole book follows.
63
+ const VAT_RATE = 0.2;
64
+
65
+ // Each Sales month tab's analysis column, by the code letter its own row 4
66
+ // carries. Every column holds the row's net figure.
67
+ export const SALES_ANALYSIS_COLUMNS = { a: "P", b: "Q", c: "R", d: "S", g: "T", o: "U", fs: "V" };
68
+
69
+ // The same on a Purchases month tab. AD is the CIS certificates column, which
70
+ // takes the tax withheld rather than a net figure and sits outside the sheet's
71
+ // own analysis check total.
72
+ export const PURCHASES_ANALYSIS_COLUMNS = {
73
+ s: "P",
74
+ c: "Q",
75
+ o: "R",
76
+ w: "S",
77
+ p: "T",
78
+ m: "U",
79
+ g: "V",
80
+ v: "W",
81
+ h: "X",
82
+ a: "Y",
83
+ l: "Z",
84
+ y: "AA",
85
+ fa: "AB",
86
+ };
87
+
88
+ // Bank.xlsx and Cash.xlsx analyse a receipt and a payment under different code
89
+ // letters, and the same letter means opposite things on the two sides, so each
90
+ // block carries its own map. Read out of each sheet's own row 5.
91
+ const BANK_LAYOUTS = {
92
+ "Bank.xlsx": {
93
+ receiptColumns: { BC: "G", DR: "H", CR: "I", K: "J", RV: "K", DL: "L", X: "M" },
94
+ paymentColumns: { BC: "U", CR: "V", DR: "W", W: "X", B: "Y", J: "Z", RP: "AA", DL: "AB", X: "AC" },
95
+ },
96
+ "Cash.xlsx": {
97
+ receiptColumns: { BB: "G", DR: "H", CR: "I", DL: "J" },
98
+ paymentColumns: { BB: "R", CR: "S", DR: "T", W: "U", J: "V", RP: "W", DL: "X" },
99
+ },
100
+ };
101
+
102
+ // Both Self Employed bank books carry one HMRC payments column, so a payment
103
+ // coded for VAT, CIS or corporation tax lands in it beside the PAYE payments.
104
+ const SE_HMRC_PAYMENT_CODE = "RP";
105
+ const COMPANY_TAX_PAYMENT_CODES = new Set(["RV", "RC", "RT"]);
106
+
107
+ // The Schedule rows each kind of asset lands on, and the Admin depreciation
108
+ // rate the block's own header cell reads.
109
+ const EXISTING_ASSET_BLOCKS = {
110
+ computer: { rows: [30, 31, 32, 33, 34], rateKey: "computer_equipment" },
111
+ motor: { rows: [38, 39, 40, 41, 42], rateKey: "motor_vehicles" },
112
+ };
113
+ const NEW_PLANT_ROW_COUNT = 5;
114
+
115
+ // The sample carriage charge cellWrites puts on the invoice's Invoice
116
+ // Database!E2 for a VAT-registered scenario (app/products/se.js).
117
+ const SALESINVOICE_SAMPLE_CARRIAGE_CHARGE = 37.5;
118
+
119
+ // The Payslips calendar rows the reconciliation samples, and the month names
120
+ // the sheet's own TEXT(DATE(...)) formula produces.
121
+ const PAYROLL_CALENDAR_SAMPLE_ROWS = [2, 33, 64, 95, 126, 157, 188, 219, 250, 281, 312, 343, 366, 381];
122
+ const SHORT_MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
123
+
124
+ // The StockControl physical-count cells for the two ends of the year.
125
+ const STOCK_OPENING_COUNT_CELL = "AB6";
126
+ const STOCK_CLOSING_COUNT_CELL = "AB30";
127
+
128
+ // The two HPfinance rows a scenario's agreements land on.
129
+ const HP_AGREEMENT_ROWS = [8, 10];
130
+
131
+ /**
132
+ * A scenario says whether the business is registered in its own metadata.
133
+ * Anything that does not say is registered.
134
+ */
135
+ function vatRateFor(scenario) {
136
+ return scenario?.metadata?.vat_registered === false ? 0 : VAT_RATE;
137
+ }
138
+
139
+ function paymentCodeFor(code) {
140
+ return COMPANY_TAX_PAYMENT_CODES.has(code) ? SE_HMRC_PAYMENT_CODE : code;
141
+ }
142
+
143
+ function businessName(scenario) {
144
+ return scenario.business?.name || scenario.metadata?.name || "";
145
+ }
146
+
147
+ function ledgerTotal(entries) {
148
+ return (entries || []).reduce((total, entry) => total + entry.amount, 0);
149
+ }
150
+
151
+ // The schedule holds a cost rounded to the penny, so the writer rounds a gross
152
+ // figure to the penny on its way onto a row.
153
+ function roundedNetOfVat(gross, rate) {
154
+ return Math.round((gross / (1 + rate)) * 100) / 100;
155
+ }
156
+
157
+ // ── The journal month tabs ─────────────────────────────────────────────────
158
+
159
+ /**
160
+ * One month tab of a sales or purchase journal: the gross, VAT and net totals
161
+ * its row 1 holds, each analysis column's own total, and the CIS tax withheld.
162
+ */
163
+ function journalMonth(transactions, rate, analysisColumns, defaultCode) {
164
+ const totals = { gross: 0, vat: 0, net: 0, byCode: {}, cis: 0 };
165
+ for (const tx of transactions || []) {
166
+ // A mileage-log row states miles where a bought purchase states an
167
+ // amount, and the sheet prices those miles itself. Its own figure never
168
+ // reaches a cell, so it is left out here and the claim added below.
169
+ if (tx.mileage) continue;
170
+ const { vat, net } = splitVat(tx.amount, rate);
171
+ totals.gross += tx.amount;
172
+ totals.vat += vat;
173
+ totals.net += net;
174
+ const code = tx.code || defaultCode;
175
+ if (analysisColumns[code] !== undefined) totals.byCode[code] = (totals.byCode[code] || 0) + net;
176
+ if (tx.cis_deduction) totals.cis += tx.cis_deduction;
177
+ }
178
+ return totals;
179
+ }
180
+
181
+ function journalMonths(journal, rate, analysisColumns, defaultCode) {
182
+ return MONTH_KEYS.map((month) => journalMonth(journal?.[month], rate, analysisColumns, defaultCode));
183
+ }
184
+
185
+ // The business miles one month's transactions carry.
186
+ function monthMiles(transactions) {
187
+ return (transactions || []).reduce((miles, tx) => miles + (typeof tx.mileage === "number" ? tx.mileage : 0), 0);
188
+ }
189
+
190
+ /**
191
+ * The mileage cells row 2 of each Purchases month tab holds: C2 the running
192
+ * business miles, which pools the month's own D column with the Sales month's
193
+ * D1 (C2 = <the month before>!C2 + D1 + [1]<month>!$D$1); G2 the claim that
194
+ * month adds, banded at the Admin rates; and A2 the claim to date
195
+ * (A2 = G2 + <the month before>!A2).
196
+ *
197
+ * I2 = G2 puts the claim in the month's net column, W2 = IF(F2="v",I2," ")
198
+ * files it under Motor Expenses, and G1/I1 carry it into the month's own
199
+ * totals, so the claim reaches the profit and loss account with no VAT
200
+ * stripped off it.
201
+ */
202
+ function mileageMonths(scenario, mileageRates) {
203
+ let milesToDate = 0;
204
+ let claimedToDate = 0;
205
+ return MONTH_KEYS.map((month) => {
206
+ const miles = monthMiles(scenario.sales?.[month]) + monthMiles(scenario.purchases?.[month]);
207
+ milesToDate += miles;
208
+ const claimToDate = mileageRates ? calculateMileageAllowance(milesToDate, mileageRates) : 0;
209
+ const claim = claimToDate - claimedToDate;
210
+ claimedToDate = claimToDate;
211
+ return { miles: milesToDate, claim, claimToDate };
212
+ });
213
+ }
214
+
215
+ // The year's net total for one code, as the last month tab's own running cell
216
+ // holds it.
217
+ function journalCodeTotal(journal, code, rate) {
218
+ let total = 0;
219
+ for (const transactions of Object.values(journal || {})) {
220
+ for (const tx of transactions) {
221
+ if (tx.code !== code) continue;
222
+ total += splitVat(tx.amount, rate).net;
223
+ }
224
+ }
225
+ return total;
226
+ }
227
+
228
+ // Row 1 of a journal month tab's analysis block: one net total per code column.
229
+ function analysisTotals(month, analysisColumns) {
230
+ const cells = {};
231
+ for (const [code, column] of Object.entries(analysisColumns)) cells[`${column}1`] = month.byCode[code] || 0;
232
+ return cells;
233
+ }
234
+
235
+ // One analysis column's running total, tab by tab: April's is its own figure
236
+ // and every later tab adds the month before it.
237
+ function runningTotals(months, code) {
238
+ let total = 0;
239
+ return months.map((month) => (total += month.byCode[code] || 0));
240
+ }
241
+
242
+ // ── Bank and cash ──────────────────────────────────────────────────────────
243
+
244
+ /**
245
+ * One bank workbook's twelve month tabs: the receipts and payments each code
246
+ * column carries, and the running balance A1 and A2 hold.
247
+ *
248
+ * An opening balance entry is written straight into its month's A1, replacing
249
+ * the formula that would otherwise carry the month before it forward.
250
+ */
251
+ function bankBook(bankJournal, fileName) {
252
+ const layout = BANK_LAYOUTS[fileName];
253
+ const months = MONTH_KEYS.map(() => ({
254
+ receipts: 0,
255
+ payments: 0,
256
+ receiptsByCode: {},
257
+ paymentsByCode: {},
258
+ openingWritten: null,
259
+ }));
260
+
261
+ for (const [monthKey, transactions] of Object.entries(bankJournal || {})) {
262
+ const index = MONTH_KEYS.indexOf(monthKey);
263
+ if (index === -1) continue;
264
+ for (const tx of transactions) {
265
+ const file = (tx.account || "1200") === "1220" ? "Cash.xlsx" : "Bank.xlsx";
266
+ if (file !== fileName) continue;
267
+ const month = months[index];
268
+ if (tx.code === "BC") {
269
+ month.openingWritten = (month.openingWritten || 0) + tx.amount;
270
+ continue;
271
+ }
272
+ if (tx.direction === "in") {
273
+ month.receipts += tx.amount;
274
+ if (layout.receiptColumns[tx.code]) month.receiptsByCode[tx.code] = (month.receiptsByCode[tx.code] || 0) + tx.amount;
275
+ } else if (tx.direction === "out") {
276
+ const code = paymentCodeFor(tx.code);
277
+ month.payments += tx.amount;
278
+ if (layout.paymentColumns[code]) month.paymentsByCode[code] = (month.paymentsByCode[code] || 0) + tx.amount;
279
+ }
280
+ }
281
+ }
282
+
283
+ let carried = 0;
284
+ for (const month of months) {
285
+ month.opening = month.openingWritten === null ? carried : month.openingWritten;
286
+ month.closing = month.opening + month.receipts - month.payments;
287
+ carried = month.closing;
288
+ }
289
+ return months;
290
+ }
291
+
292
+ // Every month tab of a bank workbook: the running balance in A1 and A2 and, on
293
+ // row 1, each analysis column's own total.
294
+ function bankMonthTabs(fileName, months) {
295
+ const layout = BANK_LAYOUTS[fileName];
296
+ const tabs = {};
297
+ months.forEach((month, index) => {
298
+ const cells = { A1: month.opening, A2: month.closing };
299
+ for (const [code, column] of Object.entries(layout.receiptColumns)) cells[`${column}1`] = month.receiptsByCode[code] || 0;
300
+ for (const [code, column] of Object.entries(layout.paymentColumns)) cells[`${column}1`] = month.paymentsByCode[code] || 0;
301
+ tabs[`${fileName}!${MONTH_SHEETS[MONTH_KEYS[index]]}`] = cells;
302
+ });
303
+ return tabs;
304
+ }
305
+
306
+ const bankPayments = (months, index, code) => months[index].paymentsByCode[code] || 0;
307
+ const bankReceipts = (months, index, code) => months[index].receiptsByCode[code] || 0;
308
+
309
+ // ── Payroll ────────────────────────────────────────────────────────────────
310
+
311
+ // The rows a month tab's weekly blocks keep for an employee paid weekly, and
312
+ // the row the last of them totals into. Every fixture pays monthly, so the
313
+ // weekly gate never reads true and these resolve to the sheet's own
314
+ // not-carried-forward branch: nil where the template holds a figure, blank
315
+ // where it holds text, which is why neither engine carries the M column.
316
+ const PAYSLIPS_WEEKLY_ROWS = [11, 12, 13, 14, 15];
317
+ const PAYSLIPS_WEEKLY_PERIOD_TOTAL_CELL = "T41";
318
+ const PAYSLIPS_BROUGHT_FORWARD_COLUMNS = ["H", "I", "J", "L"];
319
+ const PAYSLIPS_BROUGHT_FORWARD_LATE_COLUMN = { column: "K", firstRow: 12 };
320
+ // The weekly employee line each row of position 3 keeps, and the payslip
321
+ // total position 4 would bring forward: text cells, so the sheet's own
322
+ // unfilled branch leaves a blank rather than a nil.
323
+ const PAYSLIPS_WEEKLY_TEXT_COLUMN = { 3: PAYSLIPS_ENTRY_COLUMNS.name, 4: PAYSLIPS_ENTRY_COLUMNS.grossPay };
324
+ // The five columns of a monthly block row the template ships empty, against
325
+ // the three it ships as a literal zero.
326
+ const PAYSLIPS_BLANK_COLUMNS = [
327
+ PAYSLIPS_ENTRY_COLUMNS.name,
328
+ PAYSLIPS_ENTRY_COLUMNS.taxCode,
329
+ PAYSLIPS_ENTRY_COLUMNS.grossPay,
330
+ PAYSLIPS_ENTRY_COLUMNS.netPay,
331
+ PAYSLIPS_ENTRY_COLUMNS.reference,
332
+ ];
333
+ // The printed page's figures, all gated on a pay number no scenario gives.
334
+ const PAYSLIP_PRINT_BLANK_CELLS = ["M8", "G14", "H14", "I14", "M14", "G16", "H16", "I16", "M16", "M18"];
335
+
336
+ // One month tab's monthly payroll block: an employee a row from block row +
337
+ // 3, with the wages-paid date above them. A row the scenario has no employee
338
+ // for keeps the three columns the template ships as a literal zero and stays
339
+ // blank in the other five, which is what the workbook itself carries there.
340
+ function buildPayslipsMonthTab(monthIndex, entries, paidOn) {
341
+ const sheet = {};
342
+ const columns = PAYSLIPS_ENTRY_COLUMNS;
343
+ payslipsMonthEntryRows(monthIndex).forEach((row, index) => {
344
+ const entry = entries[index];
345
+ if (!entry) {
346
+ for (const column of PAYSLIPS_ZERO_FILLED_COLUMNS) sheet[`${column}${row}`] = 0;
347
+ for (const column of PAYSLIPS_BLANK_COLUMNS) sheet[`${column}${row}`] = SHEET_BLANK;
348
+ return;
349
+ }
350
+ sheet[`${columns.name}${row}`] = entry.name || SHEET_BLANK;
351
+ sheet[`${columns.taxCode}${row}`] = entry.taxCode || SHEET_BLANK;
352
+ sheet[`${columns.grossPay}${row}`] = entry.grossPay || 0;
353
+ sheet[`${columns.incomeTax}${row}`] = entry.incomeTax || 0;
354
+ sheet[`${columns.employeeNI}${row}`] = entry.employeeNI || 0;
355
+ sheet[`${columns.netPay}${row}`] = entry.netPay || 0;
356
+ sheet[`${columns.employerNI}${row}`] = entry.employerNI || 0;
357
+ sheet[`${columns.reference}${row}`] = entry.reference || SHEET_BLANK;
358
+ });
359
+ if (entries.length > 0) sheet[payslipsWagesPaidCell(monthIndex)] = paidOn(entries[0]);
360
+
361
+ // Template position 3 keeps its weekly employee lines and its period total;
362
+ // position 4 keeps the cells that would bring an unfinished weekly cycle in
363
+ // from the month before it.
364
+ if (monthIndex === PAYSLIPS_DIRECTLY_READ_MONTH_INDEXES[0]) sheet[PAYSLIPS_WEEKLY_PERIOD_TOTAL_CELL] = 0;
365
+ if (monthIndex === PAYSLIPS_DIRECTLY_READ_MONTH_INDEXES[1]) {
366
+ for (const row of PAYSLIPS_WEEKLY_ROWS) {
367
+ for (const column of PAYSLIPS_BROUGHT_FORWARD_COLUMNS) sheet[`${column}${row}`] = 0;
368
+ if (row >= PAYSLIPS_BROUGHT_FORWARD_LATE_COLUMN.firstRow) sheet[`${PAYSLIPS_BROUGHT_FORWARD_LATE_COLUMN.column}${row}`] = 0;
369
+ }
370
+ }
371
+ const weeklyTextColumn = PAYSLIPS_WEEKLY_TEXT_COLUMN[monthIndex];
372
+ if (weeklyTextColumn) for (const row of PAYSLIPS_WEEKLY_ROWS) sheet[`${weeklyTextColumn}${row}`] = SHEET_BLANK;
373
+ return sheet;
374
+ }
375
+
376
+ // The page the employer prints. H3 and H4 are the join -- the tab the chosen
377
+ // period lands on and the row its block starts at -- and I9, I10 and L7 the
378
+ // heading above the figures. Every figure below the heading is gated on the
379
+ // employee's line carrying a pay number, which a month tab gives an employee
380
+ // once their starting date has arrived. M8 is that number, and the
381
+ // year-to-date row adds the same employee's line over every month up to the
382
+ // one printed. A month with no payroll leaves the page blank below the
383
+ // heading, which is the sheet's own gated branch.
384
+ function buildPayslipsPrintPage(period, payroll, paidOn) {
385
+ const monthIndex = period - 1;
386
+ const sheet = {
387
+ [PAYSLIP_PRINT_CELLS.tab]: MONTH_SHEETS[MONTH_KEYS[monthIndex]],
388
+ [PAYSLIP_PRINT_CELLS.blockRow]: monthlyPayrollBlockRow(monthIndex),
389
+ [PAYSLIP_PRINT_CELLS.heading]: PAYSLIP_PRINT_MONTHLY_HEADING,
390
+ [PAYSLIP_PRINT_CELLS.periodNumber]: period,
391
+ };
392
+ const entries = payroll[MONTH_KEYS[monthIndex]] || [];
393
+ if (entries.length === 0) {
394
+ for (const cell of PAYSLIP_PRINT_BLANK_CELLS) sheet[cell] = SHEET_BLANK;
395
+ return sheet;
396
+ }
397
+
398
+ const entry = entries[0];
399
+ sheet[PAYSLIP_PRINT_CELLS.periodEnd] = paidOn(entry);
400
+ sheet.M8 = PAYSLIP_PRINT_FIRST_PAYROLL_NUMBER;
401
+ for (const [cell, field] of Object.entries(PAYSLIP_PRINT_PERIOD_CELLS)) sheet[cell] = entry[field] || 0;
402
+
403
+ const toDate = MONTH_KEYS.slice(0, period).flatMap((key) => (payroll[key] || []).slice(0, 1));
404
+ for (const [cell, field] of Object.entries(PAYSLIP_PRINT_TO_DATE_CELLS)) {
405
+ sheet[cell] = toDate.reduce((total, line) => total + (line[field] || 0), 0);
406
+ }
407
+ // M18's ADDRESS now points at the same cell I9 does -- the wages-paid date.
408
+ sheet.M18 = sheet[PAYSLIP_PRINT_CELLS.periodEnd];
409
+ return sheet;
410
+ }
411
+
412
+ function payrollMonths(payroll) {
413
+ return MONTH_KEYS.map((month) =>
414
+ (payroll?.[month] || []).reduce(
415
+ (totals, entry) => ({
416
+ grossPay: totals.grossPay + (entry.grossPay || 0),
417
+ incomeTax: totals.incomeTax + (entry.incomeTax || 0),
418
+ employeeNI: totals.employeeNI + (entry.employeeNI || 0),
419
+ employerNI: totals.employerNI + (entry.employerNI || 0),
420
+ }),
421
+ { grossPay: 0, incomeTax: 0, employeeNI: 0, employerNI: 0 },
422
+ ),
423
+ );
424
+ }
425
+
426
+ // ── The fixed asset schedule ───────────────────────────────────────────────
427
+
428
+ /**
429
+ * One Schedule row's computed columns.
430
+ *
431
+ * An existing asset's opening net book value is a formula, so its depreciation
432
+ * charge is capped at what is still left to write off. A new asset's is an
433
+ * empty cell, and MIN skips an empty cell, so the charge is the whole year's
434
+ * rate on the cost.
435
+ *
436
+ * The blanks matter downstream. A row whose tax written down value is the blank
437
+ * the formula leaves compares as text, so a disposal against it takes the
438
+ * balancing allowance branch and subtracting text puts the schedule in error.
439
+ * That is what the sheet reports for a disposal with no tax value entered, so
440
+ * it is what this reports too.
441
+ */
442
+ function scheduleRow({ cost, accDep = 0, taxWdv, depRate, aiaRate, wdaRate, disposal }) {
443
+ const written = cost > 0;
444
+ const isNewAsset = aiaRate !== undefined;
445
+ const row = { E: cost, F: accDep, H: depRate };
446
+ // A New asset block has no opening net book value column at all, so the row
447
+ // shows nothing there and the depreciation charge below is not capped.
448
+ row.G = isNewAsset || !written ? SHEET_BLANK : cost - accDep;
449
+ row.I = written ? (isNewAsset ? cost * depRate : Math.min(cost * depRate, sheetNumber(row.G))) : SHEET_BLANK;
450
+ row.J = written ? accDep + sheetNumber(row.I) : SHEET_BLANK;
451
+ row.K = written ? (disposal ? 0 : cost - sheetNumber(row.J)) : SHEET_BLANK;
452
+
453
+ if (!isNewAsset) {
454
+ row.O = taxWdv === undefined ? SHEET_BLANK : taxWdv;
455
+ row.Q = SHEET_BLANK;
456
+ const claimsWritingDown = typeof row.O === "number" && row.O > 0;
457
+ row.R = claimsWritingDown ? row.O * wdaRate : SHEET_BLANK;
458
+ row.S = claimsWritingDown ? row.O - row.R : SHEET_BLANK;
459
+ } else {
460
+ row.O = SHEET_BLANK;
461
+ row.P = aiaRate;
462
+ row.Q = written ? cost * aiaRate : SHEET_BLANK;
463
+ row.R = SHEET_BLANK;
464
+ row.S = written ? cost - sheetNumber(row.Q) : SHEET_BLANK;
465
+ }
466
+
467
+ row.V = disposal ? disposal.proceeds : SHEET_BLANK;
468
+ row.W = disposal ? cost : SHEET_BLANK;
469
+ row.X = disposal ? sheetNumber(row.J) : SHEET_BLANK;
470
+ if (!disposal) {
471
+ row.Y = SHEET_BLANK;
472
+ row.Z = SHEET_BLANK;
473
+ } else if (typeof row.S !== "number") {
474
+ row.Y = SHEET_ERROR;
475
+ row.Z = SHEET_BLANK;
476
+ } else {
477
+ row.Y = disposal.proceeds < row.S ? row.S - disposal.proceeds : SHEET_BLANK;
478
+ row.Z = disposal.proceeds > row.S ? disposal.proceeds - row.S : SHEET_BLANK;
479
+ }
480
+ return row;
481
+ }
482
+
483
+ // What a cell reads back as once its own arithmetic has failed. It carries
484
+ // through every cell that reads it.
485
+ const SHEET_ERROR = "#VALUE!";
486
+
487
+ /**
488
+ * A cell's value, or the error a cell it reads is already in.
489
+ * @param {Array} inputs - the cells the formula reads
490
+ * @param {function(): *} compute - the formula, run only when all of them hold a value
491
+ */
492
+ function carry(inputs, compute) {
493
+ return inputs.some((value) => value === SHEET_ERROR) ? SHEET_ERROR : compute();
494
+ }
495
+
496
+ const SCHEDULE_TOTAL_COLUMNS = ["E", "F", "G", "I", "J", "K", "O", "Q", "R", "S", "V", "W", "X", "Y", "Z"];
497
+
498
+ function scheduleTotals(rows) {
499
+ const totals = {};
500
+ for (const column of SCHEDULE_TOTAL_COLUMNS) {
501
+ totals[column] = rows.some((row) => row[column] === SHEET_ERROR) ? SHEET_ERROR : sheetSum(rows.map((row) => row[column]));
502
+ }
503
+ return totals;
504
+ }
505
+
506
+ function addScheduleTotals(left, right) {
507
+ const totals = {};
508
+ for (const column of SCHEDULE_TOTAL_COLUMNS) {
509
+ totals[column] = left[column] === SHEET_ERROR || right[column] === SHEET_ERROR ? SHEET_ERROR : left[column] + right[column];
510
+ }
511
+ return totals;
512
+ }
513
+
514
+ function buildSchedule(scenario, taxData, rate) {
515
+ const depreciation = taxData?.depreciation || {};
516
+ const wdaRate = taxData?.capital_allowances?.writing_down_allowance ?? 0;
517
+ const aiaRate = taxData?.capital_allowances?.annual_investment_allowance ?? 0;
518
+
519
+ const capitalPurchases = [];
520
+ for (const transactions of Object.values(scenario.purchases || {})) {
521
+ for (const tx of transactions) if (tx.code === "fa") capitalPurchases.push(tx);
522
+ }
523
+ const disposals = [];
524
+ for (const transactions of Object.values(scenario.sales || {})) {
525
+ for (const tx of transactions) if (tx.code === "fs") disposals.push({ proceeds: roundedNetOfVat(tx.amount, rate) });
526
+ }
527
+
528
+ // The writer fills each category's rows in declaration order and pairs a
529
+ // disposal with the existing asset row it disposes of, motor rows first.
530
+ const assetsByCategory = { motor: [], computer: [] };
531
+ for (const asset of scenario.opening_fixed_assets || []) {
532
+ if (assetsByCategory[asset.category]) assetsByCategory[asset.category].push(asset);
533
+ }
534
+ const disposalOrder = [...assetsByCategory.motor, ...assetsByCategory.computer];
535
+ const disposalByAsset = new Map();
536
+ disposals.forEach((disposal, index) => {
537
+ if (disposalOrder[index]) disposalByAsset.set(disposalOrder[index], disposal);
538
+ });
539
+
540
+ const existingRows = [];
541
+ for (const [category, block] of Object.entries(EXISTING_ASSET_BLOCKS)) {
542
+ for (const asset of assetsByCategory[category].slice(0, block.rows.length)) {
543
+ existingRows.push(
544
+ scheduleRow({
545
+ cost: asset.cost,
546
+ accDep: asset.acc_dep || 0,
547
+ taxWdv: asset.tax_wdv,
548
+ depRate: depreciation[block.rateKey] ?? 0,
549
+ wdaRate,
550
+ disposal: disposalByAsset.get(asset),
551
+ }),
552
+ );
553
+ }
554
+ }
555
+
556
+ const newRows = capitalPurchases
557
+ .slice(0, NEW_PLANT_ROW_COUNT)
558
+ .map((tx) => scheduleRow({ cost: roundedNetOfVat(tx.amount, rate), depRate: depreciation.plant_and_machinery ?? 0, aiaRate }));
559
+
560
+ const existing = scheduleTotals(existingRows);
561
+ const additions = scheduleTotals(newRows);
562
+ return { existing, additions, totals: addScheduleTotals(existing, additions) };
563
+ }
564
+
565
+ // ── Hire purchase ──────────────────────────────────────────────────────────
566
+
567
+ function buildHpFinance(scenario) {
568
+ const cells = { E2: 0 };
569
+ const agreements = scenario.hp_agreements || [];
570
+ HP_AGREEMENT_ROWS.forEach((row, index) => {
571
+ const agreement = agreements[index];
572
+ if (!agreement) {
573
+ cells[`I${row}`] = SHEET_BLANK;
574
+ cells[`J${row}`] = SHEET_BLANK;
575
+ cells[`K${row}`] = SHEET_BLANK;
576
+ return;
577
+ }
578
+ const monthly = (agreement.amount_financed + agreement.admin_charges + agreement.total_interest) / agreement.months;
579
+ const interest = agreement.total_interest / agreement.months;
580
+ cells[`I${row}`] = monthly;
581
+ cells[`K${row}`] = interest;
582
+ cells[`J${row}`] = monthly - interest;
583
+ cells.E2 += agreement.amount_financed;
584
+ });
585
+ return cells;
586
+ }
587
+
588
+ // Salesinvoice.xlsx links to nothing else in the book. The generator writes
589
+ // the tax year's standard rate down Product Details column D, and the
590
+ // invoice page looks its one sample line up from there.
591
+ //
592
+ // cellWrites only raises the sample invoice line for a VAT-registered
593
+ // business with a first sale to anchor it on (rate > 0, a VAT number, and a
594
+ // sale) -- the same condition checkCompliance's carriage checks gate on
595
+ // (app/products/se.js). A recalculated package proves the two states: with
596
+ // the line raised, Invoice Template!N27 through P64 resolve to real figures
597
+ // off the sample line and its carriage charge; without it, N27 stays blank
598
+ // and every cell downstream of it follows -- P58, P62 and P64 land on their
599
+ // formulas' own zero branch, while C38, J38, L38, P38 and the carriage cell
600
+ // P60 land on their formulas' own blank-string branch. This mirrors both
601
+ // states rather than assuming one.
602
+ function buildSalesInvoice(scenario, rate, taxData) {
603
+ const standardRatePercent = Math.round((taxData?.vat?.standard_rate ?? 0) * 100);
604
+ const productDetails = { D2: standardRatePercent };
605
+ const firstInvoiceSale = Object.values(scenario.sales || {}).flat()[0];
606
+ if (!(rate > 0 && scenario.business?.vat_number && firstInvoiceSale)) {
607
+ return {
608
+ "Salesinvoice.xlsx!Product Details": productDetails,
609
+ "Salesinvoice.xlsx!Invoice Template": {
610
+ J38: SHEET_BLANK,
611
+ L38: SHEET_BLANK,
612
+ P38: SHEET_BLANK,
613
+ V38: 0,
614
+ P58: 0,
615
+ P60: SHEET_BLANK,
616
+ P62: 0,
617
+ P64: 0,
618
+ },
619
+ };
620
+ }
621
+ const lineNet = firstInvoiceSale.amount;
622
+ const lineVat = (lineNet * standardRatePercent) / 100;
623
+ const carriageVat = (SALESINVOICE_SAMPLE_CARRIAGE_CHARGE * standardRatePercent) / 100;
624
+ const vatTotal = lineVat + carriageVat;
625
+ return {
626
+ "Salesinvoice.xlsx!Product Details": productDetails,
627
+ "Salesinvoice.xlsx!Invoice Template": {
628
+ J38: lineNet,
629
+ L38: 1,
630
+ P38: lineNet,
631
+ V38: lineVat,
632
+ P58: lineNet,
633
+ P60: SALESINVOICE_SAMPLE_CARRIAGE_CHARGE,
634
+ P62: vatTotal,
635
+ P64: lineNet + SALESINVOICE_SAMPLE_CARRIAGE_CHARGE + vatTotal,
636
+ },
637
+ };
638
+ }
639
+
640
+ // ── The Admin sheet ────────────────────────────────────────────────────────
641
+
642
+ function adminDateSerials(startYear) {
643
+ const serials = {};
644
+ for (const [cell, date] of Object.entries({ ...generateAdminDates(startYear), ...seVatPaymentDueDate(startYear) })) {
645
+ serials[parseInt(cell.slice(1), 10)] = excelSerial(date);
646
+ }
647
+ return serials;
648
+ }
649
+
650
+ function buildAdmin(taxData, dateSerials) {
651
+ const it = taxData.income_tax;
652
+ const ni = taxData.national_insurance;
653
+ const ca = taxData.capital_allowances;
654
+ const dep = taxData.depreciation || {};
655
+ const mil = taxData.mileage;
656
+ const cells = {};
657
+ for (const [row, serial] of Object.entries(dateSerials)) cells[`B${row}`] = serial;
658
+ if (taxData.tax_year?.label) cells.B23 = taxData.tax_year.label;
659
+ if (taxData.tax_year?.next_label) cells.B24 = taxData.tax_year.next_label;
660
+ cells.N4 = it.personal_allowance;
661
+ cells.N5 = it.personal_allowance_taper_threshold;
662
+ cells.N6 = it.basic_rate;
663
+ cells.N7 = it.higher_rate;
664
+ cells.N8 = it.additional_rate;
665
+ cells.K11 = it.basic_rate;
666
+ cells.N11 = it.starter_band_end;
667
+ cells.M11 = it.basic_band_end;
668
+ cells.K12 = it.higher_rate;
669
+ cells.L12 = it.higher_band_start;
670
+ cells.N12 = it.higher_band_start;
671
+ cells.K13 = it.additional_rate;
672
+ cells.L13 = it.higher_band_end + 1;
673
+ cells.N13 = it.higher_band_end;
674
+ cells.L16 = ni.class2_weekly_rate;
675
+ cells.N16 = ni.class2_small_profits_threshold;
676
+ cells.L20 = ni.class4_lower_rate;
677
+ cells.N20 = ni.class4_lower_limit;
678
+ cells.L23 = ni.class4_upper_rate;
679
+ cells.N23 = ni.class4_upper_limit;
680
+ cells.G4 = ca.annual_investment_allowance;
681
+ cells.G5 = ca.writing_down_allowance;
682
+ cells.G13 = dep.land_and_property;
683
+ cells.G14 = dep.plant_and_machinery;
684
+ cells.G15 = dep.fixtures_and_fittings;
685
+ cells.G16 = dep.computer_equipment;
686
+ cells.G17 = dep.motor_vehicles;
687
+ cells.F21 = mil.higher_rate_limit;
688
+ cells.G21 = mil.higher_rate_pence;
689
+ cells.F22 = mil.lower_rate_start;
690
+ cells.G22 = mil.lower_rate_pence;
691
+ cells.F26 = taxData.vat.registration_threshold;
692
+ cells.F27 = taxData.vat.standard_rate;
693
+ return cells;
694
+ }
695
+
696
+ // ── The payroll calendar ───────────────────────────────────────────────────
697
+
698
+ function buildPayrollCalendar(startYear, taxYearStartSerial) {
699
+ const calendar = generatePayslipsCalendar(startYear);
700
+ const yearStart = dateFromExcelSerial(taxYearStartSerial);
701
+ const yearEndSerial =
702
+ excelSerial(new Date(Date.UTC(yearStart.getUTCFullYear() + 1, yearStart.getUTCMonth(), yearStart.getUTCDate()))) - 1;
703
+ const yearEnd = dateFromExcelSerial(yearEndSerial);
704
+ const cells = {
705
+ B2: taxYearStartSerial,
706
+ I1: yearEndSerial,
707
+ N1: `${yearEnd.getUTCFullYear() - 1}-${yearEnd.getUTCFullYear() - 2000}`,
708
+ };
709
+ for (const row of PAYROLL_CALENDAR_SAMPLE_ROWS) {
710
+ const monthNumber = calendar[`D${row}`];
711
+ if (monthNumber === undefined) continue;
712
+ cells[`B${row}`] = taxYearStartSerial + row - 2;
713
+ cells[`C${row}`] = calendar[`C${row}`];
714
+ cells[`D${row}`] = monthNumber;
715
+ cells[`A${row}`] = SHORT_MONTH_NAMES[(yearStart.getUTCMonth() + monthNumber - 1) % 12];
716
+ }
717
+ return cells;
718
+ }
719
+
720
+ // ── The whole book ─────────────────────────────────────────────────────────
721
+
722
+ /**
723
+ * Every cell the engine computes for a Self Employed book, unscoped: the
724
+ * report's cells and every leaf cell a sibling workbook's link addresses,
725
+ * hub sheets under their bare names and leaf sheets as "File.xlsx!Sheet".
726
+ */
727
+ export function calculateSeCells(book, lines, taxData, scenario = {}) {
728
+ const rate = vatRateFor(scenario);
729
+ const startYear = taxData?.tax_year?.start ? new Date(taxData.tax_year.start).getUTCFullYear() : extractTaxYearStart(scenario);
730
+ const dateSerials = adminDateSerials(startYear);
731
+ // The writer dates a posting onto the tax year it is writing into, whole
732
+ // years past the scenario's own where the two differ (period-shift.js), and
733
+ // the wages-paid date is the one posting date the sheets carry as a value.
734
+ // Landing it in the same year keeps a package generated for another year
735
+ // equal to the engine asked for that year; a book in its own year moves
736
+ // by nothing.
737
+ const monthOffset = startYear ? periodShiftMonths(scenario, startYear, SE_YEAR_END_MONTH) : 0;
738
+ const paidOn = (entry) => excelSerial(shiftMonths(new Date(entry.date), monthOffset));
739
+ const admin = buildAdmin(taxData, dateSerials);
740
+
741
+ const salesMonths = journalMonths(scenario.sales, rate, SALES_ANALYSIS_COLUMNS, "a");
742
+ const purchasesMonths = journalMonths(scenario.purchases, rate, PURCHASES_ANALYSIS_COLUMNS);
743
+ const mileage = mileageMonths(scenario, taxData?.mileage);
744
+ purchasesMonths.forEach((month, index) => {
745
+ const claim = mileage[index].claim;
746
+ if (!claim) return;
747
+ month.gross += claim;
748
+ month.net += claim;
749
+ month.byCode.v = (month.byCode.v || 0) + claim;
750
+ });
751
+ const bank = bankBook(scenario.bank, "Bank.xlsx");
752
+ const cash = bankBook(scenario.bank, "Cash.xlsx");
753
+ const payroll = payrollMonths(scenario.payroll);
754
+ const schedule = buildSchedule(scenario, taxData, rate);
755
+ const scheduleNumber = (column) => sheetNumber(schedule.totals[column]);
756
+
757
+ // The twelve monthly stock cells telescope, so whatever is counted between
758
+ // them the year's movement is the difference between its two ends. A count at
759
+ // only one end leaves the closing cell's own formula carrying the same figure
760
+ // forward, so the movement is nil.
761
+ const stockOpeningCount = scenario.stock?.opening ?? 0;
762
+ const stockClosingCount = scenario.stock?.closing ?? stockOpeningCount;
763
+
764
+ const salesCode = (index, code) => salesMonths[index].byCode[code] || 0;
765
+ const purchasesCode = (index, code) => purchasesMonths[index].byCode[code] || 0;
766
+
767
+ // ── Wagesinterface ──
768
+ const wagesinterface = {};
769
+ payroll.forEach((month, index) => {
770
+ const row = WAGES_MONTH_ROWS[index];
771
+ wagesinterface[`B${row}`] = dateSerials[index + 5];
772
+ wagesinterface[`C${row}`] = month.grossPay;
773
+ wagesinterface[`D${row}`] = month.incomeTax;
774
+ wagesinterface[`E${row}`] = month.employeeNI;
775
+ wagesinterface[`F${row}`] = 0;
776
+ wagesinterface[`G${row}`] = month.grossPay - month.incomeTax - month.employeeNI;
777
+ wagesinterface[`H${row}`] = month.employerNI;
778
+ wagesinterface[`I${row}`] = 0;
779
+ });
780
+
781
+ // ── Profit and loss account ──
782
+ const scheduleDepreciation = scheduleNumber("I");
783
+ const disposalLoss = -(scheduleNumber("V") - scheduleNumber("W") + scheduleNumber("X"));
784
+ const pl = {};
785
+ MONTH_COLS.forEach((col, index) => {
786
+ const closesTheYear = index === MONTH_COLS.length - 1;
787
+ const wagesRow = WAGES_MONTH_ROWS[index];
788
+ pl[`${col}5`] = salesCode(index, "a");
789
+ pl[`${col}6`] = salesCode(index, "b");
790
+ pl[`${col}7`] = salesCode(index, "c");
791
+ pl[`${col}8`] = salesCode(index, "d");
792
+ pl[`${col}9`] = pl[`${col}5`] + pl[`${col}6`] + pl[`${col}7`] + pl[`${col}8`];
793
+ pl[`${col}11`] = salesCode(index, "g");
794
+ pl[`${col}14`] = purchasesCode(index, "s") + (closesTheYear ? stockOpeningCount - stockClosingCount : 0);
795
+ pl[`${col}15`] = purchasesCode(index, "c");
796
+ pl[`${col}16`] = purchasesCode(index, "o");
797
+ pl[`${col}17`] = pl[`${col}14`] + pl[`${col}15`] + pl[`${col}16`];
798
+ pl[`${col}19`] = pl[`${col}9`] + pl[`${col}11`] - pl[`${col}17`];
799
+ pl[`${col}21`] =
800
+ purchasesCode(index, "w") + wagesinterface[`C${wagesRow}`] + wagesinterface[`H${wagesRow}`] - wagesinterface[`I${wagesRow}`];
801
+ pl[`${col}22`] = purchasesCode(index, "p");
802
+ pl[`${col}23`] = purchasesCode(index, "m");
803
+ pl[`${col}24`] = purchasesCode(index, "g");
804
+ pl[`${col}25`] = purchasesCode(index, "v");
805
+ pl[`${col}26`] = purchasesCode(index, "h");
806
+ pl[`${col}27`] = purchasesCode(index, "a");
807
+ pl[`${col}28`] = purchasesCode(index, "l");
808
+ pl[`${col}29`] = -salesCode(index, "o");
809
+ pl[`${col}30`] = bankPayments(bank, index, "J");
810
+ pl[`${col}31`] = bankPayments(cash, index, "J") + bankPayments(bank, index, "B");
811
+ pl[`${col}32`] = purchasesCode(index, "y");
812
+ pl[`${col}33`] = disposalLoss / 12;
813
+ pl[`${col}34`] = scheduleDepreciation / 12;
814
+ pl[`${col}35`] = sheetSum([21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].map((row) => pl[`${col}${row}`]));
815
+ pl[`${col}37`] = pl[`${col}19`] - pl[`${col}35`];
816
+ pl[`${col}38`] = bankReceipts(bank, index, "K");
817
+ pl[`${col}39`] = pl[`${col}37`] + pl[`${col}38`];
818
+ });
819
+ const yearTotal = (row) => sheetSum(MONTH_COLS.map((col) => pl[`${col}${row}`]));
820
+ for (const row of [5, 6, 7, 8, 11, 14, 15, 16, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 38]) {
821
+ pl[`B${row}`] = yearTotal(row);
822
+ }
823
+ pl.B9 = pl.B5 + pl.B6 + pl.B7 + pl.B8;
824
+ pl.B17 = pl.B14 + pl.B15 + pl.B16;
825
+ pl.B19 = pl.B9 + pl.B11 - pl.B17;
826
+ pl.B35 = sheetSum([21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].map((row) => pl[`B${row}`]));
827
+ pl.B37 = pl.B19 - pl.B35;
828
+ pl.B39 = pl.B37 + pl.B38;
829
+
830
+ // ── The fixed asset workbook ──
831
+ const scheduleCells = { E57: schedule.existing.E, E110: schedule.additions.E };
832
+ for (const column of SCHEDULE_TOTAL_COLUMNS) scheduleCells[`${column}1`] = schedule.totals[column];
833
+ const faReconciliation = {
834
+ E11: schedule.additions.E,
835
+ E13: journalCodeTotal(scenario.purchases, "fa", rate),
836
+ K11: schedule.totals.V,
837
+ K13: journalCodeTotal(scenario.sales, "fs", rate),
838
+ };
839
+ faReconciliation.E15 = faReconciliation.E13 - faReconciliation.E11;
840
+ faReconciliation.K15 = faReconciliation.K13 - sheetNumber(faReconciliation.K11);
841
+
842
+ // ── VAT ──
843
+ const vatinterface = buildVatinterface({
844
+ salesMonths,
845
+ purchasesMonths,
846
+ straddlingSales: straddlingPeriodTotals(scenario.vat_straddling_sales, rate),
847
+ straddlingPurchases: straddlingPeriodTotals(scenario.vat_straddling_purchases, rate),
848
+ adminDateSerials: dateSerials,
849
+ });
850
+ const firstMonthEnd = dateFromExcelSerial(dateSerials[5]);
851
+ const returnPeriodEnds = vatReturnPeriodEnds(
852
+ new Date(Date.UTC(firstMonthEnd.getUTCFullYear(), firstMonthEnd.getUTCMonth(), 1)),
853
+ excelSerial,
854
+ );
855
+
856
+ // ── Payslips ──
857
+ // The PAYE remittance schedule: B the tax month end and C the day the
858
+ // payment falls due, both counted off the payroll year's first day; D the
859
+ // National Insurance due, E the income tax and I the whole amount payable.
860
+ const payment = {};
861
+ payroll.forEach((month, index) => {
862
+ const row = WAGES_MONTH_ROWS[index];
863
+ const taxMonth = payeTaxMonthDates(payrollYearStart(startYear), index);
864
+ payment[`B${row}`] = excelSerial(taxMonth.ends);
865
+ payment[`C${row}`] = excelSerial(taxMonth.due);
866
+ payment[`D${row}`] = month.employerNI + month.employeeNI;
867
+ payment[`E${row}`] = month.incomeTax;
868
+ payment[`I${row}`] = payment[`D${row}`] + payment[`E${row}`];
869
+ });
870
+
871
+ // ── The two self assessment returns ──
872
+ // Short return boxes 27, 29 and 35 and full return boxes 50, 52, 53, 57 and
873
+ // 61 have no formula behind them: the customer fills them in on the Business
874
+ // Details sheet or on the return, and nothing the scenario carries reaches
875
+ // them.
876
+ const goodsForOwnUse = 0;
877
+ const lossesBroughtForward = 0;
878
+ const lossToCarryForward = 0;
879
+ // Turnover at or below the VAT threshold lets the short return state one
880
+ // total and leave the expense analysis blank, which is what the sheet's own
881
+ // nine expense cells gate on.
882
+ const analysesExpenses = pl.B9 > admin.F26;
883
+ const analysed = (value) => (analysesExpenses ? value : SHEET_BLANK);
884
+ const contractorDeductions = sheetSum(salesMonths.map((month) => month.cis));
885
+
886
+ const scheduleQ = schedule.totals.Q;
887
+ const scheduleR = schedule.totals.R;
888
+ const scheduleS = schedule.totals.S;
889
+ const scheduleY = schedule.totals.Y;
890
+ const scheduleZ = schedule.totals.Z;
891
+
892
+ const seShort = {};
893
+ seShort.Q2 = dateSerials[4];
894
+ seShort.V2 = dateSerials[17];
895
+ // The return prints its business name at C8, its accounting date at S17 and
896
+ // its turnover note at A33. The left-column equivalents (A7, D8, A32) are the
897
+ // empty boxes beside the print locations.
898
+ seShort.A7 = SHEET_BLANK;
899
+ seShort.D8 = SHEET_BLANK;
900
+ seShort.A32 = SHEET_BLANK;
901
+ seShort.C8 = scenario.business?.name || " ";
902
+ seShort.S17 = seShort.Q2;
903
+ seShort.D38 = pl.B9;
904
+ seShort.O38 = pl.B38;
905
+ // Turnover note: conditional message about VAT threshold
906
+ seShort.A33 =
907
+ seShort.D38 > admin.F26
908
+ ? `SELF-EMPLOYMENT FULL RETURN REQUIRED AS TURNOVER EXCEEDS £${admin.F26} VAT threshold`
909
+ : `Business income - if your annual turnover was below £${admin.F26} VAT threshold`;
910
+ seShort.D46 = analysed(pl.B17);
911
+ seShort.O46 = analysed(pl.B28);
912
+ seShort.D51 = analysed(pl.B25 + pl.B26);
913
+ seShort.O51 = analysed(pl.B30 + pl.B31);
914
+ seShort.D55 = analysed(pl.B21);
915
+ seShort.O55 = analysed(pl.B24);
916
+ seShort.D60 = analysed(pl.B22);
917
+ seShort.O60 = analysed(pl.B27 + pl.B29 + pl.B32 + pl.B33);
918
+ seShort.D64 = analysed(pl.B23);
919
+ seShort.O64 = pl.B17 + pl.B35 - pl.B34;
920
+ const shortNetProfit = seShort.D38 + seShort.O38 - seShort.O64;
921
+ seShort.D71 = shortNetProfit >= 0 ? shortNetProfit : 0;
922
+ seShort.O71 = shortNetProfit < 0 ? -shortNetProfit : 0;
923
+ seShort.D80 = carry([scheduleQ], () => (scheduleQ > 0 ? scheduleQ : 0));
924
+ seShort.O80 = carry([scheduleR, scheduleY], () => (scheduleR + scheduleY > 0 ? scheduleR + scheduleY : 0));
925
+ seShort.D85 = carry([scheduleR, scheduleS], () => (scheduleR + scheduleS < 1000 ? scheduleS : 0));
926
+ seShort.O85 = carry([scheduleZ], () => (scheduleZ > 0 ? scheduleZ : 0));
927
+ seShort.D94 = goodsForOwnUse;
928
+ const shortAllowances = [seShort.D71, seShort.O85, seShort.D94, seShort.O71, seShort.D80, seShort.D85, seShort.O80];
929
+ seShort.D99 = carry(shortAllowances, () => {
930
+ const profit = seShort.D71 + seShort.O85 + seShort.D94 - seShort.O71 - seShort.D80 - seShort.D85 - seShort.O80;
931
+ return profit > 0 ? profit : 0;
932
+ });
933
+ seShort.O99 = pl.B11;
934
+ seShort.O106 = carry(shortAllowances, () => {
935
+ const loss = seShort.O71 + seShort.D80 + seShort.D85 + seShort.O80 - seShort.D71 - seShort.O85 - seShort.D94;
936
+ return loss >= 0 ? loss : 0;
937
+ });
938
+ seShort.O94 = carry([seShort.O106, seShort.D99], () =>
939
+ seShort.O106 > 0 || lossesBroughtForward === 0 ? 0 : Math.min(seShort.D99, lossesBroughtForward),
940
+ );
941
+ seShort.D106 = carry([seShort.D99, seShort.O94], () =>
942
+ seShort.D99 + seShort.O99 - seShort.O94 > 0 ? seShort.D99 + seShort.O99 - seShort.O94 : 0,
943
+ );
944
+ seShort.D124 = lossToCarryForward;
945
+ seShort.O124 = contractorDeductions;
946
+
947
+ const seFull = {};
948
+ // ="COPY DETAILS TO HMRC FORM ... by 31st January "&TEXT(Admin!B21,"yyyy")
949
+ seFull.G1 =
950
+ `COPY DETAILS TO HMRC FORM Submit HMRC RETURN ONLINE by 31st January ` +
951
+ dateFromExcelSerial(admin.B21).getUTCFullYear();
952
+ seFull.Q2 = dateSerials[4];
953
+ seFull.V2 = dateSerials[17];
954
+ seFull.D55 = pl.B9;
955
+ seFull.O55 = pl.B38;
956
+ seFull.D66 = pl.B14 + pl.B16;
957
+ seFull.D70 = pl.B15;
958
+ seFull.D74 = pl.B21;
959
+ seFull.D78 = pl.B25 + pl.B26;
960
+ seFull.D82 = pl.B22;
961
+ seFull.D86 = pl.B23;
962
+ seFull.D90 = pl.B24;
963
+ seFull.D94 = pl.B27;
964
+ seFull.D98 = pl.B30;
965
+ seFull.D102 = pl.B31;
966
+ seFull.D106 = pl.B29;
967
+ seFull.D110 = pl.B28;
968
+ seFull.D114 = pl.B33 + pl.B34;
969
+ seFull.D118 = pl.B32;
970
+ seFull.D122 = pl.B17 + pl.B35;
971
+ seFull.O114 = pl.B34;
972
+ seFull.O122 = pl.B34;
973
+ const fullNetProfit = seFull.D55 + seFull.O55 - seFull.D122;
974
+ seFull.D129 = fullNetProfit >= 0 ? fullNetProfit : 0;
975
+ seFull.O129 = fullNetProfit < 0 ? -fullNetProfit : 0;
976
+ seFull.G141 = admin.G5;
977
+ seFull.D139 = carry([scheduleQ], () => (scheduleQ > 0 ? scheduleQ : 0));
978
+ // Boxes the customer fills in by hand, with no formula to compute them. The
979
+ // schedule keeps one main pool at the 18% writing down rate, so the special
980
+ // rate pool (box 51), the zero-emission and structures-and-buildings claims
981
+ // (boxes 52, 52.1 and 53) and the electric charge-point claim (box 54) have
982
+ // nothing feeding them.
983
+ seFull.D147 = SHEET_BLANK;
984
+ seFull.D152 = SHEET_BLANK;
985
+ seFull.D156 = SHEET_BLANK;
986
+ seFull.D160 = SHEET_BLANK;
987
+ seFull.O139 = SHEET_BLANK;
988
+ seFull.D179 = SHEET_BLANK;
989
+ // Box 50 carries the whole writing down allowance the schedule claims.
990
+ seFull.D144 = carry([scheduleR], () => scheduleR);
991
+ seFull.O144 = carry([scheduleR, scheduleS], () => (scheduleR + scheduleS < 1000 ? scheduleS : 0));
992
+ seFull.O149 = scheduleY;
993
+ seFull.O154 = carry([seFull.D139, seFull.D144, seFull.D152, seFull.O144, seFull.O149], () =>
994
+ sheetSum([seFull.D139, seFull.D144, seFull.D147, seFull.D152, seFull.D156, seFull.D160, seFull.O139, seFull.O144, seFull.O149]),
995
+ );
996
+ seFull.O160 = scheduleZ;
997
+ seFull.D169 = goodsForOwnUse;
998
+ seFull.O169 = carry([seFull.O154], () => sheetNumber(seFull.O154) + sheetNumber(seFull.D179));
999
+ seFull.D174 = carry([seFull.O160], () => sheetNumber(seFull.O122) + sheetNumber(seFull.O160) + sheetNumber(seFull.D169));
1000
+ seFull.O174 = carry([seFull.D129, seFull.D174, seFull.O169, seFull.O129], () => {
1001
+ const fromNetProfit = seFull.D129 + seFull.D174 - seFull.O169;
1002
+ return fromNetProfit > 0 ? fromNetProfit : Math.max(0, -seFull.O129 + seFull.D174 - seFull.O169);
1003
+ });
1004
+ seFull.O179 = carry([seFull.O174, seFull.D129, seFull.D174, seFull.O169, seFull.O129], () => {
1005
+ if (seFull.O174 > 0) return 0;
1006
+ const fromNetProfit = seFull.D129 + seFull.D174 - seFull.O169;
1007
+ if (fromNetProfit < 0) return -fromNetProfit;
1008
+ const fromNetLoss = -seFull.O129 + seFull.D174 - seFull.O169;
1009
+ return fromNetLoss < 0 ? -fromNetLoss : 0;
1010
+ });
1011
+ seFull.O194 = seFull.O174;
1012
+ seFull.O204 = pl.B11;
1013
+ seFull.O199 = carry([seFull.O194], () => (sheetNumber(seFull.D179) > 0 ? 0 : Math.min(seFull.O194 + seFull.O204, lossesBroughtForward)));
1014
+ seFull.O210 = carry([seFull.O194, seFull.O199], () => seFull.O194 - seFull.O199 + seFull.O204);
1015
+ seFull.D219 = carry([seFull.O179], () => seFull.O179);
1016
+ seFull.O224 = seFull.D219;
1017
+ seFull.D231 = contractorDeductions;
1018
+ seFull.J280 = admin.N20;
1019
+
1020
+ // ── Income tax ──
1021
+ // The sheet charges tax on the full return's own taxable profit, not on the
1022
+ // profit and loss account's profit before tax.
1023
+ const taxableProfit = seFull.O210;
1024
+ const charged = carry([taxableProfit], () => calculateIncomeTax(taxableProfit, taxData.income_tax));
1025
+ const chargedOn = (field) => carry([charged], () => charged[field]);
1026
+ // The deduction line already holds the contractor deductions negated, and the
1027
+ // total below it adds every line up.
1028
+ const contractorDeductionLine = -contractorDeductions;
1029
+ const niLower = carry([taxableProfit], () =>
1030
+ taxableProfit > admin.N20 ? (Math.min(taxableProfit, admin.N23) - admin.N20) * admin.L20 : 0,
1031
+ );
1032
+ const niUpper = carry([taxableProfit], () => (taxableProfit > admin.N23 ? (taxableProfit - admin.N23) * admin.L23 : 0));
1033
+ const incomeTax = {
1034
+ E5: taxableProfit,
1035
+ // E6 = IF(E5<=0,0,MAX(0,Admin!N$4-MAX(0,E5-Admin!N$5)/2)): a loss year
1036
+ // has no taxable profit to set an allowance against, so the sheet floors
1037
+ // this at nil rather than showing the allowance unused -- the same floor
1038
+ // Profit Forecast!C40 already applies below.
1039
+ E6: carry([taxableProfit, charged], () => (taxableProfit <= 0 ? 0 : charged.personalAllowance)),
1040
+ E7: chargedOn("taxableIncome"),
1041
+ C8: admin.N11,
1042
+ D8: admin.N6,
1043
+ E8: chargedOn("basicRateTax"),
1044
+ C9: admin.M11,
1045
+ D9: admin.N7,
1046
+ E9: chargedOn("higherRateTax"),
1047
+ C10: admin.N13,
1048
+ D10: admin.N8,
1049
+ E10: chargedOn("additionalRateTax"),
1050
+ E11: chargedOn("totalIncomeTax"),
1051
+ E12: contractorDeductionLine,
1052
+ C13: dateSerials[21],
1053
+ D15: admin.L20,
1054
+ E15: niLower,
1055
+ D16: admin.L23,
1056
+ E16: niUpper,
1057
+ E18: carry([charged, niLower, niUpper], () => charged.totalIncomeTax + contractorDeductionLine + niLower + niUpper),
1058
+ };
1059
+
1060
+ // ── Profit forecast ──
1061
+ // The forecast repeats a month that traded and spreads the year's total
1062
+ // across the months that did not.
1063
+ const monthsTraded = MONTH_COLS.filter((col) => pl[`${col}9`] > 0).length;
1064
+ const projected = (row) =>
1065
+ sheetSum(MONTH_COLS.map((col) => (pl.B9 <= 0 ? 0 : pl[`${col}9`] > 0 ? pl[`${col}${row}`] : pl[`B${row}`] / monthsTraded)));
1066
+ const forecast = {};
1067
+ forecast.C21 = monthsTraded;
1068
+ forecast.C22 = projected(9);
1069
+ forecast.C24 = yearTotal(11);
1070
+ forecast.C26 = projected(17);
1071
+ forecast.C28 = forecast.C22 + forecast.C24 - forecast.C26;
1072
+ forecast.C30 = projected(35);
1073
+ forecast.C32 = forecast.C28 - forecast.C30;
1074
+ forecast.C33 = yearTotal(38);
1075
+ forecast.C34 = forecast.C32 + forecast.C33;
1076
+ forecast.C37 = pl.B33 + pl.B34;
1077
+ forecast.C38 = carry([scheduleQ, scheduleR, scheduleY, scheduleZ], () => scheduleQ + scheduleR + scheduleY - scheduleZ);
1078
+ forecast.C39 = carry([forecast.C38], () => forecast.C34 + forecast.C37 - forecast.C38);
1079
+ forecast.C40 = carry([forecast.C39], () => (forecast.C39 <= 0 ? 0 : Math.max(0, admin.N4 - Math.max(0, forecast.C39 - admin.N5) / 2)));
1080
+ forecast.C41 = carry([forecast.C39, forecast.C40], () => (forecast.C39 > forecast.C40 ? forecast.C39 - forecast.C40 : 0));
1081
+ forecast.C42 = carry([forecast.C41], () => (forecast.C41 > 0 ? Math.min(forecast.C41, admin.M11) * admin.N6 : 0));
1082
+ forecast.C43 = carry([forecast.C41], () => (forecast.C41 > admin.M11 ? (Math.min(forecast.C41, admin.N13) - admin.M11) * admin.N7 : 0));
1083
+ forecast.C44 = carry([forecast.C41], () => (forecast.C41 > admin.N13 ? (forecast.C41 - admin.N13) * admin.N8 : 0));
1084
+ forecast.C45 = carry(
1085
+ [forecast.C39],
1086
+ () =>
1087
+ (forecast.C39 > admin.N20 ? (Math.min(forecast.C39, admin.N23) - admin.N20) * admin.L20 : 0) +
1088
+ (forecast.C39 > admin.N23 ? (forecast.C39 - admin.N23) * admin.L23 : 0),
1089
+ );
1090
+ forecast.C46 = carry([forecast.C42, forecast.C43, forecast.C44, forecast.C45], () =>
1091
+ sheetSum([forecast.C42, forecast.C43, forecast.C44, forecast.C45]),
1092
+ );
1093
+
1094
+ // ── VitalTax ──
1095
+ // The summary quotes the three product sales rows and the two direct cost
1096
+ // rows, nothing else.
1097
+ const quarterSum = (row, quarter) => sheetSum(MONTH_COLS.slice(quarter * 3, quarter * 3 + 3).map((col) => pl[`${col}${row}`]));
1098
+ const productSales = (quarter) => quarterSum(5, quarter) + quarterSum(6, quarter) + quarterSum(7, quarter);
1099
+ const directCosts = (quarter) => quarterSum(14, quarter) + quarterSum(16, quarter);
1100
+ const vitalTax = {
1101
+ C5: productSales(0),
1102
+ D5: productSales(1),
1103
+ E5: productSales(2),
1104
+ F5: productSales(3),
1105
+ C7: directCosts(0),
1106
+ D7: directCosts(1),
1107
+ E7: directCosts(2),
1108
+ F7: directCosts(3),
1109
+ };
1110
+ vitalTax.G5 = vitalTax.C5 + vitalTax.D5 + vitalTax.E5 + vitalTax.F5;
1111
+ vitalTax.G7 = vitalTax.C7 + vitalTax.D7 + vitalTax.E7 + vitalTax.F7;
1112
+
1113
+ // ── The results, keyed the way the reconciliation reads them ──
1114
+ const results = {
1115
+ "Business Details": { C5: businessName(scenario) },
1116
+ "Profit & Loss Account": pl,
1117
+ "Income Tax": incomeTax,
1118
+ "Profit Forecast": forecast,
1119
+ "SE Short": seShort,
1120
+ "SE Full": seFull,
1121
+ "Wagesinterface": wagesinterface,
1122
+ "VitalTax": vitalTax,
1123
+ "StockControl": {
1124
+ [STOCK_OPENING_COUNT_CELL]: scenario.stock?.opening === undefined ? SHEET_BLANK : scenario.stock.opening,
1125
+ [STOCK_CLOSING_COUNT_CELL]: stockClosingCount,
1126
+ },
1127
+ "Admin": admin,
1128
+ "Fixedassets.xlsx!Schedule": scheduleCells,
1129
+ "Fixedassets.xlsx!FAreconciliation": faReconciliation,
1130
+ "Fixedassets.xlsx!HPfinance": buildHpFinance(scenario),
1131
+ ...buildSalesInvoice(scenario, rate, taxData),
1132
+ "Payslips.xlsx!Payment": payment,
1133
+ "Payslips.xlsx!Admin": buildPayrollCalendar(startYear, dateSerials[4]),
1134
+ [`Payslips.xlsx!${PAYSLIP_PRINT_SHEET}`]: buildPayslipsPrintPage(PAYSLIP_PRINT_PERIOD, scenario.payroll || {}, paidOn),
1135
+ ...bankMonthTabs("Bank.xlsx", bank),
1136
+ ...bankMonthTabs("Cash.xlsx", cash),
1137
+ "Sales.xlsx!OpeningDebtors": { G1: ledgerTotal(scenario.opening_debtors), H2: rate * 100 },
1138
+ // H4 quotes Mar!H4, the flat-rate marker, which no book fills; the sheet
1139
+ // reads the blank as nil.
1140
+ "Sales.xlsx!ClosingDebtors": { G1: ledgerTotal(scenario.closing_debtors), H2: rate * 100, H4: 0 },
1141
+ "Purchases.xlsx!OpeningCreditors": { G1: ledgerTotal(scenario.opening_creditors), H2: rate * 100 },
1142
+ "Purchases.xlsx!ClosingCreditors": { G1: ledgerTotal(scenario.closing_creditors), H2: rate * 100 },
1143
+ };
1144
+
1145
+ for (const monthIndex of PAYSLIPS_DIRECTLY_READ_MONTH_INDEXES) {
1146
+ const tab = MONTH_SHEETS[MONTH_KEYS[monthIndex]];
1147
+ results[`Payslips.xlsx!${tab}`] = buildPayslipsMonthTab(monthIndex, scenario.payroll?.[MONTH_KEYS[monthIndex]] || [], paidOn);
1148
+ }
1149
+
1150
+ // Every month tab carries its own whole-month totals on row 1, which is
1151
+ // what the PAYE schedule row for that month reads it through.
1152
+ payroll.forEach((month, index) => {
1153
+ const key = `Payslips.xlsx!${MONTH_SHEETS[MONTH_KEYS[index]]}`;
1154
+ if (!results[key]) results[key] = {};
1155
+ results[key][PAYE_SCHEDULE_MONTH_TAB_CELLS.employerNI] = month.employerNI;
1156
+ results[key][PAYE_SCHEDULE_MONTH_TAB_CELLS.employeeNI] = month.employeeNI;
1157
+ results[key][PAYE_SCHEDULE_MONTH_TAB_CELLS.incomeTax] = month.incomeTax;
1158
+ results[key][PAYE_SCHEDULE_MONTH_TAB_CELLS.studentLoan] = 0;
1159
+ results[key].M1 = month.grossPay;
1160
+ // Statutory pay and other deductions: no payroll line carries either.
1161
+ results[key].G1 = 0;
1162
+ results[key].Q1 = 0;
1163
+ });
1164
+
1165
+ let cisSufferedToDate = 0;
1166
+ const salesFixedAssetsToDate = runningTotals(salesMonths, "fs");
1167
+ const purchasesFixedAssetsToDate = runningTotals(purchasesMonths, "fa");
1168
+ MONTH_KEYS.forEach((month, index) => {
1169
+ const tab = MONTH_SHEETS[month];
1170
+ const sales = salesMonths[index];
1171
+ const purchases = purchasesMonths[index];
1172
+ // W1 is the month's own CIS suffered and X1 the year to date: April's X1
1173
+ // is its W1 and every later tab adds the month before it, so the March X1
1174
+ // is the figure both returns take off the tax bill.
1175
+ cisSufferedToDate += sales.cis;
1176
+ results[`Sales.xlsx!${tab}`] = {
1177
+ G1: sales.gross,
1178
+ H1: sales.vat,
1179
+ I1: sales.net,
1180
+ H2: rate * 100,
1181
+ W1: sales.cis,
1182
+ X1: cisSufferedToDate,
1183
+ D1: monthMiles(scenario.sales?.[month]),
1184
+ V2: salesFixedAssetsToDate[index],
1185
+ ...analysisTotals(sales, SALES_ANALYSIS_COLUMNS),
1186
+ };
1187
+ // H4, the flat-rate marker, is blank on the April tab and every later tab
1188
+ // quotes the one before it, so from May on it reads as nil.
1189
+ if (index > 0) results[`Sales.xlsx!${tab}`].H4 = 0;
1190
+ results[`Purchases.xlsx!${tab}`] = {
1191
+ G1: purchases.gross,
1192
+ H1: purchases.vat,
1193
+ I1: purchases.net,
1194
+ H2: rate * 100,
1195
+ AD1: purchases.cis,
1196
+ C2: mileage[index].miles,
1197
+ G2: mileage[index].claim,
1198
+ A2: mileage[index].claimToDate,
1199
+ AB2: purchasesFixedAssetsToDate[index],
1200
+ // The month's own check total. Every analysed column is accounted for, so
1201
+ // the sheet balances whatever the CIS column carries beside it.
1202
+ A1: purchases.gross - purchases.vat - sheetSum(Object.values(purchases.byCode)),
1203
+ ...analysisTotals(purchases, PURCHASES_ANALYSIS_COLUMNS),
1204
+ };
1205
+ });
1206
+
1207
+ const vatinterfaceCells = {};
1208
+ for (let row = VATINTERFACE_FIRST_ROW; row <= VATINTERFACE_LAST_ROW; row++) {
1209
+ for (const [column, value] of Object.entries(vatinterface[row])) vatinterfaceCells[`${column}${row}`] = value;
1210
+ }
1211
+ results["Vat.xlsx!Vatinterface"] = vatinterfaceCells;
1212
+ returnPeriodEnds.forEach((periodEnd, index) => {
1213
+ results[`Vat.xlsx!VATQtr${index + 1}`] = vatReturnBoxes(vatinterface, periodEnd);
1214
+ });
1215
+
1216
+ return results;
1217
+ }
1218
+
1219
+ export function calculateSeResults(book, lines, taxData, scenario = {}) {
1220
+ return withinReadScope(calculateSeCells(book, lines, taxData, scenario));
1221
+ }
1222
+
1223
+ // The report scores one value per cell the reconciliation reads, so a cell
1224
+ // computed on the way to another one is working, not a reading. Handing back
1225
+ // only the read scope keeps the two engines' documents the same shape.
1226
+ function withinReadScope(results) {
1227
+ const scope = { ...standardReads() };
1228
+ for (const [file, sheets] of Object.entries(multiFileOptions().additionalReads)) {
1229
+ for (const [sheet, cells] of Object.entries(sheets)) scope[`${file}!${sheet}`] = cells;
1230
+ }
1231
+ const scoped = {};
1232
+ for (const [sheet, cells] of Object.entries(scope)) {
1233
+ const computed = results[sheet];
1234
+ if (!computed) continue;
1235
+ scoped[sheet] = {};
1236
+ for (const cell of cells) if (computed[cell] !== undefined) scoped[sheet][cell] = computed[cell];
1237
+ }
1238
+ return scoped;
1239
+ }