@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,1912 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // generator.js — Core spreadsheet generation via zip-level XML surgery.
5
+ // Modifies only specific cell values in the Admin sheet XML, preserving all
6
+ // formatting, charts, conditional formatting, and XML packaging.
7
+
8
+ import JSZip from "jszip";
9
+ import { buildSheetMap, loadSharedStrings } from "./spreadsheet-runner.js";
10
+ import {
11
+ PAYE_DUE_DATE_ROWS,
12
+ PAYE_MONTH_END_ROWS,
13
+ PAYE_SCHEDULE_FIRST_ROW,
14
+ PAYROLL_WEEKS_PER_MONTH,
15
+ PAYSLIP_PRINT_CELLS,
16
+ PAYSLIP_PRINT_SHEET,
17
+ payeTaxMonthDates,
18
+ payslipsMonthPeriod,
19
+ payslipsPeriodStartCell,
20
+ payslipsWagesPaidCell,
21
+ payrollYearStart,
22
+ } from "./payslips-layout.js";
23
+ import { rollPayslipsCachedDateChain } from "./payslips-date-chain.js";
24
+
25
+ // ── Deterministic zip output ───────────────────────────────────────────────
26
+ //
27
+ // When JSZip creates parent directory entries (e.g. "xl/") via zip.file(), it
28
+ // sets their date to new Date(). This makes output non-deterministic between
29
+ // process runs. stabilizeDirDates() normalises all auto-created directory
30
+ // entry timestamps to the DOS epoch (1980-01-01) before generateAsync().
31
+
32
+ const DOS_EPOCH = new Date("1980-01-01T00:00:00Z");
33
+
34
+ function stabilizeDirDates(zip) {
35
+ for (const entry of Object.values(zip.files)) {
36
+ if (entry.dir) {
37
+ entry.date = DOS_EPOCH;
38
+ }
39
+ }
40
+ }
41
+
42
+ // ── VAT return cycle ────────────────────────────────────────────────────────
43
+
44
+ // Months from the book's first month to each of the five return forms' default
45
+ // period ends. Every form steps a quarter on from the one before it, so Q1-Q4
46
+ // cover the twelve accounting months once each and Q5 is the quarter that
47
+ // follows them, ending three months past the year end. The fifth form is the
48
+ // one a business files when its VAT stagger runs behind its accounting year,
49
+ // and it lands on the last of the twenty periods the Vatinterface carries.
50
+ export const VAT_RETURN_END_MONTHS = [3, 6, 9, 12, 15];
51
+
52
+ // Salesinvoice.xlsx Product Details: one row a product, column D the VAT
53
+ // Rate the row's invoice lines charge (verified against the XML: dimension
54
+ // A1:H99, row 1 the header, D2:D99 every product row).
55
+ const SALESINVOICE_PRODUCT_DETAILS_VAT_RATE_COLUMN = "D";
56
+ const SALESINVOICE_PRODUCT_DETAILS_FIRST_ROW = 2;
57
+ const SALESINVOICE_PRODUCT_DETAILS_LAST_ROW = 99;
58
+
59
+ // ── Date helpers ────────────────────────────────────────────────────────────
60
+
61
+ export function lastDayOfMonth(year, month) {
62
+ return new Date(Date.UTC(year, month, 0)).getUTCDate();
63
+ }
64
+
65
+ export function monthEnd(year, month) {
66
+ return new Date(Date.UTC(year, month - 1, lastDayOfMonth(year, month)));
67
+ }
68
+
69
+ export function utcDate(year, month, day) {
70
+ return new Date(Date.UTC(year, month - 1, day));
71
+ }
72
+
73
+ // Excel serial number: days since 1899-12-30 (Excel epoch, includes the
74
+ // intentional 1900 leap year bug).
75
+ export function toExcelSerial(date) {
76
+ const epoch = Date.UTC(1899, 11, 30);
77
+ return Math.round((date.getTime() - epoch) / (24 * 60 * 60 * 1000));
78
+ }
79
+
80
+ export function fromExcelSerial(serial) {
81
+ const epoch = Date.UTC(1899, 11, 30);
82
+ return new Date(epoch + serial * 24 * 60 * 60 * 1000);
83
+ }
84
+
85
+ // ── Admin date generation ───────────────────────────────────────────────────
86
+
87
+ export function generateAdminDates(startYear) {
88
+ return {
89
+ B2: monthEnd(startYear, 2),
90
+ B3: monthEnd(startYear, 3),
91
+ B4: utcDate(startYear, 4, 6),
92
+ B5: monthEnd(startYear, 4),
93
+ B6: monthEnd(startYear, 5),
94
+ B7: monthEnd(startYear, 6),
95
+ B8: monthEnd(startYear, 7),
96
+ B9: monthEnd(startYear, 8),
97
+ B10: monthEnd(startYear, 9),
98
+ B11: monthEnd(startYear, 10),
99
+ B12: monthEnd(startYear, 11),
100
+ B13: monthEnd(startYear, 12),
101
+ B14: monthEnd(startYear + 1, 1),
102
+ B15: monthEnd(startYear + 1, 2),
103
+ B16: monthEnd(startYear + 1, 3),
104
+ B17: utcDate(startYear + 1, 4, 5),
105
+ B18: monthEnd(startYear + 1, 4),
106
+ B19: monthEnd(startYear + 1, 5),
107
+ B20: monthEnd(startYear + 1, 6),
108
+ B21: utcDate(startYear + 2, 1, 31),
109
+ B22: utcDate(startYear + 2, 7, 31),
110
+ };
111
+ }
112
+
113
+ // The Self Employed Vatinterface's last period ends three months past the tax
114
+ // year and its payment falls due a month after that, which is later than any
115
+ // date the Admin list above carries. Vat.xlsx reads it from Admin B25 across
116
+ // the external link. The BST and Taxi Admin sheets share the list above but
117
+ // have no VAT workbook, so the extra date is written only on the SE hub.
118
+ export function seVatPaymentDueDate(startYear) {
119
+ return { B25: monthEnd(startYear + 1, 7) };
120
+ }
121
+
122
+ // ── XML cell editing ────────────────────────────────────────────────────────
123
+
124
+ export function setCellValue(xml, cellRef, value) {
125
+ const match = matchCell(xml, cellRef);
126
+ if (!match) throw new Error(`Cell ${cellRef} not found in XML`);
127
+
128
+ const openTag = match.openTag.replace(/\s+t="[^"]*"/, "");
129
+ return xml.replace(match.fullMatch, `${openTag}><v>${value}</v></c>`);
130
+ }
131
+
132
+ // Replace only a formula cell's cached <v> value, preserving the <f> element.
133
+ // Writing a value equal to the existing one leaves the XML byte-identical.
134
+ export function setCellCachedValue(xml, cellRef, value) {
135
+ const match = matchCell(xml, cellRef);
136
+ if (!match) throw new Error(`Cell ${cellRef} not found in XML`);
137
+
138
+ const vMatch = match.fullMatch.match(/<v>[^<]*<\/v>/);
139
+ if (!vMatch) throw new Error(`Cell ${cellRef} has no cached <v> value`);
140
+
141
+ const newCell = match.fullMatch.replace(vMatch[0], `<v>${value}</v>`);
142
+ return xml.replace(match.fullMatch, newCell);
143
+ }
144
+
145
+ // Replace a formula cell's formula and the cached value it carries together.
146
+ // The cell has to be holding both already: a cell that has stopped being a
147
+ // formula is a template change the caller needs to see rather than overwrite.
148
+ export function setCellFormula(xml, cellRef, formula, value) {
149
+ const match = matchCell(xml, cellRef);
150
+ if (!match) throw new Error(`Cell ${cellRef} not found in XML`);
151
+ if (!/<f[^>]*>[^<]*<\/f>/.test(match.fullMatch)) throw new Error(`Cell ${cellRef} holds no formula to replace`);
152
+
153
+ const openTag = match.openTag.replace(/\s+t="[^"]*"/, "");
154
+ return xml.replace(match.fullMatch, `${openTag}><f>${escapeXml(formula)}</f><v>${value}</v></c>`);
155
+ }
156
+
157
+ export function setCellString(xml, cellRef, str) {
158
+ const match = matchCell(xml, cellRef);
159
+ if (!match) throw new Error(`Cell ${cellRef} not found in XML`);
160
+
161
+ let openTag = match.openTag.replace(/\s+t="[^"]*"/, "");
162
+ openTag += ` t="inlineStr"`;
163
+ return xml.replace(match.fullMatch, `${openTag}><is><t>${escapeXml(str)}</t></is></c>`);
164
+ }
165
+
166
+ // Match a cell element — handles both self-closing (<c .../>) and open/close (<c ...>...</c>).
167
+ function matchCell(xml, cellRef) {
168
+ // Try self-closing first: <c r="X" .../>
169
+ const selfClosing = new RegExp(`<c\\s+r="${cellRef}"\\s[^>]*?/>`, "s");
170
+ let m = xml.match(selfClosing);
171
+ if (m) {
172
+ const openTag = m[0].replace(/\s*\/>$/, "");
173
+ return { fullMatch: m[0], openTag };
174
+ }
175
+ // Try open/close: <c r="X" ...>...</c>
176
+ const withContent = new RegExp(`<c\\s+r="${cellRef}"\\s[^>]*?>[\\s\\S]*?</c>`, "s");
177
+ m = xml.match(withContent);
178
+ if (m) {
179
+ const openTag = m[0].replace(/>[\s\S]*$/, "");
180
+ return { fullMatch: m[0], openTag };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ function escapeXml(str) {
186
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
187
+ }
188
+
189
+ // ── Tax data → cell edits (BST/Taxi Admin) ─────────────────────────────────
190
+
191
+ export function buildCellEdits(taxData, startYear) {
192
+ const dates = generateAdminDates(startYear);
193
+ const ty = taxData.tax_year;
194
+ const it = taxData.income_tax;
195
+ const ni = taxData.national_insurance;
196
+ const ca = taxData.capital_allowances;
197
+ const dep = taxData.depreciation;
198
+ const mil = taxData.mileage;
199
+
200
+ const numericEdits = {};
201
+
202
+ for (const [cell, date] of Object.entries(dates)) {
203
+ numericEdits[cell] = toExcelSerial(date);
204
+ }
205
+
206
+ numericEdits.N4 = it.personal_allowance;
207
+ numericEdits.N5 = it.personal_allowance_taper_threshold;
208
+ numericEdits.N6 = it.starting_rate;
209
+ numericEdits.N7 = it.basic_rate;
210
+ numericEdits.N8 = it.higher_rate;
211
+ numericEdits.N9 = it.additional_rate;
212
+ numericEdits.N11 = it.starter_band_end;
213
+ numericEdits.M12 = it.basic_band_end;
214
+ numericEdits.N12 = 0;
215
+ numericEdits.L13 = it.higher_band_start;
216
+ numericEdits.N13 = it.higher_band_start;
217
+ // K12 and K13 are a shared-formula group (=N7, =N8); writing a value into
218
+ // K12 would orphan its follower. K14 sits outside the group.
219
+ numericEdits.K14 = it.additional_rate;
220
+ numericEdits.L14 = it.higher_band_end + 1;
221
+ numericEdits.N14 = it.higher_band_end;
222
+
223
+ numericEdits.L17 = ni.class2_rate;
224
+ numericEdits.N17 = ni.class2_small_profits_threshold; // SE Short box 36 caption reads this
225
+ numericEdits.L20 = ni.class4_lower_rate;
226
+ numericEdits.N20 = ni.class4_lower_limit;
227
+ numericEdits.L23 = ni.class4_upper_rate;
228
+ numericEdits.N23 = ni.class4_upper_limit;
229
+
230
+ numericEdits.G4 = ca.annual_investment_allowance;
231
+ numericEdits.G5 = ca.writing_down_allowance;
232
+
233
+ numericEdits.G13 = dep.land_and_property;
234
+ numericEdits.G14 = dep.plant_and_machinery;
235
+ numericEdits.G15 = dep.fixtures_and_fittings;
236
+ numericEdits.G16 = dep.computer_equipment;
237
+ numericEdits.G17 = dep.motor_vehicles;
238
+
239
+ numericEdits.F21 = mil.higher_rate_limit;
240
+ numericEdits.G21 = mil.higher_rate_pence;
241
+ numericEdits.F22 = mil.lower_rate_start;
242
+ numericEdits.G22 = mil.lower_rate_pence;
243
+
244
+ numericEdits.F26 = taxData.vat.registration_threshold;
245
+
246
+ const stringEdits = {
247
+ B23: ty.label,
248
+ B24: ty.next_label,
249
+ };
250
+
251
+ return { numericEdits, stringEdits };
252
+ }
253
+
254
+ // ── Tax data → cell edits (Taxi Admin) ─────────────────────────────────────
255
+ //
256
+ // The Taxi Admin income tax block opens on the basic rate, where BST opens on
257
+ // the starting rate. Every band row therefore sits one row higher than its BST
258
+ // counterpart, and NI Class 2 is on L16 rather than L17. The Taxi workbook
259
+ // reads Admin N4, N5, N6, N7, N8, N11, M11 and N13 for tax: writing the BST
260
+ // positions here leaves N6 holding the starting rate and M11 holding zero,
261
+ // which charges every pound above the personal allowance at the basic rate and
262
+ // never reaches the higher band.
263
+
264
+ export function buildTaxiCellEdits(taxData, startYear) {
265
+ const dates = generateAdminDates(startYear);
266
+ const ty = taxData.tax_year;
267
+ const it = taxData.income_tax;
268
+ const ni = taxData.national_insurance;
269
+ const ca = taxData.capital_allowances;
270
+ const dep = taxData.depreciation;
271
+ const mil = taxData.mileage;
272
+
273
+ const numericEdits = {};
274
+
275
+ // Dates — same positions as BST
276
+ for (const [cell, date] of Object.entries(dates)) {
277
+ numericEdits[cell] = toExcelSerial(date);
278
+ }
279
+
280
+ // Income tax — one row above the BST positions
281
+ numericEdits.N4 = it.personal_allowance;
282
+ numericEdits.N5 = it.personal_allowance_taper_threshold;
283
+ numericEdits.N6 = it.basic_rate; // BST: starting_rate at N6
284
+ numericEdits.N7 = it.higher_rate; // BST: basic_rate at N7
285
+ numericEdits.N8 = it.additional_rate; // BST: higher_rate at N8
286
+ numericEdits.K11 = it.basic_rate; // Display-only copy of the basic rate
287
+ numericEdits.N11 = it.starter_band_end;
288
+ numericEdits.M11 = it.basic_band_end; // BST: M12
289
+ numericEdits.K12 = it.higher_rate; // Display-only copy of the higher rate
290
+ numericEdits.L12 = it.higher_band_start; // BST: L13
291
+ numericEdits.N12 = it.higher_band_start; // BST: N13
292
+ numericEdits.K13 = it.additional_rate; // Display-only copy of the additional rate
293
+ numericEdits.L13 = it.higher_band_end + 1; // BST: L14
294
+ numericEdits.N13 = it.higher_band_end; // BST: N14
295
+
296
+ // NI — L16 not L17 for Class 2
297
+ numericEdits.L16 = ni.class2_weekly_rate; // BST: class2_rate at L17
298
+ numericEdits.N16 = ni.class2_small_profits_threshold; // SE Short box 36 caption reads this
299
+ numericEdits.L20 = ni.class4_lower_rate;
300
+ numericEdits.N20 = ni.class4_lower_limit;
301
+ numericEdits.L23 = ni.class4_upper_rate;
302
+ numericEdits.N23 = ni.class4_upper_limit;
303
+
304
+ // Capital allowances — same as BST
305
+ numericEdits.G4 = ca.annual_investment_allowance;
306
+ numericEdits.G5 = ca.writing_down_allowance;
307
+
308
+ // Depreciation — same as BST
309
+ numericEdits.G13 = dep.land_and_property;
310
+ numericEdits.G14 = dep.plant_and_machinery;
311
+ numericEdits.G15 = dep.fixtures_and_fittings;
312
+ numericEdits.G16 = dep.computer_equipment;
313
+ numericEdits.G17 = dep.motor_vehicles;
314
+
315
+ // Mileage — same as BST
316
+ numericEdits.F21 = mil.higher_rate_limit;
317
+ numericEdits.G21 = mil.higher_rate_pence;
318
+ numericEdits.F22 = mil.lower_rate_start;
319
+ numericEdits.G22 = mil.lower_rate_pence;
320
+
321
+ numericEdits.F26 = taxData.vat.registration_threshold;
322
+
323
+ const stringEdits = {
324
+ B23: ty.label,
325
+ B24: ty.next_label,
326
+ };
327
+
328
+ return { numericEdits, stringEdits };
329
+ }
330
+
331
+ // ── Tax data → cell edits (SE Financialaccounts Admin) ──────────────────────
332
+ //
333
+ // The SE Admin sheet has different cell positions from BST for income tax bands,
334
+ // NI Class 2, and VAT rate. Dates and other rates use the same positions.
335
+
336
+ export function buildSeCellEdits(taxData, startYear) {
337
+ const dates = { ...generateAdminDates(startYear), ...seVatPaymentDueDate(startYear) };
338
+ const ty = taxData.tax_year;
339
+ const it = taxData.income_tax;
340
+ const ni = taxData.national_insurance;
341
+ const ca = taxData.capital_allowances;
342
+ const dep = taxData.depreciation;
343
+ const mil = taxData.mileage;
344
+
345
+ const numericEdits = {};
346
+
347
+ // Dates — same positions as BST
348
+ for (const [cell, date] of Object.entries(dates)) {
349
+ numericEdits[cell] = toExcelSerial(date);
350
+ }
351
+
352
+ // Income tax — DIFFERENT cell positions from BST
353
+ numericEdits.N4 = it.personal_allowance;
354
+ numericEdits.N5 = it.personal_allowance_taper_threshold;
355
+ numericEdits.N6 = it.basic_rate; // BST: starting_rate at N6
356
+ numericEdits.N7 = it.higher_rate; // BST: basic_rate at N7
357
+ numericEdits.N8 = it.additional_rate; // BST: higher_rate at N8
358
+ numericEdits.K11 = it.basic_rate; // Display-only copy of basic rate
359
+ numericEdits.N11 = it.starter_band_end;
360
+ numericEdits.M11 = it.basic_band_end; // BST: M12
361
+ numericEdits.K12 = it.higher_rate; // Display-only copy of the higher rate
362
+ numericEdits.L12 = it.higher_band_start; // BST: L13
363
+ numericEdits.N12 = it.higher_band_start; // BST: N13
364
+ numericEdits.K13 = it.additional_rate; // Display-only copy of the additional rate
365
+ numericEdits.L13 = it.higher_band_end + 1; // BST: L14
366
+ numericEdits.N13 = it.higher_band_end; // BST: N14
367
+
368
+ // NI — L16 not L17 for Class 2
369
+ numericEdits.L16 = ni.class2_weekly_rate; // BST: class2_rate at L17
370
+ numericEdits.N16 = ni.class2_small_profits_threshold; // SE Short box 36 caption reads this
371
+ numericEdits.L20 = ni.class4_lower_rate;
372
+ numericEdits.N20 = ni.class4_lower_limit;
373
+ numericEdits.L23 = ni.class4_upper_rate;
374
+ numericEdits.N23 = ni.class4_upper_limit;
375
+
376
+ // Capital allowances — same as BST
377
+ numericEdits.G4 = ca.annual_investment_allowance;
378
+ numericEdits.G5 = ca.writing_down_allowance;
379
+
380
+ // Depreciation — same as BST
381
+ numericEdits.G13 = dep.land_and_property;
382
+ numericEdits.G14 = dep.plant_and_machinery;
383
+ numericEdits.G15 = dep.fixtures_and_fittings;
384
+ numericEdits.G16 = dep.computer_equipment;
385
+ numericEdits.G17 = dep.motor_vehicles;
386
+
387
+ // Mileage — same as BST
388
+ numericEdits.F21 = mil.higher_rate_limit;
389
+ numericEdits.G21 = mil.higher_rate_pence;
390
+ numericEdits.F22 = mil.lower_rate_start;
391
+ numericEdits.G22 = mil.lower_rate_pence;
392
+
393
+ // VAT — threshold same, standard rate is SE-only
394
+ numericEdits.F26 = taxData.vat.registration_threshold;
395
+ numericEdits.F27 = taxData.vat.standard_rate;
396
+
397
+ const stringEdits = {
398
+ B23: ty.label,
399
+ B24: ty.next_label,
400
+ };
401
+
402
+ return { numericEdits, stringEdits };
403
+ }
404
+
405
+ // ── Tax data → cell edits (Ltd Company Financialaccounts Admin) ─────────────
406
+ //
407
+ // The Ltd Admin is much simpler than BST/SE: F21 (year-end date) is the ONLY
408
+ // date cell to set — all other dates cascade via formulas. Tax rate cells use
409
+ // whole-number percentages (19 = 19%, 20 = 20%), not fractions.
410
+
411
+ export function buildLtdCellEdits(taxData, yearEndSerial) {
412
+ const ca = taxData.capital_allowances;
413
+ const dep = taxData.depreciation;
414
+ const mil = taxData.mileage;
415
+ const ct = taxData.corporation_tax;
416
+
417
+ const numericEdits = {};
418
+
419
+ // Year-end date — the ONE date cell. All others are formula-driven from F21.
420
+ numericEdits.F21 = yearEndSerial;
421
+
422
+ // Corporation Tax rates (stored as whole-number percentages in the spreadsheet)
423
+ numericEdits.P6 = Math.round(ct.small_profits_rate * 100);
424
+ numericEdits.P7 = Math.round(ct.small_profits_rate * 100);
425
+ numericEdits.P8 = Math.round(ct.main_rate * 100);
426
+
427
+ // Marginal relief: the fraction and the two profit limits it tapers between
428
+ numericEdits.P9 = ct.marginal_relief_fraction;
429
+ numericEdits.P12 = ct.small_profits_limit;
430
+ numericEdits.P13 = ct.main_rate_limit;
431
+
432
+ // Capital allowances (stored as whole-number percentages)
433
+ numericEdits.G5 = Math.round(ca.annual_investment_allowance * 100);
434
+ numericEdits.G7 = Math.round(ca.annual_investment_allowance * 100);
435
+ numericEdits.G6 = Math.round(ca.writing_down_allowance_main * 100);
436
+ numericEdits.G8 = Math.round(ca.writing_down_allowance_main * 100);
437
+
438
+ // Depreciation (stored as fractions — same as BST/SE)
439
+ numericEdits.G15 = dep.land_and_property;
440
+ numericEdits.G16 = dep.plant_and_machinery;
441
+ numericEdits.G17 = dep.fixtures_and_fittings;
442
+ numericEdits.G18 = dep.computer_equipment;
443
+ numericEdits.G19 = dep.motor_vehicles;
444
+
445
+ // Mileage
446
+ numericEdits.N16 = mil.higher_rate_limit;
447
+ numericEdits.O16 = mil.higher_rate_pence;
448
+ numericEdits.N17 = mil.lower_rate_start;
449
+ numericEdits.O17 = mil.lower_rate_pence;
450
+
451
+ // VAT rate (stored as whole-number percentage)
452
+ numericEdits.M19 = Math.round(taxData.vat.standard_rate * 100);
453
+ numericEdits.M21 = Math.round(taxData.vat.standard_rate * 100);
454
+
455
+ return { numericEdits, stringEdits: {} };
456
+ }
457
+
458
+ // ── Ltd Admin cached B-column date roll ─────────────────────────────────────
459
+ //
460
+ // The Ltd Admin B-column is a chain of formula cells anchored at B32 = F21:
461
+ // even rows cache monthEnd(yearEnd + (r-32)/2 months), odd rows cache the
462
+ // following day (the first of the next month). Spreadsheet apps updating
463
+ // links against a closed Financialaccounts.xlsx read these STORED cached
464
+ // values — they never recalculate — so the cached serials must agree with
465
+ // the F21 year-end literal, not the template's snapshot. Rolls every B-cell
466
+ // whose cached value matches the template's year-end-relative rule value;
467
+ // non-matching cached cells (labels, non-date content) are left untouched.
468
+
469
+ export function ltdAdminBColumnSerial(yearEndSerial, row) {
470
+ const monthsOffset = (row - (row % 2 === 0 ? 32 : 33)) / 2;
471
+ const anchor = fromExcelSerial(yearEndSerial);
472
+ const monthIndex = anchor.getUTCFullYear() * 12 + anchor.getUTCMonth() + monthsOffset;
473
+ const serial = toExcelSerial(monthEnd(Math.floor(monthIndex / 12), (monthIndex % 12) + 1));
474
+ // Odd rows hold the first day of the month after the preceding even row.
475
+ return row % 2 === 0 ? serial : serial + 1;
476
+ }
477
+
478
+ export function rollLtdAdminCachedDates(adminXml, templateYearEndSerial, yearEndSerial) {
479
+ const ruleValue = ltdAdminBColumnSerial;
480
+
481
+ const rows = new Set();
482
+ for (const [, rowStr] of adminXml.matchAll(/<c r="B(\d+)"/g)) {
483
+ rows.add(parseInt(rowStr, 10));
484
+ }
485
+
486
+ for (const row of rows) {
487
+ const match = matchCell(adminXml, `B${row}`);
488
+ const vMatch = match.fullMatch.match(/<v>([^<]*)<\/v>/);
489
+ if (!vMatch) continue;
490
+ if (parseFloat(vMatch[1]) !== ruleValue(templateYearEndSerial, row)) continue;
491
+ adminXml = setCellCachedValue(adminXml, `B${row}`, ruleValue(yearEndSerial, row));
492
+ }
493
+
494
+ const b32 = matchCell(adminXml, "B32");
495
+ const b32Value = b32 && b32.fullMatch.match(/<v>([^<]*)<\/v>/);
496
+ if (!b32Value || parseFloat(b32Value[1]) !== yearEndSerial) {
497
+ throw new Error(
498
+ `Admin B32 cached value ${b32Value ? b32Value[1] : "(missing)"} does not equal the F21 year-end serial ${yearEndSerial}`,
499
+ );
500
+ }
501
+
502
+ return adminXml;
503
+ }
504
+
505
+ // ── Ltd Admin corporation tax rate rows ─────────────────────────────────────
506
+ //
507
+ // The Admin rate table sets out the accounting period as the one or two UK
508
+ // financial years it falls in. Row 6 runs from the period start to the 31
509
+ // March inside the period (or to the year end, whichever comes first) and row
510
+ // 7 runs from the day after that to the year end, so a period wholly inside
511
+ // one financial year leaves row 7 empty. K6 and K7 name each row's financial
512
+ // year, which is the calendar year the 1 April before it started in.
513
+ //
514
+ // Fixedassets.xlsx reads Admin!N7 across the external link, and a spreadsheet
515
+ // app updating that link against a closed Financialaccounts.xlsx reads the
516
+ // STORED cached value rather than recalculating, so these six formula cells
517
+ // need their cached values rolled to the package's own year end.
518
+
519
+ export function ltdAdminFinancialYearRows(yearEndSerial) {
520
+ const yearEnd = fromExcelSerial(yearEndSerial);
521
+ const periodStart = fromExcelSerial(toExcelSerial(monthEnd(yearEnd.getUTCFullYear() - 1, yearEnd.getUTCMonth() + 1)) + 1);
522
+
523
+ let firstYearEnd = utcDate(periodStart.getUTCFullYear(), 3, 31);
524
+ if (firstYearEnd < periodStart) firstYearEnd = utcDate(periodStart.getUTCFullYear() + 1, 3, 31);
525
+ if (firstYearEnd > yearEnd) firstYearEnd = yearEnd;
526
+
527
+ const secondYearStart = fromExcelSerial(toExcelSerial(firstYearEnd) + 1);
528
+ const financialYearOf = (date) => date.getUTCFullYear() - (date.getUTCMonth() + 1 < 4 ? 1 : 0);
529
+
530
+ return {
531
+ K6: financialYearOf(periodStart),
532
+ L6: toExcelSerial(periodStart),
533
+ N6: toExcelSerial(firstYearEnd),
534
+ K7: financialYearOf(secondYearStart),
535
+ L7: toExcelSerial(secondYearStart),
536
+ N7: yearEndSerial,
537
+ };
538
+ }
539
+
540
+ export function rollLtdAdminCachedRateRows(adminXml, yearEndSerial) {
541
+ for (const [cellRef, value] of Object.entries(ltdAdminFinancialYearRows(yearEndSerial))) {
542
+ adminXml = setCellCachedValue(adminXml, cellRef, value);
543
+ }
544
+ return adminXml;
545
+ }
546
+
547
+ // Every Ltd Admin cell another workbook can cache across an external link,
548
+ // resolved to the value this package's Admin sheet holds: the rates and
549
+ // thresholds the generator writes, the two financial year rows, the B-column
550
+ // date chain, and the date cells that echo it.
551
+
552
+ export function ltdAdminCachedValues(taxData, yearEndSerial) {
553
+ const { numericEdits } = buildLtdCellEdits(taxData, yearEndSerial);
554
+ const values = { ...numericEdits, ...ltdAdminFinancialYearRows(yearEndSerial) };
555
+ for (let row = 2; row <= 56; row++) values[`B${row}`] = ltdAdminBColumnSerial(yearEndSerial, row);
556
+ values.F5 = values.B8;
557
+ values.F6 = values.B8;
558
+ values.F7 = values.B32;
559
+ values.F8 = values.B32;
560
+ values.L10 = values.B8;
561
+ values.N10 = values.B8;
562
+ values.L11 = values.B32;
563
+ values.N11 = values.B32;
564
+ return values;
565
+ }
566
+
567
+ // ── Ltd Financialaccounts cross-sheet cached values ─────────────────────────
568
+ //
569
+ // Several report sheets in the same Financialaccounts.xlsx workbook cache a
570
+ // formula result that reads the local Admin sheet directly (not across an
571
+ // external link): CorporationTax, CT600, PubP&L, PubBalSht, PubNotes and
572
+ // Report all echo the accounting period Admin!F21 and the two financial-year
573
+ // rows Admin!K6/L6/N6/K7/L7/N7 compute. Grouped by sheet name for
574
+ // rollDependentSheetCaches().
575
+
576
+ export function ltdFinancialaccountsDependentCaches(yearEndSerial) {
577
+ const rows = ltdAdminFinancialYearRows(yearEndSerial);
578
+ return {
579
+ "CorporationTax": {
580
+ E5: rows.L6, // =Admin!L6
581
+ H5: rows.N7, // =Admin!N7
582
+ E33: rows.K6, // =Admin!K6
583
+ E34: rows.K7, // =Admin!K7
584
+ A33: rows.N6 - rows.L6 + 1, // =D33-C33+1, D33=Admin!N6, C33=Admin!L6
585
+ A34: Math.max(0, rows.N7 - rows.L7 + 1), // =MAX(0,D34-C34+1), D34=Admin!N7, C34=Admin!L7
586
+ },
587
+ "CT600": {
588
+ B33: rows.L6, // =Admin!L6
589
+ M33: rows.N7, // =Admin!N7
590
+ C126: rows.K6, // =CorporationTax!E33
591
+ },
592
+ "PubP&L": {
593
+ D3: yearEndSerial, // =Admin!B32 (=F21)
594
+ E5: yearEndSerial, // =D3
595
+ },
596
+ "PubBalSht": { D2: yearEndSerial }, // ='PubP&L'!D3
597
+ "PubNotes": { A11: yearEndSerial }, // ='PubP&L'!D3
598
+ "Report": { F22: yearEndSerial }, // =PubBalSht!D2
599
+ };
600
+ }
601
+
602
+ // ── SE Financialaccounts cross-sheet cached values ──────────────────────────
603
+ //
604
+ // SE Full!G1 is "...by 31st January "&TEXT(Admin!B21,"yyyy") — B21 is always
605
+ // 31 January of the second calendar year after the tax year's start, so only
606
+ // the year needs rolling. G141, Q2 and V2 echo the local Admin sheet's
607
+ // writing-down allowance rate and tax-year start/end dates; SE Short!Q2
608
+ // echoes the same Admin!B4 date and S17 echoes SE Short!Q2 in turn.
609
+ // Profit Forecast!C40 is
610
+ // IF(C39<=0,0,MAX(0,Admin!N$4-MAX(0,C39-Admin!N$5)/2)); the generator never
611
+ // writes to Profit Forecast, 'Profit & Loss Account' or the Fixedassets
612
+ // external link C39's own formula reads, so C39 keeps the template's shipped
613
+ // 0 and C40 always resolves to the IF's first branch. SE Short!A33 is
614
+ // IF(D38>67000,"...exceeds...","...below £"&Admin!F26&" VAT threshold"): D38
615
+ // (turnover) is 'Profit & Loss Account'!B9, untouched by the generator and so
616
+ // always the template's shipped 0, which keeps A33 on the "below" branch;
617
+ // only the VAT threshold Admin!F26 echoes needs rolling. SE Short!C8 reads
618
+ // 'Business Details'!C5, which the generator never writes either, so it
619
+ // keeps the template's shipped blank and needs no roll. SE Short!N111 is
620
+ // "If your total profits for "&Admin!G2&" are less than £"&TEXT(Admin!N16,
621
+ // "#,##0")&" and you" (box 36, the voluntary Class 2 tick): the tax year
622
+ // rolls with Admin!G2 and the threshold with the new Admin!N16 cell.
623
+
624
+ function seShortClass2Caption(numericEdits) {
625
+ const startYear = fromExcelSerial(numericEdits.B4).getUTCFullYear();
626
+ const yearLabel = `${startYear}-${String((startYear + 1) % 100).padStart(2, "0")}`;
627
+ const threshold = numericEdits.N16.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
628
+ return `If your total profits for ${yearLabel} are less than £${threshold} and you`;
629
+ }
630
+
631
+ export function seFinancialaccountsDependentCaches(numericEdits) {
632
+ return {
633
+ "SE Full": {
634
+ G1: `COPY DETAILS TO HMRC FORM Submit HMRC RETURN ONLINE by 31st January ${fromExcelSerial(numericEdits.B21).getUTCFullYear()}`,
635
+ G141: numericEdits.G5, // =Admin!G5
636
+ Q2: numericEdits.B4, // =Admin!B4
637
+ V2: numericEdits.B17, // =Admin!B17
638
+ },
639
+ "SE Short": {
640
+ Q2: numericEdits.B4, // =Admin!B4
641
+ S17: numericEdits.B4, // =Q2 (=Admin!B4)
642
+ A33: `Business income - if your annual turnover was below £${numericEdits.F26} VAT threshold`,
643
+ N111: seShortClass2Caption(numericEdits),
644
+ },
645
+ "Profit Forecast": {
646
+ C40: 0,
647
+ },
648
+ };
649
+ }
650
+
651
+ // Write a { SheetName: { cellRef: value } } map of cached formula results
652
+ // into their sheets within an already-loaded workbook zip.
653
+ async function rollDependentSheetCaches(zip, sheetMap, editsBySheet) {
654
+ for (const [sheetName, cellEdits] of Object.entries(editsBySheet)) {
655
+ const sheetPath = sheetMap.get(sheetName);
656
+ if (!sheetPath) throw new Error(`Sheet ${sheetName} not found while rolling dependent caches`);
657
+ let sheetXml = await zip.file(sheetPath).async("string");
658
+ for (const [cellRef, value] of Object.entries(cellEdits)) {
659
+ sheetXml = setCellCachedValue(sheetXml, cellRef, value);
660
+ }
661
+ const originalDate = zip.file(sheetPath).date;
662
+ zip.file(sheetPath, sheetXml, { date: originalDate });
663
+ }
664
+ }
665
+
666
+ // ── Payslips Admin calendar generation ──────────────────────────────────────
667
+ //
668
+ // Generates the C (week), D (month), F (week-in-month) columns for the
669
+ // Payslips Admin sheet. These are hardcoded values — no formulas.
670
+ //
671
+ // Algorithm (verified against all 9 existing packages with zero mismatches):
672
+ // Week 1 = always 5 days (Apr 6–10)
673
+ // Weeks 2–52 = 7 days each (starting Apr 11)
674
+ // Week 53 = remainder (18 days, extending ~15 days past tax year end)
675
+ // Month pattern = fixed [4,4,5, 4,4,5, 4,4,5, 4,4,6] totalling 53 weeks
676
+
677
+ export function generatePayslipsCalendar(startYear) {
678
+ const WEEKS_PER_MONTH = [4, 4, 5, 4, 4, 5, 4, 4, 5, 4, 4, 6];
679
+ const TOTAL_ROWS = 380; // Apr 6 through ~Apr 20 next year
680
+
681
+ const edits = {};
682
+ let week = 1;
683
+ let month = 1;
684
+ let weekInMonth = 1;
685
+ let dayInWeek = 1;
686
+ let weeksInCurrentMonth = WEEKS_PER_MONTH[0];
687
+
688
+ for (let i = 0; i < TOTAL_ROWS; i++) {
689
+ const row = i + 2; // rows start at 2
690
+ edits[`C${row}`] = week;
691
+ edits[`D${row}`] = month;
692
+ edits[`F${row}`] = weekInMonth;
693
+
694
+ dayInWeek++;
695
+
696
+ // Week 1 = 5 days, all other weeks = 7 days (week 53 = 18 days)
697
+ const weekLength = week === 1 ? 5 : week < 53 ? 7 : 18;
698
+ if (dayInWeek > weekLength) {
699
+ dayInWeek = 1;
700
+ week++;
701
+
702
+ // Check if we've completed enough weeks for this month
703
+ if (weekInMonth >= weeksInCurrentMonth && month < 12) {
704
+ month++;
705
+ weekInMonth = 1;
706
+ weeksInCurrentMonth = WEEKS_PER_MONTH[month - 1];
707
+ } else {
708
+ weekInMonth++;
709
+ }
710
+ }
711
+ }
712
+
713
+ return edits;
714
+ }
715
+
716
+ // ── Payslips Admin cached date chain ────────────────────────────────────────
717
+ //
718
+ // The Payslips Admin sheet anchors a daily date chain at B2 (the tax year
719
+ // start, a generator-written literal): B3 = B2+1, B4 = B3+1, and so on down
720
+ // to B381, plus I1 = the day before the following year's B2 (the tax year
721
+ // end) and N1 = the "YYYY-YY" label built from I1's year. All of these are
722
+ // formula cells whose cached values still carry the template's own year
723
+ // until rolled to the package's own tax year.
724
+
725
+ export function rollPayslipsAdminCachedDates(payslipsXml, startYear) {
726
+ const startSerial = toExcelSerial(utcDate(startYear, 4, 6));
727
+
728
+ const rows = new Set();
729
+ for (const [, rowStr] of payslipsXml.matchAll(/<c r="B(\d+)"/g)) {
730
+ const row = parseInt(rowStr, 10);
731
+ if (row >= 3) rows.add(row);
732
+ }
733
+ for (const row of rows) {
734
+ const match = matchCell(payslipsXml, `B${row}`);
735
+ if (!match || !match.fullMatch.includes("<v>")) continue;
736
+ payslipsXml = setCellCachedValue(payslipsXml, `B${row}`, startSerial + (row - 2));
737
+ }
738
+
739
+ const endSerial = toExcelSerial(utcDate(startYear + 1, 4, 5));
740
+ payslipsXml = setCellCachedValue(payslipsXml, "I1", endSerial);
741
+ payslipsXml = setCellCachedValue(payslipsXml, "N1", `${startYear}-${startYear + 1 - 2000}`);
742
+
743
+ return payslipsXml;
744
+ }
745
+
746
+ // The daily chain's first and last rows. Rolling stops at the last because a
747
+ // reference past it reads a cell the chain never reaches.
748
+ const PAYSLIPS_ADMIN_FIRST_CALENDAR_ROW = 2;
749
+ const PAYSLIPS_ADMIN_CHAIN_LAST_ROW = 381;
750
+
751
+ // Every sheet in the Payslips workbook reads dates back off the Admin chain
752
+ // -- the month tabs their wages-paid and period dates, the Payment schedule
753
+ // its due dates, the Employee sheet its calendar column. Each of those cells
754
+ // keeps its own cached copy, which rolling the Admin sheet alone does not
755
+ // reach, so they would still print the template's year until the workbook was
756
+ // recalculated.
757
+ export function rollPayslipsAdminDateReads(sheetXml, startYear) {
758
+ const startSerial = toExcelSerial(utcDate(startYear, 4, 6));
759
+ let xml = sheetXml;
760
+ for (const [, cellRef, rowStr] of [...xml.matchAll(/<c\s+r="([A-Z]+\d+)"[^>]*><f>Admin!\$?B\$?(\d+)<\/f><v>[^<]*<\/v><\/c>/g)]) {
761
+ const row = parseInt(rowStr, 10);
762
+ if (row < 2 || row > PAYSLIPS_ADMIN_CHAIN_LAST_ROW) continue;
763
+ xml = setCellCachedValue(xml, cellRef, startSerial + (row - 2));
764
+ }
765
+ return xml;
766
+ }
767
+
768
+ // ── Sales date generation (Taxi Driver) ────────────────────────────────────
769
+
770
+ // Generate all weeks of the tax year as arrays of Date objects.
771
+ // First week: April 6 to first Sunday. Full weeks: Mon-Sun.
772
+ // Last week: last Monday to April 5 (may be partial).
773
+ export function generateTaxYearWeeks(startYear) {
774
+ const taxYearStart = utcDate(startYear, 4, 6);
775
+ const taxYearEnd = utcDate(startYear + 1, 4, 5);
776
+
777
+ const weeks = [];
778
+ const current = new Date(taxYearStart);
779
+
780
+ // First week: April 6 to first Sunday (inclusive)
781
+ const firstWeek = [];
782
+ do {
783
+ firstWeek.push(new Date(current));
784
+ if (current.getUTCDay() === 0) break; // Sunday
785
+ current.setUTCDate(current.getUTCDate() + 1);
786
+ } while (current <= taxYearEnd);
787
+ weeks.push(firstWeek);
788
+ current.setUTCDate(current.getUTCDate() + 1);
789
+
790
+ // Full Monday-Sunday weeks (last week may be partial ending Apr 5)
791
+ while (current <= taxYearEnd) {
792
+ const week = [];
793
+ for (let d = 0; d < 7 && current <= taxYearEnd; d++) {
794
+ week.push(new Date(current));
795
+ current.setUTCDate(current.getUTCDate() + 1);
796
+ }
797
+ weeks.push(week);
798
+ }
799
+
800
+ return weeks;
801
+ }
802
+
803
+ // Group weeks into monthly Sales sheets.
804
+ // Rule: a week belongs to the month containing its Sunday (last day if full).
805
+ // SalesMar collects all remaining weeks after February.
806
+ export function groupWeeksIntoMonths(weeks) {
807
+ const monthKeys = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
808
+ const result = {};
809
+ for (const k of monthKeys) result[k] = [];
810
+
811
+ // Process Apr(3) through Feb(1) in tax-year order
812
+ const monthOrder = [3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1];
813
+ let weekIdx = 0;
814
+
815
+ for (const monthIndex of monthOrder) {
816
+ while (weekIdx < weeks.length) {
817
+ const week = weeks[weekIdx];
818
+ const lastDay = week[week.length - 1];
819
+ if (lastDay.getUTCDay() !== 0) break; // no Sunday — partial last week
820
+ if (lastDay.getUTCMonth() !== monthIndex) break;
821
+ result[monthKeys[monthIndex]].push(week);
822
+ weekIdx++;
823
+ }
824
+ }
825
+
826
+ // All remaining weeks go to March (SalesMar)
827
+ while (weekIdx < weeks.length) {
828
+ result.mar.push(weeks[weekIdx]);
829
+ weekIdx++;
830
+ }
831
+
832
+ return result;
833
+ }
834
+
835
+ // Build the <sheetData> XML for one monthly Sales sheet.
836
+ // Returns { xml, lastRow } where xml is the inner content of <sheetData>.
837
+ export function buildSalesSheetXml(monthWeeks) {
838
+ const rows = [];
839
+ const weekCount = monthWeeks.length;
840
+
841
+ // Calculate total last row for column total formulas
842
+ let lastRow = 4; // start after header rows
843
+ for (let w = 0; w < weekCount; w++) {
844
+ const days = monthWeeks[w].length;
845
+ lastRow += days + 3; // days + rental + other income + subtotal
846
+ if (w < weekCount - 1) lastRow += 1; // blank separator (not after last week)
847
+ }
848
+
849
+ // Row 1: Column totals
850
+ rows.push(
851
+ `<row r="1" spans="1:6" s="302" customFormat="1" ht="12.75" customHeight="1" x14ac:dyDescent="0.15">` +
852
+ `<c r="A1" s="486" t="s"><v>241</v></c>` +
853
+ `<c r="B1" s="484" t="s"><v>240</v></c>` +
854
+ `<c r="C1" s="303" t="s"><v>239</v></c>` +
855
+ `<c r="D1" s="304"><f>SUM(D4:D${lastRow})</f><v>0</v></c>` +
856
+ `<c r="E1" s="303"><f>SUM(E4:E${lastRow})/2</f><v>0</v></c>` +
857
+ `<c r="F1" s="303"><f>SUM(F4:F${lastRow})/2</f><v>0</v></c>` +
858
+ `</row>`,
859
+ );
860
+
861
+ // Row 2: Column headers
862
+ rows.push(
863
+ `<row r="2" spans="1:6" s="302" customFormat="1" ht="12.75" customHeight="1" x14ac:dyDescent="0.15">` +
864
+ `<c r="A2" s="487"/><c r="B2" s="485"/>` +
865
+ `<c r="C2" s="482" t="s"><v>238</v></c>` +
866
+ `<c r="D2" s="488" t="s"><v>237</v></c>` +
867
+ `<c r="E2" s="482" t="s"><v>236</v></c>` +
868
+ `<c r="F2" s="482" t="s"><v>235</v></c>` +
869
+ `</row>`,
870
+ );
871
+
872
+ // Row 3: Column headers continued (merged)
873
+ rows.push(
874
+ `<row r="3" spans="1:6" s="301" customFormat="1" ht="24" customHeight="1" x14ac:dyDescent="0.15">` +
875
+ `<c r="A3" s="487"/><c r="B3" s="485"/>` +
876
+ `<c r="C3" s="490"/><c r="D3" s="489"/>` +
877
+ `<c r="E3" s="483"/><c r="F3" s="483"/>` +
878
+ `</row>`,
879
+ );
880
+
881
+ // Row 4: Blank separator
882
+ rows.push(`<row r="4" spans="1:6" ht="14" thickBot="1" x14ac:dyDescent="0.2"/>`);
883
+
884
+ let currentRow = 5;
885
+
886
+ for (let w = 0; w < weekCount; w++) {
887
+ const days = monthWeeks[w];
888
+ const firstDayRow = currentRow;
889
+
890
+ // Day rows
891
+ for (let d = 0; d < days.length; d++) {
892
+ const serial = toExcelSerial(days[d]);
893
+ const r = currentRow;
894
+ if (d === 0) {
895
+ // First day of week — special styles with empty editable cells
896
+ rows.push(
897
+ `<row r="${r}" spans="1:6" x14ac:dyDescent="0.15">` +
898
+ `<c r="A${r}" s="298"><v>${serial}</v></c>` +
899
+ `<c r="B${r}" s="297"><v>${serial}</v></c>` +
900
+ `<c r="C${r}" s="296"/><c r="D${r}" s="295"/>` +
901
+ `<c r="E${r}" s="294"/><c r="F${r}" s="293"/>` +
902
+ `</row>`,
903
+ );
904
+ } else {
905
+ rows.push(
906
+ `<row r="${r}" spans="1:6" x14ac:dyDescent="0.15">` +
907
+ `<c r="A${r}" s="292"><v>${serial}</v></c>` +
908
+ `<c r="B${r}" s="285"><v>${serial}</v></c>` +
909
+ `<c r="F${r}" s="291"/>` +
910
+ `</row>`,
911
+ );
912
+ }
913
+ currentRow++;
914
+ }
915
+
916
+ // Rental due row — date = last day of the week
917
+ const lastDaySerial = toExcelSerial(days[days.length - 1]);
918
+ rows.push(
919
+ `<row r="${currentRow}" spans="1:6" x14ac:dyDescent="0.15">` +
920
+ `<c r="A${currentRow}" s="292"><v>${lastDaySerial}</v></c>` +
921
+ `<c r="B${currentRow}" s="285" t="s"><v>234</v></c>` +
922
+ `<c r="F${currentRow}" s="291"/>` +
923
+ `</row>`,
924
+ );
925
+ currentRow++;
926
+
927
+ // Any other income row
928
+ rows.push(
929
+ `<row r="${currentRow}" spans="1:6" x14ac:dyDescent="0.15">` +
930
+ `<c r="A${currentRow}" s="292"><v>${lastDaySerial}</v></c>` +
931
+ `<c r="B${currentRow}" s="285" t="s"><v>233</v></c>` +
932
+ `<c r="F${currentRow}" s="291"/>` +
933
+ `</row>`,
934
+ );
935
+ const lastDataRow = currentRow;
936
+ currentRow++;
937
+
938
+ // Subtotal row
939
+ rows.push(
940
+ `<row r="${currentRow}" spans="1:6" ht="14" thickBot="1" x14ac:dyDescent="0.2">` +
941
+ `<c r="A${currentRow}" s="290"/><c r="B${currentRow}" s="289"/>` +
942
+ `<c r="C${currentRow}" s="287"/><c r="D${currentRow}" s="288"/>` +
943
+ `<c r="E${currentRow}" s="300"><f>SUM(E${firstDayRow}:E${lastDataRow})</f><v>0</v></c>` +
944
+ `<c r="F${currentRow}" s="299"><f>SUM(F${firstDayRow}:F${lastDataRow})</f><v>0</v></c>` +
945
+ `</row>`,
946
+ );
947
+ currentRow++;
948
+
949
+ // Blank separator (not after last week)
950
+ if (w < weekCount - 1) {
951
+ rows.push(`<row r="${currentRow}" spans="1:6" ht="14" thickBot="1" x14ac:dyDescent="0.2"/>`);
952
+ currentRow++;
953
+ }
954
+ }
955
+
956
+ return { xml: rows.join(""), lastRow: currentRow - 1 };
957
+ }
958
+
959
+ // Replace the <sheetData> and <dimension> in a Sales sheet XML.
960
+ function replaceSalesSheetData(sheetXml, monthWeeks) {
961
+ const { xml: newData, lastRow } = buildSalesSheetXml(monthWeeks);
962
+
963
+ // Update dimension
964
+ sheetXml = sheetXml.replace(/<dimension ref="[^"]*"\/>/, `<dimension ref="A1:F${lastRow}"/>`);
965
+
966
+ // Replace sheetData content
967
+ sheetXml = sheetXml.replace(/<sheetData>[\s\S]*<\/sheetData>/, `<sheetData>${newData}</sheetData>`);
968
+
969
+ return sheetXml;
970
+ }
971
+
972
+ // ── Generate one spreadsheet ────────────────────────────────────────────────
973
+
974
+ // A workbook.xml that asks the spreadsheet application to recalculate every
975
+ // formula when the file is opened, so cached values written by the template
976
+ // or by a cell write are replaced with the figures the book implies.
977
+ function withFullCalcOnLoad(wbXml) {
978
+ if (wbXml.includes('fullCalcOnLoad="1"')) return wbXml;
979
+ const set = wbXml.replace(/(<calcPr[^/]*)\/?>/, '$1 fullCalcOnLoad="1"/>');
980
+ if (set === wbXml) throw new Error("workbook.xml has no calcPr element to set fullCalcOnLoad on");
981
+ return set;
982
+ }
983
+
984
+ // The same setting, applied to a finished workbook. A workbook that already
985
+ // carries it comes back as the same bytes, so a caller can ask for it on
986
+ // every file of a package whether or not generateSpreadsheet touched that one.
987
+ export async function setFullCalcOnLoad(xlsxBuffer) {
988
+ const zip = await JSZip.loadAsync(xlsxBuffer);
989
+ const wbXml = await zip.file("xl/workbook.xml").async("string");
990
+ const set = withFullCalcOnLoad(wbXml);
991
+ if (set === wbXml) return xlsxBuffer;
992
+
993
+ zip.file("xl/workbook.xml", set, { date: zip.file("xl/workbook.xml").date });
994
+ stabilizeDirDates(zip);
995
+ return zip.generateAsync({
996
+ type: "uint8array",
997
+ compression: "DEFLATE",
998
+ compressionOptions: { level: 6 },
999
+ });
1000
+ }
1001
+
1002
+ export async function generateSpreadsheet(templateBuffer, taxData, sheetsConfig) {
1003
+ // SE/BST use tax_year, Ltd uses financial_year
1004
+ const yearInfo = taxData.tax_year || taxData.financial_year;
1005
+ const startDate = new Date(yearInfo.start);
1006
+ const startYear = startDate.getUTCFullYear();
1007
+ const endDate = new Date(yearInfo.end);
1008
+
1009
+ const zip = await JSZip.loadAsync(templateBuffer);
1010
+
1011
+ // Admin sheet edits — dispatch to product-specific cell edit function
1012
+ if (sheetsConfig.admin) {
1013
+ let adminXml = await zip.file(sheetsConfig.admin).async("string");
1014
+
1015
+ let numericEdits, stringEdits;
1016
+ let templateYearEndSerial;
1017
+ if (sheetsConfig.cellEditFn === "ltd") {
1018
+ const yearEndSerial = toExcelSerial(endDate);
1019
+ ({ numericEdits, stringEdits } = buildLtdCellEdits(taxData, yearEndSerial));
1020
+ // Capture the template's own year-end before the F21 edit overwrites it —
1021
+ // it anchors the cached B-column roll below.
1022
+ const templateF21 = matchCell(adminXml, "F21");
1023
+ const templateF21Value = templateF21 && templateF21.fullMatch.match(/<v>([^<]*)<\/v>/);
1024
+ if (!templateF21Value) throw new Error("Admin F21 has no year-end value in the template");
1025
+ templateYearEndSerial = parseFloat(templateF21Value[1]);
1026
+ } else {
1027
+ const buildFn = { se: buildSeCellEdits, taxi: buildTaxiCellEdits }[sheetsConfig.cellEditFn] ?? buildCellEdits;
1028
+ ({ numericEdits, stringEdits } = buildFn(taxData, startYear));
1029
+ }
1030
+
1031
+ for (const [cellRef, value] of Object.entries(numericEdits)) {
1032
+ adminXml = setCellValue(adminXml, cellRef, value);
1033
+ }
1034
+ for (const [cellRef, str] of Object.entries(stringEdits)) {
1035
+ adminXml = setCellString(adminXml, cellRef, str);
1036
+ }
1037
+
1038
+ if (sheetsConfig.cellEditFn === "ltd") {
1039
+ adminXml = rollLtdAdminCachedDates(adminXml, templateYearEndSerial, toExcelSerial(endDate));
1040
+ adminXml = rollLtdAdminCachedRateRows(adminXml, toExcelSerial(endDate));
1041
+ }
1042
+
1043
+ const originalDate = zip.file(sheetsConfig.admin).date;
1044
+ zip.file(sheetsConfig.admin, adminXml, { date: originalDate });
1045
+
1046
+ // Other report sheets in this same workbook cache a formula result that
1047
+ // reads the local Admin sheet directly; roll those to match.
1048
+ if (sheetsConfig.cellEditFn === "ltd" || sheetsConfig.cellEditFn === "se") {
1049
+ const sheetMap = await buildSheetMap(zip);
1050
+ const editsBySheet =
1051
+ sheetsConfig.cellEditFn === "ltd"
1052
+ ? ltdFinancialaccountsDependentCaches(toExcelSerial(endDate))
1053
+ : seFinancialaccountsDependentCaches(numericEdits);
1054
+ await rollDependentSheetCaches(zip, sheetMap, editsBySheet);
1055
+ }
1056
+ }
1057
+
1058
+ // Fixedassets reads the Admin sheet's allowance rates and the accounting
1059
+ // period across its external link. A spreadsheet app updating that link
1060
+ // against a closed Financialaccounts.xlsx reads this cache until the user
1061
+ // refreshes it, so it has to carry this package's values, not the
1062
+ // template's snapshot.
1063
+ if (sheetsConfig.adminExternalLink) {
1064
+ const linkPath = sheetsConfig.adminExternalLink;
1065
+ const relsPath = linkPath.replace(/externalLinks\/(externalLink\d+)\.xml$/, "externalLinks/_rels/$1.xml.rels");
1066
+ const relsXml = await zip.file(relsPath).async("string");
1067
+ if (!relsXml.includes('Target="Financialaccounts.xlsx"')) {
1068
+ throw new Error(`${linkPath} does not target Financialaccounts.xlsx`);
1069
+ }
1070
+
1071
+ const adminValues = ltdAdminCachedValues(taxData, toExcelSerial(endDate));
1072
+ const linkXmlOriginal = await zip.file(linkPath).async("string");
1073
+ const sheetNames = [...linkXmlOriginal.matchAll(/<sheetName val="([^"]*)"/g)].map((m) => m[1].replace(/&amp;/g, "&"));
1074
+ const adminSheetId = sheetNames.indexOf("Admin");
1075
+ if (adminSheetId < 0) throw new Error(`${linkPath} lists no Admin sheet`);
1076
+
1077
+ const block = linkXmlOriginal.match(new RegExp(`<sheetData sheetId="${adminSheetId}">[\\s\\S]*?</sheetData>`));
1078
+ if (!block) throw new Error(`${linkPath} caches no Admin cells`);
1079
+ const rolledBlock = block[0].replace(/<cell r="([A-Z]+\d+)"([^>]*)><v>[^<]*<\/v><\/cell>/g, (_match, cellRef, attrs) => {
1080
+ if (adminValues[cellRef] === undefined) {
1081
+ throw new Error(`${linkPath} caches Admin!${cellRef}, which has no generated value`);
1082
+ }
1083
+ return `<cell r="${cellRef}"${attrs}><v>${adminValues[cellRef]}</v></cell>`;
1084
+ });
1085
+
1086
+ const linkXml = linkXmlOriginal.replace(block[0], rolledBlock);
1087
+ if (linkXml !== linkXmlOriginal) {
1088
+ zip.file(linkPath, linkXml, { date: zip.file(linkPath).date, createFolders: false });
1089
+ }
1090
+ }
1091
+
1092
+ // Sales sheet generation (Taxi only — when sheetsConfig.sales is present)
1093
+ if (sheetsConfig.sales) {
1094
+ const weeks = generateTaxYearWeeks(startYear);
1095
+ const monthlyData = groupWeeksIntoMonths(weeks);
1096
+ const monthKeys = ["apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "jan", "feb", "mar"];
1097
+
1098
+ for (const monthKey of monthKeys) {
1099
+ const sheetPath = sheetsConfig.sales[monthKey];
1100
+ if (!sheetPath || !monthlyData[monthKey].length) continue;
1101
+
1102
+ let sheetXml = await zip.file(sheetPath).async("string");
1103
+ sheetXml = replaceSalesSheetData(sheetXml, monthlyData[monthKey]);
1104
+
1105
+ const origDate = zip.file(sheetPath).date;
1106
+ zip.file(sheetPath, sheetXml, { date: origDate });
1107
+ }
1108
+
1109
+ // Remove calcChain.xml — the generated Sales sheets have different formulas
1110
+ // than the template, so the cached chain is stale. fullCalcOnLoad="1" ensures
1111
+ // Excel rebuilds it from scratch on first open.
1112
+ if (zip.file("xl/calcChain.xml")) {
1113
+ zip.remove("xl/calcChain.xml");
1114
+ }
1115
+ }
1116
+
1117
+ // Fix Home sheet HYPERLINKs: replace filename-based links (HYPERLINK(B3&"'Sheet'!Cell"))
1118
+ // with intra-workbook # links (HYPERLINK("#'Sheet'!Cell")) so they work regardless of filename.
1119
+ if (sheetsConfig.home) {
1120
+ let homeXml = await zip.file(sheetsConfig.home).async("string");
1121
+ if (homeXml.includes('B3&amp;"')) {
1122
+ homeXml = homeXml.replace(/HYPERLINK\(B3&amp;"'/g, `HYPERLINK("#'`);
1123
+ const homeDate = zip.file(sheetsConfig.home).date;
1124
+ zip.file(sheetsConfig.home, homeXml, { date: homeDate });
1125
+ }
1126
+ }
1127
+
1128
+ // Payslips Admin calendar generation (when sheetsConfig.payslipsAdmin is present)
1129
+ if (sheetsConfig.payslipsAdmin) {
1130
+ let payslipsXml = await zip.file(sheetsConfig.payslipsAdmin).async("string");
1131
+
1132
+ // Set B2 = tax year start date (all other dates cascade via shared formulas)
1133
+ const taxYearStartSerial = toExcelSerial(utcDate(startYear, 4, 6));
1134
+ payslipsXml = setCellValue(payslipsXml, "B2", taxYearStartSerial);
1135
+
1136
+ // Regenerate C (week), D (month), F (week-in-month) — hardcoded values
1137
+ const calendarEdits = generatePayslipsCalendar(startYear);
1138
+ for (const [cellRef, value] of Object.entries(calendarEdits)) {
1139
+ payslipsXml = setCellValue(payslipsXml, cellRef, value);
1140
+ }
1141
+
1142
+ // Roll the B3:B381 daily date chain and its I1/N1 dependents to this
1143
+ // package's tax year.
1144
+ payslipsXml = rollPayslipsAdminCachedDates(payslipsXml, startYear);
1145
+
1146
+ const payslipsDate = zip.file(sheetsConfig.payslipsAdmin).date;
1147
+ zip.file(sheetsConfig.payslipsAdmin, payslipsXml, { date: payslipsDate });
1148
+
1149
+ // Roll the cached copies the workbook's other sheets keep of the same
1150
+ // chain, so a package that is never recalculated still shows its own
1151
+ // year's dates on the month tabs and the PAYE payment schedule.
1152
+ for (const file of zip.file(/^xl\/worksheets\/sheet\d+\.xml$/)) {
1153
+ if (file.name === sheetsConfig.payslipsAdmin) continue;
1154
+ const rolled = rollPayslipsAdminDateReads(await file.async("string"), startYear);
1155
+ zip.file(file.name, rolled, { date: file.date });
1156
+ }
1157
+
1158
+ // Only the seeds of the weekly payroll chain read the Admin calendar. The
1159
+ // blocks below and after them count days off each other, across tabs, so
1160
+ // the roll above leaves them on the template's year. Recompute those from
1161
+ // their own formulas over the calendar just written.
1162
+ const payslipsSheetPaths = await buildSheetMap(zip);
1163
+ const payslipsSheetXmls = new Map();
1164
+ for (const [name, path] of payslipsSheetPaths) payslipsSheetXmls.set(name, await zip.file(path).async("string"));
1165
+ const chained = rollPayslipsCachedDateChain(payslipsSheetXmls, startYear, await loadSharedStrings(zip), setCellCachedValue);
1166
+ for (const [name, xml] of chained) {
1167
+ if (xml === payslipsSheetXmls.get(name)) continue;
1168
+ const path = payslipsSheetPaths.get(name);
1169
+ zip.file(path, xml, { date: zip.file(path).date });
1170
+ }
1171
+
1172
+ // The month boundaries the workbook states: the days each tab's monthly
1173
+ // payroll block covers, and the two dates on each row of the PAYE
1174
+ // schedule. The template reaches all of them by counting a fixed number of
1175
+ // days down the calendar, and no count is right for both a leap payroll
1176
+ // year and a common one, so they are written as the dates they are. A tab
1177
+ // renamed for another year end moves its block on to the accounting
1178
+ // period's months afterwards.
1179
+ const payrollYearOpens = utcDate(startYear, 4, 6);
1180
+ await datePayslipsMonthTabPeriods(zip, payslipsSheetPaths, payrollYearOpens);
1181
+ await datePayslipsPaymentSchedule(zip, payslipsSheetPaths, payrollYearOpens);
1182
+ }
1183
+
1184
+ // Expenses claim form (Ltd only — when sheetsConfig.mileageMonth is
1185
+ // present). The mileage rate is a literal on the first month's sheet and
1186
+ // every other month chains from it, so one write moves the caption, the
1187
+ // rate and the claim on all twelve.
1188
+ if (sheetsConfig.mileageMonth) {
1189
+ let monthXml = await zip.file(sheetsConfig.mileageMonth).async("string");
1190
+ monthXml = setCellValue(monthXml, "C30", taxData.mileage.higher_rate_pence);
1191
+ const monthDate = zip.file(sheetsConfig.mileageMonth).date;
1192
+ zip.file(sheetsConfig.mileageMonth, monthXml, { date: monthDate });
1193
+ }
1194
+
1195
+ // Sales invoice VAT rate (Salesinvoice.xlsx Product Details, SE and Ltd
1196
+ // only, when sheetsConfig.productDetails is present). The template hard-
1197
+ // codes every product row's "VAT Rate" column at a literal 20, with no tie
1198
+ // to the tax year the invoice is raised in (discovered from the XML:
1199
+ // Product Details!D2:D99, header D1 the shared string "VAT Rate"). This
1200
+ // workbook has no external link into the rest of the book, so the wrong
1201
+ // figure never reached the accounts -- it reached the customer's customer.
1202
+ if (sheetsConfig.productDetails) {
1203
+ let productDetailsXml = await zip.file(sheetsConfig.productDetails).async("string");
1204
+ const vatRatePercent = Math.round(taxData.vat.standard_rate * 100);
1205
+ for (let row = SALESINVOICE_PRODUCT_DETAILS_FIRST_ROW; row <= SALESINVOICE_PRODUCT_DETAILS_LAST_ROW; row++) {
1206
+ productDetailsXml = setCellValue(productDetailsXml, `${SALESINVOICE_PRODUCT_DETAILS_VAT_RATE_COLUMN}${row}`, vatRatePercent);
1207
+ }
1208
+ const productDetailsDate = zip.file(sheetsConfig.productDetails).date;
1209
+ zip.file(sheetsConfig.productDetails, productDetailsXml, { date: productDetailsDate });
1210
+ }
1211
+
1212
+ // VAT quarter dates (when sheetsConfig has vatQtr1..vatQtr5): write each
1213
+ // return form's default G5 from VAT_RETURN_END_MONTHS, then roll the whole
1214
+ // cached date chain — the externalLink1 Admin cache, the Vatinterface cached
1215
+ // values, and each form's K2:K16 dropdown list — to this package's year.
1216
+ if (sheetsConfig.vatQtr1) {
1217
+ if (!sheetsConfig.vatinterface) {
1218
+ throw new Error("sheetsConfig has vatQtr sheets but no vatinterface path");
1219
+ }
1220
+
1221
+ // The first of the book's twelve month tabs, which is also the first
1222
+ // accounting-year period the Vatinterface carries. A year that ends on a
1223
+ // month end starts the month after, so year-end Mar 2026 gives Apr 2025.
1224
+ // A Self Employed year ends on 5 April, mid-month, and its tabs still run
1225
+ // April to March, so it takes the month its own start date falls in.
1226
+ const yearEndMonth = endDate.getUTCMonth() + 1; // 1-indexed
1227
+ const yearEndYear = endDate.getUTCFullYear();
1228
+ const yearEndsOnMonthEnd = endDate.getUTCDate() === lastDayOfMonth(yearEndYear, yearEndMonth);
1229
+ const vatStartMonth = yearEndsOnMonthEnd ? (yearEndMonth % 12) + 1 : startDate.getUTCMonth() + 1;
1230
+ const vatStartYear = yearEndsOnMonthEnd ? (vatStartMonth > yearEndMonth ? yearEndYear - 1 : yearEndYear) : startYear;
1231
+
1232
+ // Admin B-column serials this package's Financialaccounts will hold.
1233
+ const adminB = {};
1234
+ if (taxData.financial_year) {
1235
+ // Ltd: the generated Admin B-column is year-end-relative around the
1236
+ // B32 = F21 anchor — B{r} = month end of (yearEnd + (r-32)/2 months).
1237
+ for (let r = 6; r <= 40; r += 2) {
1238
+ const monthIndex = yearEndYear * 12 + (yearEndMonth - 1) + (r - 32) / 2;
1239
+ adminB[r] = toExcelSerial(monthEnd(Math.floor(monthIndex / 12), (monthIndex % 12) + 1));
1240
+ }
1241
+ } else {
1242
+ // SE: the same B-column dates buildSeCellEdits writes into the
1243
+ // Financialaccounts Admin sheet.
1244
+ for (const [cell, date] of Object.entries({ ...generateAdminDates(startYear), ...seVatPaymentDueDate(startYear) })) {
1245
+ adminB[parseInt(cell.slice(1), 10)] = toExcelSerial(date);
1246
+ }
1247
+ }
1248
+
1249
+ // Roll the externalLink1.xml Admin cache (the [1]Financialaccounts link).
1250
+ const extLinkPath = "xl/externalLinks/externalLink1.xml";
1251
+ const extRelsXml = await zip.file("xl/externalLinks/_rels/externalLink1.xml.rels").async("string");
1252
+ if (!extRelsXml.includes('Target="Financialaccounts.xlsx"')) {
1253
+ throw new Error("externalLink1.xml.rels does not target Financialaccounts.xlsx");
1254
+ }
1255
+ const extXmlOriginal = await zip.file(extLinkPath).async("string");
1256
+ const extXml = extXmlOriginal.replace(/<cell r="B(\d+)"([^>]*)><v>[^<]*<\/v><\/cell>/g, (m, rowStr, attrs) => {
1257
+ const row = parseInt(rowStr, 10);
1258
+ if (adminB[row] === undefined) {
1259
+ throw new Error(`externalLink1.xml caches Admin!B${row}, which has no generated value`);
1260
+ }
1261
+ return `<cell r="B${rowStr}"${attrs}><v>${adminB[row]}</v></cell>`;
1262
+ });
1263
+ // Rewrite only on change: an untouched entry keeps its original compressed
1264
+ // bytes, which keeps template-year output byte-identical.
1265
+ if (extXml !== extXmlOriginal) {
1266
+ zip.file(extLinkPath, extXml, { date: zip.file(extLinkPath).date, createFolders: false });
1267
+ }
1268
+
1269
+ // Roll the Vatinterface cached values by resolving each cell's own formula.
1270
+ const viPath = sheetsConfig.vatinterface;
1271
+ const viXmlOriginal = await zip.file(viPath).async("string");
1272
+ let viXml = viXmlOriginal;
1273
+ const viValues = {}; // Vatinterface cell ref → serial just written
1274
+ for (const [, cellRef, rowStr] of viXml.matchAll(/<c r="([A-Z]+\d+)"[^>]*><f>\[1\]Admin!\$B\$(\d+)<\/f>/g)) {
1275
+ const row = parseInt(rowStr, 10);
1276
+ if (adminB[row] === undefined) {
1277
+ throw new Error(`Vatinterface ${cellRef} references [1]Admin!$B$${row}, which has no generated value`);
1278
+ }
1279
+ viXml = setCellCachedValue(viXml, cellRef, adminB[row]);
1280
+ viValues[cellRef] = adminB[row];
1281
+ }
1282
+ for (const [, rowStr] of viXml.matchAll(/\[1\]Admin!\$B\$(\d+)/g)) {
1283
+ if (adminB[parseInt(rowStr, 10)] === undefined) {
1284
+ throw new Error(`Vatinterface has an unresolved [1]Admin!$B$${rowStr} reference`);
1285
+ }
1286
+ }
1287
+
1288
+ // Roll the Vatinterface C4:C18 column, which reads the next row's B
1289
+ // column rather than the external link directly: C4's own formula is
1290
+ // "B5", and C5:C18 share that same +1 row offset via a shared formula
1291
+ // anchored at C5 = "B6". Read both anchors from the XML rather than
1292
+ // assuming the offset.
1293
+ const c4Formula = matchCell(viXml, "C4")?.fullMatch.match(/<f[^>]*>B(\d+)<\/f>/);
1294
+ const c5Formula = matchCell(viXml, "C5")?.fullMatch.match(/<f[^>]*>B(\d+)<\/f>/);
1295
+ if (!c4Formula || !c5Formula) {
1296
+ throw new Error("Vatinterface C4/C5 do not have the expected B-column formula");
1297
+ }
1298
+ const cToBOffset = parseInt(c4Formula[1], 10) - 4;
1299
+ if (parseInt(c5Formula[1], 10) - 5 !== cToBOffset) {
1300
+ throw new Error("Vatinterface C4 and C5 formulas do not share the same row offset to column B");
1301
+ }
1302
+ for (let r = 4; r <= 18; r++) {
1303
+ const sourceRef = `B${r + cToBOffset}`;
1304
+ if (viValues[sourceRef] === undefined) {
1305
+ throw new Error(`Vatinterface C${r} resolves to ${sourceRef}, which has no generated value`);
1306
+ }
1307
+ viXml = setCellCachedValue(viXml, `C${r}`, viValues[sourceRef]);
1308
+ viValues[`C${r}`] = viValues[sourceRef];
1309
+ }
1310
+
1311
+ if (viXml !== viXmlOriginal) {
1312
+ zip.file(viPath, viXml, { date: zip.file(viPath).date, createFolders: false });
1313
+ }
1314
+
1315
+ // Vatinterface B4:B20/C4:C20 as (b, c) pairs, ascending by date, for
1316
+ // simulating each quarter's G7 = LOOKUP(G$5, Vatinterface!B:B, C:C).
1317
+ const lookupRows = [];
1318
+ for (let r = 4; r <= 20; r++) {
1319
+ const b = viValues[`B${r}`];
1320
+ const c = viValues[`C${r}`];
1321
+ if (b !== undefined && c !== undefined) lookupRows.push({ b, c });
1322
+ }
1323
+ lookupRows.sort((a, b) => a.b - b.b);
1324
+
1325
+ for (let q = 1; q <= 5; q++) {
1326
+ const sheetPath = sheetsConfig[`vatQtr${q}`];
1327
+ if (!sheetPath) continue;
1328
+
1329
+ const monthsFromStart = VAT_RETURN_END_MONTHS[q - 1];
1330
+ const totalMonth = vatStartMonth + monthsFromStart - 1;
1331
+ const qMonth = ((totalMonth - 1) % 12) + 1;
1332
+ const qYear = vatStartYear + Math.floor((totalMonth - 1) / 12);
1333
+ const quarterEnd = monthEnd(qYear, qMonth);
1334
+ const serial = toExcelSerial(quarterEnd);
1335
+
1336
+ let sheetXml = await zip.file(sheetPath).async("string");
1337
+ sheetXml = setCellValue(sheetXml, "G5", serial);
1338
+
1339
+ // Roll G7 = LOOKUP(G$5, Vatinterface!B:B, Vatinterface!C:C): the C
1340
+ // value paired with the largest B at or before this quarter's G5.
1341
+ let g7Value;
1342
+ for (const { b, c } of lookupRows) {
1343
+ if (b <= serial) g7Value = c;
1344
+ }
1345
+ if (g7Value === undefined) {
1346
+ throw new Error(`VATQtr${q} G5 serial ${serial} is before every Vatinterface row`);
1347
+ }
1348
+ sheetXml = setCellCachedValue(sheetXml, "G7", g7Value);
1349
+
1350
+ // Roll the K2:K16 dropdown source list (cached formula values).
1351
+ const kValues = [];
1352
+ for (let k = 2; k <= 16; k++) {
1353
+ const cellRef = `K${k}`;
1354
+ const match = matchCell(sheetXml, cellRef);
1355
+ if (!match) throw new Error(`Cell ${cellRef} not found in ${sheetPath}`);
1356
+ const fMatch = match.fullMatch.match(/<f[^>]*>([\s\S]*?)<\/f>/);
1357
+ if (!fMatch) throw new Error(`Cell ${cellRef} in ${sheetPath} has no formula`);
1358
+ const formula = fMatch[1];
1359
+
1360
+ let value;
1361
+ const viRef = formula.match(/^Vatinterface!B(\d+)$/);
1362
+ const adminRef = formula.match(/^\[1\]Admin!\$B\$(\d+)$/);
1363
+ if (viRef) value = viValues[`B${viRef[1]}`];
1364
+ else if (adminRef) value = adminB[parseInt(adminRef[1], 10)];
1365
+ if (value === undefined) {
1366
+ throw new Error(`Cell ${cellRef} in ${sheetPath} has unresolvable formula ${formula}`);
1367
+ }
1368
+ sheetXml = setCellCachedValue(sheetXml, cellRef, value);
1369
+ kValues.push(value);
1370
+ }
1371
+
1372
+ if (!kValues.includes(serial)) {
1373
+ throw new Error(`VATQtr${q} default G5 serial ${serial} is not in the K2:K16 list [${kValues.join(", ")}]`);
1374
+ }
1375
+
1376
+ const origDate = zip.file(sheetPath).date;
1377
+ zip.file(sheetPath, sheetXml, { date: origDate });
1378
+ }
1379
+ }
1380
+
1381
+ // Force full recalculation on open so cached formula values (e.g. G2=B23) update
1382
+ const wbXml = await zip.file("xl/workbook.xml").async("string");
1383
+ const wbDate = zip.file("xl/workbook.xml").date;
1384
+ zip.file("xl/workbook.xml", withFullCalcOnLoad(wbXml), { date: wbDate });
1385
+
1386
+ stabilizeDirDates(zip);
1387
+ return zip.generateAsync({
1388
+ type: "uint8array",
1389
+ compression: "DEFLATE",
1390
+ compressionOptions: { level: 6 },
1391
+ });
1392
+ }
1393
+
1394
+ // ── Month tab renaming (Ltd Company all year-end months) ────────────────────
1395
+
1396
+ const MONTH_NAMES_SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1397
+
1398
+ export function getMonthTabSequence(yearEndMonth) {
1399
+ const tabs = [];
1400
+ for (let i = 0; i < 12; i++) {
1401
+ tabs.push(MONTH_NAMES_SHORT[(yearEndMonth + i) % 12]);
1402
+ }
1403
+ return tabs;
1404
+ }
1405
+
1406
+ export async function renameMonthTabs(xlsxBuffer, yearEndMonth) {
1407
+ const zip = await JSZip.loadAsync(xlsxBuffer);
1408
+ let wbXml = await zip.file("xl/workbook.xml").async("string");
1409
+
1410
+ const templateTabs = getMonthTabSequence(3);
1411
+ const targetTabs = getMonthTabSequence(yearEndMonth);
1412
+
1413
+ if (templateTabs.join(",") === targetTabs.join(",")) {
1414
+ return xlsxBuffer;
1415
+ }
1416
+
1417
+ const placeholders = templateTabs.map((_, i) => `__MONTH_${i}__`);
1418
+ for (let i = 0; i < 12; i++) {
1419
+ wbXml = wbXml.replace(new RegExp(`name="${templateTabs[i]}"`, "g"), `name="${placeholders[i]}"`);
1420
+ }
1421
+ for (let i = 0; i < 12; i++) {
1422
+ wbXml = wbXml.replace(new RegExp(placeholders[i], "g"), targetTabs[i]);
1423
+ }
1424
+
1425
+ const origDate = zip.file("xl/workbook.xml").date;
1426
+ zip.file("xl/workbook.xml", wbXml, { date: origDate });
1427
+
1428
+ stabilizeDirDates(zip);
1429
+ return zip.generateAsync({ type: "uint8array", compression: "DEFLATE", compressionOptions: { level: 6 } });
1430
+ }
1431
+
1432
+ // ── Payslips Admin month-sheet column (Ltd Company all year-end months) ─────
1433
+ //
1434
+ // Payslips Admin column A is headed "Month Sheet": for each day of the tax
1435
+ // calendar it names the month tab that day's payroll belongs on, and the
1436
+ // printed payslip joins through it -- H3 is LOOKUP(F4, Admin!D, Admin!A),
1437
+ // month number to tab name. The column builds the name from the calendar's
1438
+ // own 6 April anchor, so it names Apr, May, Jun ..., which is the tab order
1439
+ // only the March template ships. Rename the tabs for another year end and the
1440
+ // column still hands month 1 to "Apr", so the page reads whichever tab now
1441
+ // carries that name -- a different month of the year, printed under its own
1442
+ // period number, with nothing else on the sheet disagreeing.
1443
+ //
1444
+ // The tabs themselves are the frame everything else follows: each carries its
1445
+ // place in the package's own year in E, its block starts on the row that place
1446
+ // gives it, and the writers fill it by that place. So the name column is what
1447
+ // moves.
1448
+ export async function reorientPayslipsAdminMonthSheets(xlsxBuffer, yearEndMonth, adminSheetPath) {
1449
+ const templateTabs = getMonthTabSequence(3);
1450
+ const targetTabs = getMonthTabSequence(yearEndMonth);
1451
+
1452
+ if (templateTabs.join(",") === targetTabs.join(",")) {
1453
+ return xlsxBuffer;
1454
+ }
1455
+
1456
+ const zip = await JSZip.loadAsync(xlsxBuffer);
1457
+ let adminXml = await zip.file(adminSheetPath).async("string");
1458
+
1459
+ // The column's month name is the calendar anchor's month plus the payroll
1460
+ // month's distance from it, so the whole column moves by the distance from
1461
+ // the template's first tab to this package's.
1462
+ const monthShift = (yearEndMonth - 3 + 12) % 12;
1463
+ const monthSheetFormula = /TEXT\(DATE\(YEAR\(B\$2\),MONTH\(B\$2\)\+\(D(\d+)-1\),1\),"Mmm"\)/g;
1464
+ let formulasMoved = 0;
1465
+ adminXml = adminXml.replace(monthSheetFormula, (_, row) => {
1466
+ formulasMoved++;
1467
+ return `TEXT(DATE(YEAR(B$2),MONTH(B$2)+(D${row}-1)+${monthShift},1),"Mmm")`;
1468
+ });
1469
+ if (formulasMoved === 0) {
1470
+ throw new Error(`No Payslips Admin month-sheet formulas found in ${adminSheetPath}`);
1471
+ }
1472
+
1473
+ // The cached names each of those cells carries, so a package that is never
1474
+ // recalculated still joins to the right tab.
1475
+ for (let row = PAYSLIPS_ADMIN_FIRST_CALENDAR_ROW; row <= PAYSLIPS_ADMIN_CHAIN_LAST_ROW; row++) {
1476
+ const monthCell = matchCell(adminXml, `D${row}`);
1477
+ if (!monthCell) throw new Error(`Payslips Admin D${row} not found in ${adminSheetPath}`);
1478
+ const monthNumber = parseInt((monthCell.fullMatch.match(/<v>([^<]*)<\/v>/) || [])[1], 10);
1479
+ if (!(monthNumber >= 1 && monthNumber <= 12)) {
1480
+ throw new Error(`Payslips Admin D${row} holds ${monthNumber}, not a payroll month number`);
1481
+ }
1482
+ adminXml = setCellCachedValue(adminXml, `A${row}`, targetTabs[monthNumber - 1]);
1483
+ }
1484
+
1485
+ const origDate = zip.file(adminSheetPath).date;
1486
+ zip.file(adminSheetPath, adminXml, { date: origDate });
1487
+
1488
+ // The printed page keeps its own cached copy of the name the lookup returns,
1489
+ // and a package is read before it is ever recalculated. The sheet ships
1490
+ // asking for period 1, which both the weekly and the monthly lookup column
1491
+ // answer with the calendar's first row, so that row's new name is the answer
1492
+ // whichever frequency the page ships set to.
1493
+ const printSheetPath = (await buildSheetMap(zip)).get(PAYSLIP_PRINT_SHEET);
1494
+ if (!printSheetPath) throw new Error(`No ${PAYSLIP_PRINT_SHEET} sheet in the Payslips workbook`);
1495
+ let printXml = await zip.file(printSheetPath).async("string");
1496
+ const periodCell = matchCell(printXml, PAYSLIP_PRINT_CELLS.period);
1497
+ if (!periodCell) throw new Error(`Payslips ${PAYSLIP_PRINT_CELLS.period} not found in ${printSheetPath}`);
1498
+ const shippedPeriod = parseInt((periodCell.fullMatch.match(/<v>([^<]*)<\/v>/) || [])[1], 10);
1499
+ if (shippedPeriod !== 1) {
1500
+ throw new Error(`Payslips ${PAYSLIP_PRINT_CELLS.period} ships asking for period ${shippedPeriod}, not the calendar's first row`);
1501
+ }
1502
+ printXml = setCellCachedValue(printXml, PAYSLIP_PRINT_CELLS.tab, targetTabs[0]);
1503
+ zip.file(printSheetPath, printXml, { date: zip.file(printSheetPath).date });
1504
+
1505
+ stabilizeDirDates(zip);
1506
+ return zip.generateAsync({ type: "uint8array", compression: "DEFLATE", compressionOptions: { level: 6 } });
1507
+ }
1508
+
1509
+ // ── Payslips month-tab payroll periods (non-March year ends) ────────────────
1510
+ //
1511
+ // Every month tab opens its monthly payroll block with the days it covers: K
1512
+ // the first, M the last, and generateSpreadsheet dates both over the payroll
1513
+ // year's own twelve months. The March template's tabs run those same twelve
1514
+ // months, so on that one year end the block on the tab named May reads 1 to
1515
+ // 31 May and there is nothing to move.
1516
+ //
1517
+ // Rename the tabs for another year end and the two frames come apart. A June
1518
+ // year end names its second tab Aug and the block on it still reads 1 to
1519
+ // 31 May: the dates a customer sees are the payroll year's second month, under
1520
+ // the accounting period's second month's name. The tab name is the frame the
1521
+ // rest of the package follows, so it is the month the block covers.
1522
+ //
1523
+ // M is also where the writer puts the date the month's wages were paid, which
1524
+ // is why the block's period is what the printed payslip reads back as its
1525
+ // period end. K is written by nobody and is the tab's calendar on a blank
1526
+ // package and a populated one alike.
1527
+ export async function reorientPayslipsMonthTabPeriods(xlsxBuffer, yearEndDate, payrollYearStart) {
1528
+ const yearEndMonth = yearEndDate.getUTCMonth() + 1;
1529
+ const targetTabs = getMonthTabSequence(yearEndMonth);
1530
+
1531
+ if (getMonthTabSequence(3).join(",") === targetTabs.join(",")) {
1532
+ return xlsxBuffer;
1533
+ }
1534
+
1535
+ const zip = await JSZip.loadAsync(xlsxBuffer);
1536
+ const sheetMap = await buildSheetMap(zip);
1537
+
1538
+ // The period opens on the first day of the month after the year-end month,
1539
+ // twelve months back from the year end itself.
1540
+ const periodStartMonths = yearEndDate.getUTCFullYear() * 12 + yearEndDate.getUTCMonth() - 11;
1541
+ const periodStart = new Date(Date.UTC(Math.floor(periodStartMonths / 12), periodStartMonths % 12, 1));
1542
+
1543
+ for (let monthIndex = 0; monthIndex < 12; monthIndex++) {
1544
+ const tab = targetTabs[monthIndex];
1545
+ const sheetPath = sheetMap.get(tab);
1546
+ if (!sheetPath) throw new Error(`No ${tab} tab in the Payslips workbook`);
1547
+
1548
+ const { first, last } = payslipsMonthPeriod(periodStart, monthIndex, payrollYearStart);
1549
+ let sheetXml = await zip.file(sheetPath).async("string");
1550
+ sheetXml = setPayrollPeriodCell(sheetXml, tab, payslipsPeriodStartCell(monthIndex), first);
1551
+ sheetXml = setPayrollPeriodCell(sheetXml, tab, payslipsWagesPaidCell(monthIndex), last);
1552
+ zip.file(sheetPath, sheetXml, { date: zip.file(sheetPath).date });
1553
+ }
1554
+
1555
+ stabilizeDirDates(zip);
1556
+ return zip.generateAsync({ type: "uint8array", compression: "DEFLATE", compressionOptions: { level: 6 } });
1557
+ }
1558
+
1559
+ // ── Payslips PAYE remittance schedule (Ltd Company non-March year ends) ─────
1560
+ //
1561
+ // The Payment sheet is what the company pays HMRC each month. Rows 4 to 15 are
1562
+ // the twelve tax months: B the month end, C the day the payment is due on the
1563
+ // 19th after it, and D to H the figures from the payroll paid in that month.
1564
+ // B and C read the Admin calendar, which runs the tax year from 6 April, so
1565
+ // row 4 is April whatever the package's year end.
1566
+ //
1567
+ // The columns beside them name a month tab, and the rename pass moves every
1568
+ // tab name in the workbook by position. On a June year end it turned row 4's
1569
+ // Apr into Jul: the row headed 30 April went on to sum the tab holding July's
1570
+ // payroll. A PAYE month runs the 6th to the 5th and the schedule's dates are
1571
+ // right, so it is the totals that move back: each row takes the tab named for
1572
+ // the calendar month that tax month ends in, which is the tab the writers put
1573
+ // that month's payroll on.
1574
+ //
1575
+ // The row a tab's director figures sit on follows the weeks that tab's month
1576
+ // holds, so it moves when the tab does -- which is why this is generated per
1577
+ // year end rather than fixed in the template.
1578
+ // The columns each row reads its month tab through: row 1 aggregates for the
1579
+ // employees' figures, the director block's own rows for the statutory pay the
1580
+ // company recovers.
1581
+ const PAYMENT_ROW_ONE_COLUMNS = { D: ["T", "O"], E: ["N"], H: ["P"] };
1582
+ const PAYMENT_DIRECTOR_BLOCK_COLUMNS = { F: ["AD", "AE", "AF", "AG"], G: ["AE", "AF", "AG"] };
1583
+ // The director block opens twelve rows below the monthly payroll block, and
1584
+ // the NIC compensation the schedule reads sits two rows below that.
1585
+ const PAYMENT_DIRECTOR_ROW_OFFSET = 12;
1586
+ const PAYMENT_NIC_COMPENSATION_ROW_OFFSET = 2;
1587
+
1588
+ export async function realignPayslipsPaymentSchedule(xlsxBuffer, yearEndMonth, paymentSheetName = "Payment") {
1589
+ const templateTabs = getMonthTabSequence(3);
1590
+ const targetTabs = getMonthTabSequence(yearEndMonth);
1591
+
1592
+ if (templateTabs.join(",") === targetTabs.join(",")) {
1593
+ return xlsxBuffer;
1594
+ }
1595
+
1596
+ const zip = await JSZip.loadAsync(xlsxBuffer);
1597
+ const sheetMap = await buildSheetMap(zip);
1598
+ const paymentPath = sheetMap.get(paymentSheetName);
1599
+ if (!paymentPath) throw new Error(`No ${paymentSheetName} sheet in the Payslips workbook`);
1600
+ let paymentXml = await zip.file(paymentPath).async("string");
1601
+
1602
+ for (let taxMonth = 0; taxMonth < 12; taxMonth++) {
1603
+ const row = PAYE_SCHEDULE_FIRST_ROW + taxMonth;
1604
+ // The tab the rename pass left this row reading, and the one the tax
1605
+ // month's own calendar month names.
1606
+ const readTab = targetTabs[taxMonth];
1607
+ const paidTab = templateTabs[taxMonth];
1608
+ const readBlockRow = payslipsDirectorBlockRow(taxMonth);
1609
+ const paidBlockRow = payslipsDirectorBlockRow(targetTabs.indexOf(paidTab));
1610
+
1611
+ for (const [column, sources] of Object.entries(PAYMENT_ROW_ONE_COLUMNS)) {
1612
+ paymentXml = repointPaymentCell(
1613
+ paymentXml,
1614
+ `${column}${row}`,
1615
+ sources.map((source) => `${readTab}!${source}1`).join("+"),
1616
+ sources.map((source) => `${paidTab}!${source}1`).join("+"),
1617
+ );
1618
+ }
1619
+ for (const [column, sources] of Object.entries(PAYMENT_DIRECTOR_BLOCK_COLUMNS)) {
1620
+ const offset = column === "G" ? PAYMENT_NIC_COMPENSATION_ROW_OFFSET : 0;
1621
+ paymentXml = repointPaymentCell(
1622
+ paymentXml,
1623
+ `${column}${row}`,
1624
+ sources.map((source) => `${readTab}!${source}${readBlockRow + offset}`).join("+"),
1625
+ sources.map((source) => `${paidTab}!${source}${paidBlockRow + offset}`).join("+"),
1626
+ );
1627
+ }
1628
+ }
1629
+
1630
+ zip.file(paymentPath, paymentXml, { date: zip.file(paymentPath).date });
1631
+ stabilizeDirDates(zip);
1632
+ return zip.generateAsync({ type: "uint8array", compression: "DEFLATE", compressionOptions: { level: 6 } });
1633
+ }
1634
+
1635
+ // The row a month tab's director block opens on, by the tab's place in the
1636
+ // package's own year -- the same weeks-per-month rule the monthly payroll
1637
+ // block follows.
1638
+ const payslipsDirectorBlockRow = (monthIndex) => 8 + 10 * PAYROLL_WEEKS_PER_MONTH[monthIndex] + PAYMENT_DIRECTOR_ROW_OFFSET;
1639
+
1640
+ // One schedule cell repointed from the tab the rename left it on to the tab
1641
+ // whose payroll the tax month covers. The cell has to be holding the formula
1642
+ // the template ships, addressed to the tab the rename produced: anything else
1643
+ // is a template change to see rather than a formula to overwrite. The cached
1644
+ // value is left where it is -- both tabs are empty on a blank package, and a
1645
+ // populated one is recalculated.
1646
+ function repointPaymentCell(paymentXml, cellRef, expected, replacement) {
1647
+ const cell = matchCell(paymentXml, cellRef);
1648
+ if (!cell) throw new Error(`Payslips Payment ${cellRef} not found`);
1649
+ const formula = (cell.fullMatch.match(/<f[^>]*>([^<]*)<\/f>/) || [])[1];
1650
+ if (formula !== expected) {
1651
+ throw new Error(`Payslips Payment ${cellRef} reads ${formula ?? "no formula"}, not ${expected}`);
1652
+ }
1653
+ const value = (cell.fullMatch.match(/<v>([^<]*)<\/v>/) || [])[1];
1654
+ if (value === undefined) throw new Error(`Payslips Payment ${cellRef} has no cached value`);
1655
+ return setCellFormula(paymentXml, cellRef, replacement, value);
1656
+ }
1657
+
1658
+ // One end of a month tab's payroll period. The cell has to be holding either
1659
+ // the Admin calendar read the template ships or the day an earlier pass wrote
1660
+ // over it: a block that has moved row, or a template that has stopped dating
1661
+ // the period here, is a change to see rather than a cell to overwrite.
1662
+ function setPayrollPeriodCell(sheetXml, tab, cellRef, day) {
1663
+ const cell = matchCell(sheetXml, cellRef);
1664
+ if (!cell) throw new Error(`Payslips ${tab} ${cellRef} not found`);
1665
+ const formula = (cell.fullMatch.match(/<f[^>]*>([^<]*)<\/f>/) || [])[1];
1666
+ if (!/^(Admin!\$?B\$?\d+|DATE\(\d+,\d+,\d+\))$/.test(formula || "")) {
1667
+ throw new Error(`Payslips ${tab} ${cellRef} reads ${formula ?? "no formula"}, neither the Admin calendar nor a date`);
1668
+ }
1669
+ return setCellFormula(sheetXml, cellRef, excelDateFormula(day), toExcelSerial(day));
1670
+ }
1671
+
1672
+ const excelDateFormula = (day) => `DATE(${day.getUTCFullYear()},${day.getUTCMonth() + 1},${day.getUTCDate()})`;
1673
+
1674
+ // ── Payslips month boundaries ───────────────────────────────────────────────
1675
+ //
1676
+ // The template reaches every month boundary in the workbook by counting a
1677
+ // fixed number of days down the Admin calendar: the days a tab's monthly
1678
+ // payroll block covers, the end of the calendar month a tax month runs to, and
1679
+ // the 19th of the month after that the payment falls due on. No single count
1680
+ // is right for both a leap payroll year and a common one. The month ends land
1681
+ // a day early on everything after a leap February -- the block on Mar opened
1682
+ // on 29 February and closed on the 30th -- and the last two due dates land on
1683
+ // the 20th in a year without one. Every package ships one of the two wrong, so
1684
+ // all of them are written as the dates they are.
1685
+
1686
+ const PAYSLIPS_PAYMENT_SHEET = "Payment";
1687
+
1688
+ // Each tab's monthly payroll block, over the payroll year's own twelve months.
1689
+ // A tab renamed for another year end moves its block on to the accounting
1690
+ // period's months afterwards.
1691
+ async function datePayslipsMonthTabPeriods(zip, sheetPaths, payrollYearOpens) {
1692
+ const tabs = [...sheetPaths.keys()].filter((name) => MONTH_NAMES_SHORT.includes(name));
1693
+ if (tabs.length !== 12) throw new Error(`The Payslips workbook has ${tabs.length} month tabs, not 12`);
1694
+ const periodStart = utcDate(payrollYearOpens.getUTCFullYear(), 4, 1);
1695
+
1696
+ for (let monthIndex = 0; monthIndex < 12; monthIndex++) {
1697
+ const tab = tabs[monthIndex];
1698
+ const path = sheetPaths.get(tab);
1699
+ const { first, last } = payslipsMonthPeriod(periodStart, monthIndex, payrollYearOpens);
1700
+ let sheetXml = await zip.file(path).async("string");
1701
+ sheetXml = setPayrollPeriodCell(sheetXml, tab, payslipsPeriodStartCell(monthIndex), first);
1702
+ sheetXml = setPayrollPeriodCell(sheetXml, tab, payslipsWagesPaidCell(monthIndex), last);
1703
+ zip.file(path, sheetXml, { date: zip.file(path).date });
1704
+ }
1705
+ }
1706
+
1707
+ // The PAYE schedule's own two dates a row.
1708
+ async function datePayslipsPaymentSchedule(zip, sheetPaths, payrollYearOpens) {
1709
+ const paymentPath = sheetPaths.get(PAYSLIPS_PAYMENT_SHEET);
1710
+ if (!paymentPath) throw new Error(`No ${PAYSLIPS_PAYMENT_SHEET} sheet in the Payslips workbook`);
1711
+ let paymentXml = await zip.file(paymentPath).async("string");
1712
+
1713
+ for (let taxMonth = 0; taxMonth < PAYE_MONTH_END_ROWS.length; taxMonth++) {
1714
+ const row = PAYE_SCHEDULE_FIRST_ROW + taxMonth;
1715
+ const { ends, due } = payeTaxMonthDates(payrollYearOpens, taxMonth);
1716
+ paymentXml = setPaymentScheduleDate(paymentXml, `B${row}`, PAYE_MONTH_END_ROWS[taxMonth], ends);
1717
+ paymentXml = setPaymentScheduleDate(paymentXml, `C${row}`, PAYE_DUE_DATE_ROWS[taxMonth], due);
1718
+ }
1719
+
1720
+ zip.file(paymentPath, paymentXml, { date: zip.file(paymentPath).date });
1721
+ }
1722
+
1723
+ // One schedule date. The cell has to be reading the Admin calendar row the
1724
+ // template ships for it: a schedule that has moved row is a change to see
1725
+ // rather than a cell to overwrite.
1726
+ function setPaymentScheduleDate(paymentXml, cellRef, adminRow, day) {
1727
+ const cell = matchCell(paymentXml, cellRef);
1728
+ if (!cell) throw new Error(`Payslips Payment ${cellRef} not found`);
1729
+ const formula = (cell.fullMatch.match(/<f[^>]*>([^<]*)<\/f>/) || [])[1];
1730
+ if (formula !== `Admin!$B$${adminRow}`) {
1731
+ throw new Error(`Payslips Payment ${cellRef} reads ${formula ?? "no formula"}, not Admin!$B$${adminRow}`);
1732
+ }
1733
+ return setCellFormula(paymentXml, cellRef, excelDateFormula(day), toExcelSerial(day));
1734
+ }
1735
+
1736
+ // ── Vatinterface formula rewriting (Ltd Company all year-end months) ────────
1737
+
1738
+ // Renames the [2]Purchases/[3]Sales month-tab references in the Vatinterface
1739
+ // D and M column formulas for non-March year-ends. The [1]Admin!$B$ references
1740
+ // are left at the template rows: the generated Financialaccounts Admin keeps
1741
+ // the template's year-end-relative B-column (anchored at B32 = F21), so the
1742
+ // template rows are correct for every year-end.
1743
+ export async function rewriteVatinterfaceFormulas(xlsxBuffer, yearEndMonth, vatinterfacePath) {
1744
+ const templateTabs = getMonthTabSequence(3);
1745
+ const targetTabs = getMonthTabSequence(yearEndMonth);
1746
+
1747
+ if (templateTabs.join(",") === targetTabs.join(",")) {
1748
+ return xlsxBuffer;
1749
+ }
1750
+
1751
+ const zip = await JSZip.loadAsync(xlsxBuffer);
1752
+ let viXml = await zip.file(vatinterfacePath).async("string");
1753
+
1754
+ // Two passes via placeholders: a direct in-place rename cascades (Apr→May,
1755
+ // then May→Jun re-hits the cells just renamed, collapsing every month onto
1756
+ // the final target).
1757
+ const placeholders = templateTabs.map((_, i) => `__VI_MONTH_${i}__`);
1758
+ for (let i = 0; i < 12; i++) {
1759
+ viXml = viXml.replace(new RegExp(`\\[2\\]${templateTabs[i]}!`, "g"), `[2]${placeholders[i]}!`);
1760
+ viXml = viXml.replace(new RegExp(`\\[3\\]${templateTabs[i]}!`, "g"), `[3]${placeholders[i]}!`);
1761
+ }
1762
+ for (let i = 0; i < 12; i++) {
1763
+ viXml = viXml.replace(new RegExp(placeholders[i], "g"), targetTabs[i]);
1764
+ }
1765
+
1766
+ const origDate = zip.file(vatinterfacePath).date;
1767
+ zip.file(vatinterfacePath, viXml, { date: origDate });
1768
+
1769
+ stabilizeDirDates(zip);
1770
+ return zip.generateAsync({ type: "uint8array", compression: "DEFLATE", compressionOptions: { level: 6 } });
1771
+ }
1772
+
1773
+ // ── External link sheet name renaming (Ltd Company) ─────────────────────────
1774
+
1775
+ export async function renameExternalLinkSheetNames(xlsxBuffer, yearEndMonth) {
1776
+ const zip = await JSZip.loadAsync(xlsxBuffer);
1777
+ const templateTabs = getMonthTabSequence(3);
1778
+ const targetTabs = getMonthTabSequence(yearEndMonth);
1779
+
1780
+ if (templateTabs.join(",") === targetTabs.join(",")) return xlsxBuffer;
1781
+
1782
+ const placeholders = templateTabs.map((_, i) => `__EL_${i}__`);
1783
+
1784
+ function renameTabs(xml) {
1785
+ for (let i = 0; i < 12; i++) {
1786
+ xml = xml.replace(new RegExp(`${templateTabs[i]}!`, "g"), `${placeholders[i]}!`);
1787
+ xml = xml.replace(new RegExp(`sheetName val="${templateTabs[i]}"`, "g"), `sheetName val="${placeholders[i]}"`);
1788
+ }
1789
+ for (let i = 0; i < 12; i++) {
1790
+ xml = xml.replace(new RegExp(`${placeholders[i]}!`, "g"), `${targetTabs[i]}!`);
1791
+ xml = xml.replace(new RegExp(`sheetName val="${placeholders[i]}"`, "g"), `sheetName val="${targetTabs[i]}"`);
1792
+ }
1793
+ return xml;
1794
+ }
1795
+
1796
+ // Rename in external link XML files (cached sheet names)
1797
+ const linkFiles = Object.keys(zip.files).filter((f) => /xl\/externalLinks\/externalLink\d+\.xml$/.test(f));
1798
+ for (const path of linkFiles) {
1799
+ let xml = await zip.file(path).async("string");
1800
+ xml = renameTabs(xml);
1801
+ zip.file(path, xml, { date: zip.file(path).date });
1802
+ }
1803
+
1804
+ // Rename in ALL worksheet XMLs (TrialBalance, MnthP&L, etc. reference [2]Apr! [3]Apr!)
1805
+ const sheetFiles = Object.keys(zip.files).filter((f) => /xl\/worksheets\/sheet\d+\.xml$/.test(f));
1806
+ for (const path of sheetFiles) {
1807
+ let xml = await zip.file(path).async("string");
1808
+ const orig = xml;
1809
+ xml = renameTabs(xml);
1810
+ if (xml !== orig) {
1811
+ zip.file(path, xml, { date: zip.file(path).date });
1812
+ }
1813
+ }
1814
+
1815
+ stabilizeDirDates(zip);
1816
+ return zip.generateAsync({ type: "uint8array", compression: "DEFLATE", compressionOptions: { level: 6 } });
1817
+ }
1818
+
1819
+ // ── Output naming ───────────────────────────────────────────────────────────
1820
+
1821
+ // The ledger workbooks whose month tabs are named for the accounting months
1822
+ // they hold, so a year end other than March renames them.
1823
+ const TAB_RENAME_FILES = new Set([
1824
+ "Sales.xlsx",
1825
+ "Purchases.xlsx",
1826
+ "Currentaccount.xlsx",
1827
+ "Savingaccount.xlsx",
1828
+ "Cashaccount.xlsx",
1829
+ "Creditcardaccount.xlsx",
1830
+ "Payslips.xlsx",
1831
+ ]);
1832
+
1833
+ // Workbooks with no month tabs of their own that still address the
1834
+ // ledgers' month tabs by name across a link: the hub reads every month's
1835
+ // totals, and the asset workbook's reconciliation reads the two ledgers'
1836
+ // annual fixed asset rows off their final month tab.
1837
+ const LINK_RENAME_FILES = new Set(["Financialaccounts.xlsx", "Fixedassets.xlsx"]);
1838
+
1839
+ // Everything a year end other than the template's own March asks of one file
1840
+ // of a package: the month tabs renamed, the links that address them by name
1841
+ // followed, the payroll calendar reoriented and the VAT interface's formulas
1842
+ // rewritten. A March year end leaves every file as it is. The CLI and the
1843
+ // book writer both compose a package through this, so there is one sequence.
1844
+ export async function applyYearEndSequence(xlsxBuffer, templateFile, sheetsConfig, yearEndMonth, endDate, yearInfo) {
1845
+ if (!yearEndMonth) return xlsxBuffer;
1846
+ let buffer = xlsxBuffer;
1847
+
1848
+ if (templateFile.endsWith(".xlsx") && TAB_RENAME_FILES.has(templateFile)) {
1849
+ buffer = await renameMonthTabs(buffer, yearEndMonth);
1850
+ buffer = await renameExternalLinkSheetNames(buffer, yearEndMonth);
1851
+ }
1852
+
1853
+ // The Payslips Admin sheet names the month tab each payroll month belongs
1854
+ // on, which the printed payslip joins through, so it moves with the tabs.
1855
+ if (sheetsConfig?.payslipsAdmin) {
1856
+ buffer = await reorientPayslipsAdminMonthSheets(buffer, yearEndMonth, sheetsConfig.payslipsAdmin);
1857
+ // Each month tab's monthly payroll block already covers a month of the
1858
+ // payroll year. The tab's name is the accounting period's month, so on
1859
+ // another year end that is the month the block moves to.
1860
+ buffer = await reorientPayslipsMonthTabPeriods(buffer, endDate, payrollYearStart(new Date(yearInfo.start).getUTCFullYear()));
1861
+ // Each PAYE schedule row then takes the tab holding the payroll paid
1862
+ // in its tax month rather than the tab the rename left it pointing at.
1863
+ buffer = await realignPayslipsPaymentSchedule(buffer, yearEndMonth);
1864
+ }
1865
+
1866
+ if (templateFile === "Vatreturns.xlsx" && sheetsConfig) {
1867
+ buffer = await rewriteVatinterfaceFormulas(buffer, yearEndMonth, "xl/worksheets/sheet6.xml");
1868
+ }
1869
+
1870
+ if (LINK_RENAME_FILES.has(templateFile)) {
1871
+ buffer = await renameExternalLinkSheetNames(buffer, yearEndMonth);
1872
+ }
1873
+
1874
+ return buffer;
1875
+ }
1876
+
1877
+ export function formatDateDDMMYY(date) {
1878
+ const d = date.getUTCDate().toString().padStart(2, "0");
1879
+ const m = (date.getUTCMonth() + 1).toString().padStart(2, "0");
1880
+ const y = (date.getUTCFullYear() % 100).toString().padStart(2, "0");
1881
+ return `${d}${m}${y}`;
1882
+ }
1883
+
1884
+ export function formatDateYYYYMMDD(date) {
1885
+ const y = date.getUTCFullYear();
1886
+ const m = (date.getUTCMonth() + 1).toString().padStart(2, "0");
1887
+ const d = date.getUTCDate().toString().padStart(2, "0");
1888
+ return `${y}-${m}-${d}`;
1889
+ }
1890
+
1891
+ export function shortLabel(date) {
1892
+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1893
+ return `${months[date.getUTCMonth()]}${(date.getUTCFullYear() % 100).toString().padStart(2, "0")}`;
1894
+ }
1895
+
1896
+ // The package directory and spreadsheet names a product's meta.toml patterns
1897
+ // produce for one year end. A multi-file product ships its workbooks under
1898
+ // their template names and declares no spreadsheet pattern, so it gets a
1899
+ // directory name and nothing else.
1900
+ export function packageNaming(productMeta, sharedMeta, endDate) {
1901
+ const dirName = productMeta.output.dir_pattern
1902
+ .replace("{prefix}", sharedMeta.package.prefix)
1903
+ .replace("{name}", productMeta.product.name)
1904
+ .replace("{year_end_date}", formatDateYYYYMMDD(endDate))
1905
+ .replace("{short_label}", shortLabel(endDate))
1906
+ .replace("{format}", sharedMeta.package.format);
1907
+
1908
+ const pattern = productMeta.output.spreadsheet_pattern;
1909
+ const xlsxFilename = pattern ? pattern.replace("{year_end_ddmmyy}", formatDateDDMMYY(endDate)) : null;
1910
+
1911
+ return { dirName, xlsxFilename };
1912
+ }