@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,27 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // products.js — the four product modules diya-gl carries, addressed by
5
+ // their short id. Browser-safe: nothing here touches fs or any Node
6
+ // builtin, so this loads in the books bundle exactly as it does under Node.
7
+
8
+ import * as bst from "../products/bst.js";
9
+ import * as taxi from "../products/taxi.js";
10
+ import * as se from "../products/se.js";
11
+ import * as ltd from "../products/ltd.js";
12
+
13
+ export const PRODUCTS = { bst, taxi, se, ltd };
14
+
15
+ /**
16
+ * The product module for a short id.
17
+ *
18
+ * @param {string} id
19
+ * @returns {Object} the product module (CELL_MAP, PRODUCT, cellWrites, ...)
20
+ */
21
+ export function productModule(id) {
22
+ const productMod = PRODUCTS[id];
23
+ if (!productMod) {
24
+ throw new Error(`Unknown product "${id}"; the products diya-gl carries are ${Object.keys(PRODUCTS).join(", ")}`);
25
+ }
26
+ return productMod;
27
+ }
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // provenance-data.js — generated by scripts/build-provenance-data.mjs.
5
+ // Regenerate with that script; do not hand-edit the values below.
6
+ //
7
+ // The five provenance stamps' current values: the engine's own npm version
8
+ // and commit, a hash over every tax-year data file, and each product's own
9
+ // template hash and reconciliation scorecard. Node (the CLI, the MCP
10
+ // server) and the browser bundle both import this file directly, so a book
11
+ // stamped by any of the three surfaces carries the same values.
12
+
13
+ export const PROVENANCE_DATA = {
14
+ "formatVersion": "diya-gl-books/1",
15
+ "engineVersion": "1.0.0+5b29e39cdf35",
16
+ "taxDataHash": "942a6388a226",
17
+ "reconciledCommit": "",
18
+ "templates": {
19
+ "bst": {
20
+ "hash": "06fdcd072930",
21
+ "scorecard": "810 passed, 0 warnings, 0 failed"
22
+ },
23
+ "taxi": {
24
+ "hash": "6c36b3785a83",
25
+ "scorecard": "686 passed, 0 warnings, 0 failed"
26
+ },
27
+ "se": {
28
+ "hash": "aaf63ff852c5",
29
+ "scorecard": "7679 passed, 0 warnings, 0 failed"
30
+ },
31
+ "ltd": {
32
+ "hash": "c3da60838497",
33
+ "scorecard": "101279 passed, 0 warnings, 0 failed"
34
+ }
35
+ }
36
+ };
@@ -0,0 +1,92 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // provenance.js — the five provenance stamps every diya-gl book and report
5
+ // carries: which format version it is written as, which engine build wrote
6
+ // it, which tax data it was calculated from, which template it reproduces
7
+ // (with that template's published reconciliation scorecard), and the commit
8
+ // whose CI reconciliation last passed for it.
9
+ //
10
+ // The values themselves live in provenance-data.js, generated once by
11
+ // scripts/build-provenance-data.mjs and committed. This module only shapes
12
+ // them for a book's documentInfo or a report's header, so it carries no fs,
13
+ // git or hashing of its own -- nothing here needs a Node-only stub in the
14
+ // browser bundle, and every surface (the CLI, the MCP server, the page)
15
+ // reads the exact same generated values.
16
+
17
+ import { PROVENANCE_DATA } from "./provenance-data.js";
18
+
19
+ // The same schema-name-to-product-id mapping xlsx-exporter.js's
20
+ // productIdOf() carries, kept as a small map of its own rather than an
21
+ // import: report-serializer.js and books-interchange.js both reach this
22
+ // module from one side of a cycle through xlsx-exporter.js (which itself
23
+ // imports scenario-extractor.js), and a static import back into
24
+ // xlsx-exporter.js from here closes that cycle -- a genuine circular ESM
25
+ // import that throws "Cannot access ... before initialization" at load
26
+ // time, not merely a lint concern.
27
+ const PRODUCT_ID_BY_SCHEMA_NAME = { BasicSoleTrader: "bst", TaxiDriver: "taxi", SelfEmployed: "se", Company: "ltd" };
28
+
29
+ function productOf(book) {
30
+ const schemaName = book?.entityInformation?.["diya-gl:product"];
31
+ return schemaName === undefined ? undefined : PRODUCT_ID_BY_SCHEMA_NAME[schemaName];
32
+ }
33
+
34
+ /**
35
+ * The five stamps for one product's book, as book.toml's documentInfo
36
+ * extension keys.
37
+ * @param {string} product - bst, taxi, se or ltd
38
+ * @returns {Object}
39
+ */
40
+ export function provenanceStamps(product) {
41
+ const template = PROVENANCE_DATA.templates[product];
42
+ if (!template) {
43
+ throw new Error(`provenanceStamps(): "${product}" is not one of ${Object.keys(PROVENANCE_DATA.templates).join(", ")}`);
44
+ }
45
+ const stamps = {
46
+ "diya-gl:formatVersion": PROVENANCE_DATA.formatVersion,
47
+ "diya-gl:engineVersion": PROVENANCE_DATA.engineVersion,
48
+ "diya-gl:taxDataHash": PROVENANCE_DATA.taxDataHash,
49
+ "diya-gl:templateHash": template.hash,
50
+ "diya-gl:templateScorecard": template.scorecard,
51
+ };
52
+ if (PROVENANCE_DATA.reconciledCommit) stamps["diya-gl:reconciledCommit"] = PROVENANCE_DATA.reconciledCommit;
53
+ return stamps;
54
+ }
55
+
56
+ /**
57
+ * A copy of book whose documentInfo carries this build's provenance
58
+ * stamps, keyed to the book's own declared product. Every writer that
59
+ * turns a book into book.toml, the JSON envelope or a diya-gl zip calls
60
+ * this first -- CLI, MCP and browser all reach the same values from the
61
+ * same generated data, so the stamps hold byte-identical across all three.
62
+ * A book with no declared product is returned unchanged: the existing
63
+ * "declares no product" refusals downstream still name that, rather than
64
+ * this module guessing which template's stamps would apply.
65
+ * @param {Object} book
66
+ * @returns {Object}
67
+ */
68
+ export function stampBook(book) {
69
+ const product = productOf(book);
70
+ if (!product) return book;
71
+ return { ...book, documentInfo: { ...book.documentInfo, ...provenanceStamps(product) } };
72
+ }
73
+
74
+ /**
75
+ * The same five stamps, shaped for report.json's header rather than
76
+ * book.toml's documentInfo -- a plain object, not TOML's quoted
77
+ * "diya-gl:"-prefixed keys.
78
+ * @param {string} product - bst, taxi, se or ltd
79
+ * @returns {Object}
80
+ */
81
+ export function provenanceHeader(product) {
82
+ const stamps = provenanceStamps(product);
83
+ const header = {
84
+ formatVersion: stamps["diya-gl:formatVersion"],
85
+ engineVersion: stamps["diya-gl:engineVersion"],
86
+ taxDataHash: stamps["diya-gl:taxDataHash"],
87
+ templateHash: stamps["diya-gl:templateHash"],
88
+ templateScorecard: stamps["diya-gl:templateScorecard"],
89
+ };
90
+ if (stamps["diya-gl:reconciledCommit"]) header.reconciledCommit = stamps["diya-gl:reconciledCommit"];
91
+ return header;
92
+ }
@@ -0,0 +1,374 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // report-generator.js — Shared report formatting for reconciliation and standalone report commands.
5
+ // Extracted from app/bin/reconcile.js.
6
+
7
+ import { canonicalForUnit, roundHalfUp, MONEY_DECIMALS } from "./canonical-report-value.js";
8
+
9
+ // The bridge walks the accounting profit to the profit the tax computation
10
+ // charges, one named adjustment at a time, and states what is left over. A
11
+ // product supplies the rows through profitBridge(results); the title, the
12
+ // check name and the table shape are the same for all four so a reader who
13
+ // has seen one has seen them all.
14
+ export const PROFIT_BRIDGE_TITLE = "Accounting profit to tax profit bridge";
15
+ export const PROFIT_BRIDGE_CHECK = "Accounting profit to tax profit bridge closes to zero";
16
+
17
+ // A number written out in decimal digits, whatever its magnitude. String()
18
+ // gives exponent form below 1e-6, which carries no decimal point for
19
+ // roundHalfUp to round on, so float noise would print with its sign still on
20
+ // it. Twenty places is far finer than any place a report prints to, so the
21
+ // rounding that follows is the only one that moves a printed digit.
22
+ function plainDecimal(value) {
23
+ return Number.isFinite(value) && Math.abs(value) < 1e21 ? value.toFixed(20) : String(value);
24
+ }
25
+
26
+ // Lines print to the penny. The residue asks for more places than that, so a
27
+ // difference under a penny is shown rather than rounded into a nil.
28
+ //
29
+ // One rounding, half away from zero, on the decimal digits themselves: a
30
+ // money line through canonicalForUnit, so a figure prints as the same value
31
+ // verify-roundtrip compares it as. toFixed rounds a binary float, which sends
32
+ // a half penny the wrong way (1.005 to 1.00), and toLocaleString would then
33
+ // round the result a second time. roundHalfUp gives a nil no sign, so a
34
+ // negated nil line and a residue that is float noise print as "0" rather than
35
+ // the "-0" that reads as a defect.
36
+ export function reportAmount(value, fractionDigits = MONEY_DECIMALS) {
37
+ if (typeof value !== "number") return "—";
38
+ const text = plainDecimal(value);
39
+ const rounded = fractionDigits === MONEY_DECIMALS ? canonicalForUnit(text, "money") : roundHalfUp(text, fractionDigits);
40
+ return Number(rounded).toLocaleString("en-GB", { minimumFractionDigits: 0, maximumFractionDigits: fractionDigits });
41
+ }
42
+
43
+ export function profitBridgeLines(bridge) {
44
+ if (!bridge) return [];
45
+ const lines = ["", `## ${PROFIT_BRIDGE_TITLE}`, "", "| Line | Cell | Amount |", "|------|------|-------:|"];
46
+ for (const row of bridge.rows) {
47
+ lines.push(`| ${row.label} | ${row.cell} | ${reportAmount(row.value)} |`);
48
+ }
49
+ lines.push(`| **Tax profit the bridge computes** | | **${reportAmount(bridge.computed)}** |`);
50
+ lines.push(`| Tax profit the sheet carries | ${bridge.sheetCell} | ${reportAmount(bridge.sheetProfit)} |`);
51
+ lines.push(`| **Residue** | | **${reportAmount(bridge.residue, 4)}** |`);
52
+ return lines;
53
+ }
54
+
55
+ // Sums a bridge's rows and states the residue against the sheet's own tax
56
+ // profit. Products build the rows; the arithmetic lives here so all four
57
+ // close the same way.
58
+ export function buildProfitBridge(rows, sheetCell, sheetProfit) {
59
+ const computed = rows.reduce((total, row) => total + row.value, 0);
60
+ return { rows, computed, sheetCell, sheetProfit, residue: computed - sheetProfit };
61
+ }
62
+
63
+ // ── Journal category netting ───────────────────────────────────────────────
64
+
65
+ // A journal amount is entered including VAT; the statement it feeds carries
66
+ // it net. Stating that only in total leaves each category's own netting to
67
+ // inference, so a reader cannot tell a correctly netted figure from one
68
+ // copied off a scenario that never had VAT in it. This table does it one
69
+ // category at a time: what the journal holds, what comes off, what is left,
70
+ // where that lands, and what the two differ by.
71
+ export const CATEGORY_NETTING_TITLE = "Journal category VAT netting";
72
+
73
+ export function categoryNettingCheckName(row) {
74
+ return `Category netting: ${row.label} (${row.code}) net reaches ${row.cell} with no residue`;
75
+ }
76
+
77
+ // Products supply { code, label, gross, net, cell, downstream } per category.
78
+ // The VAT stripped and the residue are derived here so every product states
79
+ // them the same way, and a category the scenario never used is dropped rather
80
+ // than printed as a row of zeros.
81
+ export function buildCategoryNetting(rate, rows) {
82
+ return {
83
+ rate,
84
+ rows: rows
85
+ .filter((row) => row.gross !== 0 || row.downstream !== 0)
86
+ .map((row) => ({ ...row, vat: row.gross - row.net, residue: row.net - row.downstream })),
87
+ };
88
+ }
89
+
90
+ export function categoryNettingLines(netting) {
91
+ if (!netting || netting.rows.length === 0) return [];
92
+ const lines = ["", `## ${CATEGORY_NETTING_TITLE}`, ""];
93
+ if (netting.rate === 0) {
94
+ lines.push(
95
+ `The books charge VAT at 0%. Gross equals net for all ${netting.rows.length} journal categories that cross into another statement, and each reaches it at the figure the journal holds.`,
96
+ );
97
+ return lines;
98
+ }
99
+ lines.push(`Journal amounts include VAT at ${(netting.rate * 100).toLocaleString("en-GB")}%.`);
100
+ lines.push("");
101
+ lines.push("| Journal category | Gross per the journal | VAT stripped | Net | Where the net lands | Figure there | Residue |");
102
+ lines.push("|------------------|----------------------:|-------------:|----:|---------------------|-------------:|--------:|");
103
+ for (const row of netting.rows) {
104
+ lines.push(
105
+ `| ${row.label} (${row.code}) | ${reportAmount(row.gross)} | ${reportAmount(row.vat)} | ${reportAmount(row.net)} | ${row.cell} | ${reportAmount(row.downstream)} | ${reportAmount(row.residue, 4)} |`,
106
+ );
107
+ }
108
+ return lines;
109
+ }
110
+
111
+ // ── VAT return cycle ───────────────────────────────────────────────────────
112
+
113
+ // A VAT quarter stagger follows the date the business registered, not its
114
+ // accounting year, so the shown returns and the year's own VAT lines cover
115
+ // different months and cannot be expected to agree. Left unstated that reads
116
+ // as a broken total. This works it out from the sheets' own dates: which
117
+ // periods each shown return covers, which months of the accounting year no
118
+ // shown return reaches and what VAT is on them, which covered periods fall
119
+ // outside the year, and where two shown returns cover the same period twice.
120
+ //
121
+ // periods: [{ row, endLabel, outputVat, inputVat, inAccountingYear }] in row
122
+ // order, one per VAT period the interface carries.
123
+ // forms: [{ name, end }] where end is the row the form's own period end
124
+ // date matches, or null when it matches none.
125
+ export function vatCycleRows(periods, forms) {
126
+ const { byRow, coverage, placed, missed, outside, shared } = vatReturnCoverage(periods, forms);
127
+ const rows = placed.map((form) => ({
128
+ label: `${form.name} covers the periods ending`,
129
+ value: form.covers.map((row) => byRow.get(row).endLabel).join(", "),
130
+ indent: 1,
131
+ }));
132
+ if (rows.length === 0) return [];
133
+
134
+ if (missed.length > 0) {
135
+ const named = missed.map((period) => period.endLabel).join(", ");
136
+ rows.push({
137
+ label: `No return above covers the accounting year's ${missed.length === 1 ? "month" : "months"} ending ${named}. That month sat on the previous return of the same cycle, which is why the quarters below fall short of the year's own VAT lines.`,
138
+ value: "",
139
+ });
140
+ rows.push({ label: "Output VAT on it", value: reportAmount(missed.reduce((total, p) => total + p.outputVat, 0)), indent: 1 });
141
+ rows.push({ label: "Input VAT on it", value: reportAmount(missed.reduce((total, p) => total + p.inputVat, 0)), indent: 1 });
142
+ }
143
+
144
+ if (outside.length > 0) {
145
+ rows.push({
146
+ label: `The returns above also cover the ${outside.length === 1 ? "period" : "periods"} ending ${outside.map((period) => period.endLabel).join(", ")}, ${outside.length === 1 ? "which falls" : "which fall"} outside the accounting year.`,
147
+ value: "",
148
+ });
149
+ rows.push({ label: "Output VAT on those", value: reportAmount(outside.reduce((total, p) => total + p.outputVat, 0)), indent: 1 });
150
+ rows.push({ label: "Input VAT on those", value: reportAmount(outside.reduce((total, p) => total + p.inputVat, 0)), indent: 1 });
151
+ }
152
+
153
+ if (shared.length > 0) {
154
+ const names = [...new Set(shared.flatMap((period) => coverage.get(period.row)))].join(" and ");
155
+ const months = shared.length === 1 ? "period" : "periods";
156
+ rows.push({
157
+ label: `${names} both cover the ${months} ending ${shared.map((period) => period.endLabel).join(" and ")}. The five forms are meant to run one quarter after another, each taking its period from a dropdown of the month ends the book carries, so no period should reach two of them. Filing all five as they stand would declare ${shared.length === 1 ? "that period" : "those periods"} twice.`,
158
+ value: "",
159
+ });
160
+ rows.push({
161
+ label: `Output VAT on ${shared.length === 1 ? "it" : "those"}`,
162
+ value: reportAmount(shared.reduce((total, p) => total + p.outputVat, 0)),
163
+ indent: 1,
164
+ });
165
+ rows.push({
166
+ label: `Input VAT on ${shared.length === 1 ? "it" : "those"}`,
167
+ value: reportAmount(shared.reduce((total, p) => total + p.inputVat, 0)),
168
+ indent: 1,
169
+ });
170
+ }
171
+
172
+ return [{ label: "**How the return periods line up with the accounting year**", value: "" }, ...rows];
173
+ }
174
+
175
+ // Which interface period each return form covers, and where the forms fall
176
+ // short of a clean cycle. A return covers the period its own end date names
177
+ // and the two before it, which is what the interface's rolling three-row sums
178
+ // total. Shared by the report prose above and by the products' cycle checks,
179
+ // so both read the same coverage.
180
+ export function vatReturnCoverage(periods, forms) {
181
+ const byRow = new Map(periods.map((period) => [period.row, period]));
182
+ const coverage = new Map(); // interface row -> the names of the forms covering it
183
+ const placed = [];
184
+
185
+ for (const form of forms) {
186
+ if (form.end === null || !byRow.has(form.end)) continue;
187
+ const covers = [form.end - 2, form.end - 1, form.end].filter((row) => byRow.has(row));
188
+ for (const row of covers) coverage.set(row, [...(coverage.get(row) ?? []), form.name]);
189
+ placed.push({ name: form.name, row: form.end, covers });
190
+ }
191
+
192
+ return {
193
+ byRow,
194
+ coverage,
195
+ placed,
196
+ missed: periods.filter((period) => period.inAccountingYear && !coverage.has(period.row)),
197
+ outside: periods.filter((period) => !period.inAccountingYear && coverage.has(period.row)),
198
+ shared: periods.filter((period) => (coverage.get(period.row) ?? []).length > 1),
199
+ };
200
+ }
201
+
202
+ export const COMPLIANCE_CHECKS_TITLE = "Compliance Checks";
203
+
204
+ // The same check table generateReport prints inline, as its own section, so
205
+ // a report generated without a full narrative (report.js's roundtrip mode)
206
+ // still carries the verdicts alongside the values.
207
+ export function complianceChecksLines(checks) {
208
+ const lines = [
209
+ "",
210
+ `## ${COMPLIANCE_CHECKS_TITLE}`,
211
+ "",
212
+ "| Check | Expected | Actual | Diff | Result |",
213
+ "|-------|----------|--------|------|--------|",
214
+ ];
215
+ for (const c of checks) {
216
+ const result = c.pass ? "PASS" : c.severity === "warning" ? "**WARNING**" : "**FAIL**";
217
+ lines.push(`| ${c.name} | ${c.expected} | ${c.actual} | ${c.diff > 0 ? "+" : ""}${c.diff} | ${result} |`);
218
+ }
219
+ return lines;
220
+ }
221
+
222
+ export function generateReport(packageName, scenarioName, results, checks, productMod, scenario) {
223
+ const hasFail = checks.some((c) => !c.pass && c.severity !== "warning");
224
+ const hasWarning = checks.some((c) => !c.pass && c.severity === "warning");
225
+ const status = hasFail ? "ANOMALYDETECTED" : hasWarning ? "RECONCILES (with warnings)" : "RECONCILES";
226
+ const lines = [`# Reconciliation Report: ${packageName}`, ``, `Scenario: ${scenarioName}`, `Status: ${status}`];
227
+
228
+ // The scenario's own words about the business the figures below belong to.
229
+ // Without them a reader has the figures and no account of what was put in.
230
+ const metadata = scenario?.metadata ?? {};
231
+ if (metadata.description) lines.push(``, metadata.description);
232
+ if (scenario?.business?.description) lines.push(``, `Trade: ${scenario.business.description}`);
233
+
234
+ lines.push(...complianceChecksLines(checks));
235
+
236
+ // The bridge sits straight under the checks: it is the one section that
237
+ // explains a difference the checks only prove correct.
238
+ if (typeof productMod.profitBridge === "function") {
239
+ lines.push(...profitBridgeLines(productMod.profitBridge(results)));
240
+ }
241
+
242
+ // Then the netting, which explains the other difference the checks only
243
+ // prove correct: a journal figure and the statement figure it becomes.
244
+ if (typeof productMod.categoryNetting === "function") {
245
+ lines.push(...categoryNettingLines(productMod.categoryNetting(results, scenario)));
246
+ }
247
+
248
+ // Formatted accounting statements (if product module provides them)
249
+ if (typeof productMod.reportSections === "function") {
250
+ const sections = productMod.reportSections(results);
251
+ for (const section of sections) {
252
+ lines.push("");
253
+ lines.push(`## ${section.title}`);
254
+ lines.push("");
255
+ lines.push("| | Amount |");
256
+ lines.push("|---|------:|");
257
+ for (const row of section.rows) {
258
+ if (!row.label && !row.value) {
259
+ lines.push("| | |");
260
+ } else {
261
+ const indent = row.indent ? "&nbsp;&nbsp;&nbsp;&nbsp;".repeat(row.indent) : "";
262
+ lines.push(`| ${indent}${row.label} | ${row.value} |`);
263
+ }
264
+ }
265
+ }
266
+ }
267
+
268
+ // Cell-by-cell appendix with DIY labels and diya-gl mappings
269
+ const labels = typeof productMod.cellLabels === "function" ? productMod.cellLabels() : {};
270
+
271
+ lines.push("");
272
+ lines.push("---");
273
+ lines.push("");
274
+ lines.push("## Appendix: Cell Values");
275
+ lines.push("");
276
+
277
+ for (const [sheetName, cells] of Object.entries(results)) {
278
+ if (!cells || typeof cells !== "object") continue;
279
+ const entries = Object.entries(cells).filter(([, v]) => v !== null && v !== undefined && v !== "" && v !== " ");
280
+ if (entries.length === 0) continue;
281
+ lines.push(`### ${sheetName}`);
282
+ lines.push("");
283
+ lines.push("| Cell | DIY Label | Value | diya-gl mapping |");
284
+ lines.push("|------|-----------|-------|-----------------|");
285
+ for (const [cell, val] of entries) {
286
+ const key = `${sheetName}!${cell}`;
287
+ const lbl = labels[key];
288
+ const diyLabel = lbl?.diyLabel || "";
289
+ const glMapping = lbl?.glMapping || "";
290
+ lines.push(`| ${cell} | ${diyLabel} | ${val} | ${glMapping} |`);
291
+ }
292
+ lines.push("");
293
+ }
294
+
295
+ return { content: lines.join("\n"), compliant: !hasFail };
296
+ }
297
+
298
+ /**
299
+ * Generate individual report files, one per reportSections() section.
300
+ * Returns { "filename.md": content } map.
301
+ */
302
+ export function generateSectionReports(results, productMod, scenario, checks) {
303
+ const reports = {};
304
+
305
+ if (typeof productMod.reportSections !== "function") return reports;
306
+
307
+ const sections = productMod.reportSections(results);
308
+ for (const section of sections) {
309
+ const lines = [];
310
+ lines.push(`# ${section.title}`);
311
+ lines.push("");
312
+ lines.push("| | Amount |");
313
+ lines.push("|---|------:|");
314
+ for (const row of section.rows) {
315
+ if (!row.label && !row.value) {
316
+ lines.push("| | |");
317
+ } else {
318
+ const indent = row.indent ? "&nbsp;&nbsp;&nbsp;&nbsp;".repeat(row.indent) : "";
319
+ lines.push(`| ${indent}${row.label} | ${row.value} |`);
320
+ }
321
+ }
322
+ lines.push("");
323
+
324
+ const filename =
325
+ section.title
326
+ .toLowerCase()
327
+ .replace(/[^a-z0-9]+/g, "-")
328
+ .replace(/-+$/, "") + ".md";
329
+ reports[filename] = lines.join("\n");
330
+ }
331
+
332
+ if (checks && checks.length > 0) {
333
+ reports["compliance-checks.md"] = [`# ${COMPLIANCE_CHECKS_TITLE}`, ...complianceChecksLines(checks).slice(2), ""].join("\n");
334
+ }
335
+
336
+ if (typeof productMod.profitBridge === "function") {
337
+ const bridgeLines = profitBridgeLines(productMod.profitBridge(results));
338
+ if (bridgeLines.length > 0) {
339
+ reports["accounting-profit-to-tax-profit-bridge.md"] = [`# ${PROFIT_BRIDGE_TITLE}`, ...bridgeLines.slice(2), ""].join("\n");
340
+ }
341
+ }
342
+
343
+ if (typeof productMod.categoryNetting === "function") {
344
+ const nettingLines = categoryNettingLines(productMod.categoryNetting(results, scenario));
345
+ if (nettingLines.length > 0) {
346
+ reports["journal-category-vat-netting.md"] = [`# ${CATEGORY_NETTING_TITLE}`, ...nettingLines.slice(2), ""].join("\n");
347
+ }
348
+ }
349
+
350
+ // Cell appendix
351
+ const labels = typeof productMod.cellLabels === "function" ? productMod.cellLabels() : {};
352
+ const appendixLines = ["# Cell Values", ""];
353
+ for (const [sheetName, cells] of Object.entries(results)) {
354
+ if (!cells || typeof cells !== "object") continue;
355
+ const entries = Object.entries(cells).filter(([, v]) => v !== null && v !== undefined && v !== "" && v !== " ");
356
+ if (entries.length === 0) continue;
357
+ appendixLines.push(`## ${sheetName}`);
358
+ appendixLines.push("");
359
+ appendixLines.push("| Cell | DIY Label | Value | diya-gl mapping |");
360
+ appendixLines.push("|------|-----------|-------|-----------------|");
361
+ for (const [cell, val] of entries) {
362
+ const key = `${sheetName}!${cell}`;
363
+ const lbl = labels[key];
364
+ const diyLabel = lbl?.diyLabel || "";
365
+ const glMapping = lbl?.glMapping || "";
366
+ const displayVal = typeof val === "number" ? parseFloat(val.toPrecision(15)) : val;
367
+ appendixLines.push(`| ${cell} | ${diyLabel} | ${displayVal} | ${glMapping} |`);
368
+ }
369
+ appendixLines.push("");
370
+ }
371
+ reports["cell-values.md"] = appendixLines.join("\n");
372
+
373
+ return reports;
374
+ }