@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,1348 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: AGPL-3.0-only
3
+ // Copyright (C) 2026 DIY Accounting Ltd
4
+ //
5
+ // extract-scenarios.js — Write every reconciliation fixture, and the diya-gl
6
+ // subset behind it, from the master books under examples/.
7
+ //
8
+ // Usage:
9
+ // node app/bin/extract-scenarios.js
10
+ //
11
+ // One master a business, one subset a product the business is kept on. A
12
+ // fixture states no figure of its own: the transactions come from the
13
+ // master's journals, the ledgers and registers from its book, and every
14
+ // [expected] figure is worked out here from the two.
15
+ //
16
+ // Reads: examples/precision-code-ltd/{book.toml,lines.jsonl}
17
+ // examples/brickwork-pro/{book.toml,lines.jsonl}
18
+ // examples/sp-sixty-driving/{book.toml,lines.jsonl}
19
+ // examples/kestrel-executive-cars/{book.toml,lines.jsonl}
20
+ // examples/basic-taxi-driver/{book.toml,lines.jsonl}
21
+ // examples/autumn-start-cabs/{book.toml,lines.jsonl}
22
+ //
23
+ // Writes: a book.toml and lines.jsonl subset directory under each master,
24
+ // and the twelve fixtures under app/test/fixtures/.
25
+
26
+ import { parse as parseTOML } from "smol-toml";
27
+ import { readFileSync, writeFileSync, mkdirSync } from "fs";
28
+ import { join, resolve, dirname } from "path";
29
+ import { fileURLToPath } from "url";
30
+ import { canonicalBookToml, canonicalLinesJsonl } from "../lib/diya-gl-canonical.js";
31
+ import {
32
+ buildClosingDebtors,
33
+ HP_AGREEMENT_FIELD,
34
+ CIS_DEDUCTION_FIELD,
35
+ LTD_PURCHASE_CODE_MAP,
36
+ BST_PURCHASE_CODE_MAP,
37
+ SE_PURCHASE_CODE_MAP,
38
+ TAXI_PURCHASE_CODE_MAP,
39
+ TAXI_BST_PURCHASE_CODE_MAP,
40
+ assertPurchaseCodesCoverChart,
41
+ filterBst,
42
+ bstStaffWagesAsPurchases,
43
+ filterAdvanced,
44
+ filterFull,
45
+ buildGrouped,
46
+ buildPayroll,
47
+ seDrawingsFromDividends,
48
+ withoutDirectorPayroll,
49
+ monthlySalesTotals,
50
+ takingsOnlySales,
51
+ fixedAssetAdditions,
52
+ buildOpeningBalance,
53
+ toV2OpeningBalances,
54
+ formatScenarioToml,
55
+ buildSubsetBook,
56
+ bstAccountFilter,
57
+ seAccountFilter,
58
+ fullAccountFilter,
59
+ getMonthKey,
60
+ taxiExpectedFigures,
61
+ totalsByCode,
62
+ bstExpectedFigures,
63
+ computeNetSales,
64
+ computeSpreadsheetNetSales,
65
+ splitStraddlingLines,
66
+ deriveStraddlingEntries,
67
+ } from "../lib/scenario-extractor.js";
68
+ import { totalBusinessMiles, calculateMileageAllowance, HMRC_CAR_MILEAGE_RATES } from "../lib/tax/mileage.js";
69
+
70
+ const __dirname = dirname(fileURLToPath(import.meta.url));
71
+ const ROOT = resolve(__dirname, "..", "..");
72
+ const FIXTURES_DIR = join(ROOT, "app", "test", "fixtures");
73
+
74
+ // ============================================================================
75
+ // Masters in, fixtures out
76
+ // ============================================================================
77
+
78
+ function readMaster(name) {
79
+ const dir = join(ROOT, "examples", name);
80
+ const book = parseTOML(readFileSync(join(dir, "book.toml"), "utf-8"));
81
+ const lines = readFileSync(join(dir, "lines.jsonl"), "utf-8")
82
+ .split("\n")
83
+ .filter((line) => line.trim().length > 0)
84
+ .map((line) => JSON.parse(line));
85
+ return { dir, book, lines };
86
+ }
87
+
88
+ // One product's slice of a master, written where the master keeps it. The
89
+ // canonical writer owns the field order and the money formatting, so a
90
+ // subset and an export of the same book are text-identical.
91
+ const extracted = [];
92
+
93
+ function writeSubset(masterDir, subsetName, book, subsetSpec, lines) {
94
+ const dir = join(masterDir, subsetName);
95
+ mkdirSync(dir, { recursive: true });
96
+ writeFileSync(join(dir, "book.toml"), canonicalBookToml(buildSubsetBook(book, { subsetName, ...subsetSpec })));
97
+ writeFileSync(join(dir, "lines.jsonl"), canonicalLinesJsonl(lines));
98
+ return { dataLines: lines.length };
99
+ }
100
+
101
+ function writeFixture(name, toml) {
102
+ writeFileSync(join(FIXTURES_DIR, `${name}.toml`), toml);
103
+ const rows = (table) => (toml.match(new RegExp(`^\\[\\[${table}[.\\]]`, "gm")) || []).length;
104
+ extracted.push({ name, sales: rows("sales"), purchases: rows("purchases"), bank: rows("bank"), payroll: rows("payroll") });
105
+ }
106
+
107
+ // The [business] block every product's Admin sheet takes, from the book's
108
+ // own entity information.
109
+ function businessBlock(entity, extra = {}) {
110
+ const business = { name: entity.organizationIdentifier, description: extra.description || entity.organizationDescription };
111
+ if (extra.company_number) business.company_number = extra.company_number;
112
+ if (entity.organizationAddressLine) business.address = entity.organizationAddressLine;
113
+ if (entity.organizationTown) business.town = entity.organizationTown;
114
+ if (entity.organizationPostcode) business.postcode = entity.organizationPostcode;
115
+ if (extra.omitContact !== true) {
116
+ if (entity.organizationTelephone) business.phone = entity.organizationTelephone;
117
+ if (entity.taxRegistrationNumber) business.utr = entity.taxRegistrationNumber;
118
+ }
119
+ if (extra.vat_number) business.vat_number = extra.vat_number;
120
+ if (extra.nino) business.nino = extra.nino;
121
+ return business;
122
+ }
123
+
124
+ // The debtor and creditor ledgers the master book publishes. Each listing
125
+ // names its counterparty and the invoice still open, timed opening or
126
+ // closing, and every scenario takes the same two ledgers -- one business, one
127
+ // year end.
128
+ function ledgerListing(entries, nameField, timing) {
129
+ return (entries || [])
130
+ .filter((entry) => entry.timing === timing)
131
+ .map((entry) => ({ [nameField]: entry.counterparty, invoice: entry.invoice, amount: entry.amount }));
132
+ }
133
+
134
+ const dateOnly = (value) => (value instanceof Date ? value.toISOString().slice(0, 10) : value);
135
+
136
+ const VAT_ON = (gross, rate) => Math.round(((gross * rate) / (1 + rate)) * 100) / 100;
137
+
138
+ // The Company keeps four bank accounts, each with its own letter for a
139
+ // transfer to or from it (ltd-layout.js's BANK_TRANSFER_CODES: BB/BS/BD/BC
140
+ // for Current/Savings/CreditCard/Cash), and app/products/ltd.js writes any
141
+ // "BC"-coded line straight to the account's own opening-balance cell,
142
+ // whatever the date. SE keeps only two of those four accounts, and its own
143
+ // template already spends "BC" the same way -- se.js's BANK_ACCOUNT_FILES
144
+ // treats every "BC" line as an opening balance too -- so a genuine transfer
145
+ // that happens to carry the Company's "BC" letter would land in SE as a
146
+ // second opening balance instead of a statement line. Only a "BC" line
147
+ // dated the period's first day is really an opening balance (see T20's
148
+ // bankMonthTotals); every other line coded with one of the four transfer
149
+ // letters is a real transfer, and reaches SE under SE's own letter for the
150
+ // account it lands on instead: Bank.xlsx (1200) analyses a transfer under
151
+ // "X", the same letter every other uncoded intra-company movement uses;
152
+ // Cash.xlsx (1220) already analyses one under "BB", the letter the Company
153
+ // gives it. Savings and CreditCard have no SE equivalent, so a transfer
154
+ // naming either drops out with the rest of that account's lines once
155
+ // filterAdvanced runs.
156
+ const LTD_BANK_TRANSFER_CODES = new Set(["BB", "BS", "BD", "BC"]);
157
+ const SE_BANK_TRANSFER_CODE = { 1200: "X", 1220: "BB" };
158
+
159
+ function isLtdOpeningBankLine(line, periodStart) {
160
+ return line["diya-gl:bankCode"] === "BC" && line.postingDate === periodStart;
161
+ }
162
+
163
+ function mapLtdBankCodeForSe(line, periodStart) {
164
+ const code = line["diya-gl:bankCode"];
165
+ if (!LTD_BANK_TRANSFER_CODES.has(code) || isLtdOpeningBankLine(line, periodStart)) return line;
166
+ const seCode = SE_BANK_TRANSFER_CODE[line["diya-gl:bankAccountID"]];
167
+ return seCode ? { ...line, "diya-gl:bankCode": seCode } : line;
168
+ }
169
+
170
+ function mapLtdBankCodesForSe(lines, book) {
171
+ const periodStart = dateOnly(book.documentInfo.periodCoveredStart);
172
+ return lines.map((line) => (line.sourceJournalID === "bank" ? mapLtdBankCodeForSe(line, periodStart) : line));
173
+ }
174
+
175
+ // ============================================================================
176
+ // Precision Code Ltd — an IT consultancy kept as a company, a self employed
177
+ // trader and a basic sole trader
178
+ // ============================================================================
179
+
180
+ const { dir: PRECISION_DIR, book, lines: precisionLines } = readMaster("precision-code-ltd");
181
+
182
+ // The straddling lines carry diya-gl:vatPeriodEnd, dated before the book
183
+ // opens or after it closes; every function below that builds the accounting
184
+ // year's own figures has to see only the year's own lines.
185
+ const { yearLines: allLines, straddlingLines } = splitStraddlingLines(precisionLines);
186
+
187
+ // The one dividend the master book declares for the year. book.dividends is
188
+ // an array (a book could in principle declare more than one), but this
189
+ // scenario only ever has the single board resolution.
190
+ const masterDividend = book.dividends[0];
191
+
192
+ const precisionEntity = book.entityInformation;
193
+ const precisionAddress = {
194
+ organizationAddressLine: precisionEntity.organizationAddressLine,
195
+ organizationTown: precisionEntity.organizationTown,
196
+ organizationPostcode: precisionEntity.organizationPostcode,
197
+ organizationTelephone: precisionEntity.organizationTelephone,
198
+ };
199
+
200
+ // The name the company's book reads under when the same year is kept as a
201
+ // sole trader's. The trade itself doesn't change between the company and its
202
+ // sole-trader telling of the same year, so the description carries over from
203
+ // the master entity rather than a second, separately worded copy of it.
204
+ const PRECISION_SOLE_TRADER = {
205
+ organizationIdentifier: "Precision Code Trading",
206
+ };
207
+
208
+ function precisionSubsetEntity(product, { vatRegistered }) {
209
+ const entity = {
210
+ ...PRECISION_SOLE_TRADER,
211
+ "organizationDescription": precisionEntity.organizationDescription,
212
+ ...precisionAddress,
213
+ "taxRegistrationNumber": precisionEntity.taxRegistrationNumber,
214
+ "taxAuthorityIdentifier": "HMRC",
215
+ "diya-gl:product": product,
216
+ "diya-gl:vatRegistered": vatRegistered,
217
+ "diya-gl:basisOfAccounting": "cash",
218
+ };
219
+ if (vatRegistered) entity["diya-gl:vatNumber"] = precisionEntity["diya-gl:vatNumber"];
220
+ return entity;
221
+ }
222
+
223
+ // ============================================================================
224
+ // Precision Code ledgers, registers and agreements
225
+ // ============================================================================
226
+
227
+ // The Basic Sole Trader package has one cell a side for what was owed when
228
+ // the year opened -- the "Owed start year" figures at C3 and F3 on its
229
+ // Debtors & Creditors sheet -- and no room anywhere for the names behind
230
+ // them. Its book states the two totals on openingBalances, which is where
231
+ // both the writer and the export read them.
232
+ function bstOpeningBalances(openingDebtorEntries, openingCreditorEntries) {
233
+ const total = (entries) => Math.round(entries.reduce((sum, entry) => sum + entry.amount, 0) * 100) / 100;
234
+ return { tradeDebtors: total(openingDebtorEntries), tradeCreditors: total(openingCreditorEntries) };
235
+ }
236
+
237
+ function bstOpeningBalanceBlock(openingBalances) {
238
+ return { opening_balance: { trade_debtors: openingBalances.tradeDebtors, trade_creditors: openingBalances.tradeCreditors } };
239
+ }
240
+
241
+ const openingDebtors = ledgerListing(book.debtors, "customer", "opening");
242
+ const publishedClosingDebtors = ledgerListing(book.debtors, "customer", "closing");
243
+ const openingCreditors = ledgerListing(book.creditors, "supplier", "opening");
244
+ const closingCreditors = ledgerListing(book.creditors, "supplier", "closing");
245
+
246
+ // What the bank journal leaves unsettled has to be the ledger the book
247
+ // publishes. Working it out from the invoices raised and the money banked
248
+ // keeps the two tied together, so master data that moves one without the
249
+ // other stops the extract.
250
+ const closingDebtors = buildClosingDebtors(allLines, openingDebtors);
251
+ const asDebtorKey = (debtor) => `${debtor.invoice} ${debtor.customer} ${debtor.amount}`;
252
+ const workedOut = closingDebtors.map(asDebtorKey).sort().join(", ");
253
+ const published = publishedClosingDebtors.map(asDebtorKey).sort().join(", ");
254
+ if (workedOut !== published) {
255
+ throw new Error(`The bank journal leaves ${workedOut} owing, against a published closing debtor ledger of ${published}`);
256
+ }
257
+
258
+ // Sales and purchases in the VAT periods either side of the accounting year,
259
+ // derived from the master's own straddling lines (sales/purchases lines
260
+ // carrying diya-gl:vatPeriodEnd). The VAT workbook keeps a pair of entry
261
+ // sheets per straddling period and the figures reach the VAT return without
262
+ // ever touching the books, so these are the only transactions in the fixture
263
+ // that move a VAT box and leave the trial balance where it was.
264
+ const { periodCoveredStart, periodCoveredEnd } = book.documentInfo;
265
+ const straddlingSales = deriveStraddlingEntries(straddlingLines, "sales", "customer", periodCoveredStart, periodCoveredEnd);
266
+ const straddlingPurchases = deriveStraddlingEntries(straddlingLines, "purchases", "supplier", periodCoveredStart, periodCoveredEnd);
267
+
268
+ // A subset book keeps those same lines beside the accounting year's own, so
269
+ // a book read from lines carries the VAT return the scenario TOML above
270
+ // states. diyaGlToScenario splits them straight back out, exactly as this
271
+ // file does, and derives the same entries from them, so the year's figures
272
+ // never see them. A subset whose business is not registered for VAT files no
273
+ // return at all, so a line dated by a VAT period has nothing there to reach.
274
+ function withStraddling(lines, { vatRegistered }) {
275
+ return vatRegistered ? [...lines, ...straddlingLines] : lines;
276
+ }
277
+
278
+ // The hire purchase agreements the master book declares, in the scenario's
279
+ // own field names. Each one finances one purchase; the HPfinance sheet works
280
+ // the monthly payment and the capital and interest split out for itself.
281
+ const hpAgreements = book.hpAgreements.map((agreement) => ({
282
+ date: dateOnly(agreement.startDate),
283
+ finance_company: agreement.financeCompany,
284
+ reference: agreement.agreementID,
285
+ amount_financed: agreement.amountFinanced,
286
+ admin_charges: agreement.adminCharges,
287
+ total_interest: agreement.totalInterest,
288
+ months: agreement.termMonths,
289
+ supplier: agreement.supplier,
290
+ }));
291
+
292
+ // The fixed assets the book holds at the opening balance sheet date, on the
293
+ // Schedule's own terms. tax_wdv is the written down value the capital
294
+ // allowances working brings forward, which is not the accounting
295
+ // depreciation and is the register's own figure.
296
+ const OPENING_ASSET_CATEGORIES = { motorVehicles: "motor", computerTechnology: "computer", landBuildings: "land" };
297
+
298
+ const openingFixedAssets = book.fixedAssets.map((asset) => {
299
+ const opening = {
300
+ category: OPENING_ASSET_CATEGORIES[asset.class],
301
+ description: asset.description,
302
+ cost: asset.cost,
303
+ acc_dep: asset.accumulatedDepreciation,
304
+ };
305
+ if (asset.taxWrittenDownValue !== undefined) opening.tax_wdv = asset.taxWrittenDownValue;
306
+ return opening;
307
+ });
308
+
309
+ // SE's Schedule has no land block (se.js EXISTING_ASSET_ROWS only carries
310
+ // motor and computer), the same restriction filterAdvanced already applies
311
+ // to the rest of the opening journal (only accounts 0030/0040 pass). Ltd's
312
+ // Schedule and OpenAccounts both take land, so the full set stands there.
313
+ const seOpeningFixedAssets = openingFixedAssets.filter((asset) => asset.category !== "land");
314
+
315
+ // The charges registered over the company's assets, from the book's own
316
+ // register. Each one secures a creditor falling due after more than one year.
317
+ const chargesRegister = book.charges.map((charge) => ({
318
+ date: dateOnly(charge.chargeDate),
319
+ asset: charge.description,
320
+ valuation: charge.valuation,
321
+ holder: charge.holder,
322
+ terms: charge.terms,
323
+ board_meeting: dateOnly(charge.boardMeetingDate),
324
+ }));
325
+
326
+ // ============================================================================
327
+ // Extract BST (basic)
328
+ // ============================================================================
329
+
330
+ const bstLines = filterBst(bstStaffWagesAsPurchases(allLines));
331
+ const bstGrouped = buildGrouped(bstLines, BST_PURCHASE_CODE_MAP, {
332
+ carriesCisDeductions: false,
333
+ carriesSourceFields: true,
334
+ carriesMileage: "claims",
335
+ });
336
+ const bstFigures = bstExpectedFigures(bstLines, book.stock);
337
+ const bstEntity = precisionSubsetEntity("BasicSoleTrader", { vatRegistered: false });
338
+
339
+ // Purchases coded f capitalise out of the profit and loss account. The Fixed
340
+ // Assets schedule is where they earn their capital allowance, so the same
341
+ // purchases are registered there. A schedule short of the journal strands the
342
+ // spend in neither statement.
343
+ const bstFixedAssetAdditions = fixedAssetAdditions(bstLines, BST_PURCHASE_CODE_MAP, "f");
344
+ const bstOpeningLedger = bstOpeningBalances(openingDebtors, openingCreditors);
345
+
346
+ const bstToml = formatScenarioToml(
347
+ {
348
+ name: "Precision Code - basic sole trader",
349
+ description: "BST-scoped extract from Precision Code Ltd master data. Sales + purchases, 14 BST expense codes, no VAT/bank/payroll.",
350
+ product: "bst",
351
+ tax_regime: "se",
352
+ vat_registered: false,
353
+ business: businessBlock(bstEntity),
354
+ },
355
+ bstGrouped,
356
+ {
357
+ ...bstFigures,
358
+ ...bstOpeningBalanceBlock(bstOpeningLedger),
359
+ // In-year additions go in the "Bought AFTER" block on the Fixed Assets
360
+ // schedule. 100% Annual Investment Allowance applies, so the full cost is
361
+ // claimed in the year.
362
+ fixed_asset_additions: bstFixedAssetAdditions,
363
+ },
364
+ );
365
+
366
+ const bstV2 = {
367
+ stock: { openingValue: 10000, closingValue: 6000 },
368
+ openingBalances: bstOpeningLedger,
369
+ // The named ledgers the trade actually kept. The Basic Sole Trader sheets
370
+ // have no counterparty column to hold them, so the round trip declares them
371
+ // structurally absent rather than dropping them out of the book and leaving
372
+ // the absence unmeasured.
373
+ debtors: book.debtors,
374
+ creditors: book.creditors,
375
+ fixedAssets: bstFixedAssetAdditions.map((asset, index) => ({
376
+ assetID: `BST-FA-${index + 1}`,
377
+ description: asset.description,
378
+ cost: asset.cost,
379
+ acquiredDate: asset.date,
380
+ })),
381
+ };
382
+
383
+ writeFixture("bst-scenario-basic", bstToml);
384
+ const bstDiya = writeSubset(
385
+ PRECISION_DIR,
386
+ "bst",
387
+ book,
388
+ {
389
+ entity: bstEntity,
390
+ taxSections: ["incomeTax", "nationalInsurance", "capitalAllowances", "mileage"],
391
+ accountFilter: bstAccountFilter,
392
+ tables: bstV2,
393
+ },
394
+ withStraddling(bstLines, { vatRegistered: false }),
395
+ );
396
+
397
+ // ============================================================================
398
+ // Extract SE (advanced)
399
+ // ============================================================================
400
+
401
+ const advLines = seDrawingsFromDividends(filterAdvanced(mapLtdBankCodesForSe(allLines, book)));
402
+ const advSalesLines = advLines.filter((l) => l.sourceJournalID === "sales");
403
+ const SE_TURNOVER_ACCOUNTS = new Set(["4000", "4001", "4002", "4003"]);
404
+ const advTurnoverLines = advSalesLines.filter((l) => SE_TURNOVER_ACCOUNTS.has(l.accountMainID));
405
+ const advTotalSales = computeSpreadsheetNetSales(advTurnoverLines);
406
+ const advGrouped = buildGrouped(advLines, SE_PURCHASE_CODE_MAP, { carriesSourceFields: true, carriesMileage: "claims" });
407
+ advGrouped.payroll = buildPayroll(advLines, { carriesSourceFields: true, employees: book.employees });
408
+ const advPurchLines = advLines.filter((l) => l.sourceJournalID === "purchases");
409
+ const advByCode = {};
410
+ advPurchLines.forEach((l) => {
411
+ const c = SE_PURCHASE_CODE_MAP[l.accountMainID];
412
+ if (c) advByCode[c] = (advByCode[c] || 0) + l.amount;
413
+ });
414
+ // A mileage-log line buys nothing: the Purchases sheet prices the year's
415
+ // business miles itself and files the claim under Motor Expenses with no VAT
416
+ // on it, so the motoring total leaves the line's own amount out and takes the
417
+ // claim instead. Trusting the amount the master states would tie the figure
418
+ // to whichever package that line was priced for.
419
+ const advBusinessMiles = totalBusinessMiles(advPurchLines);
420
+ const advCashMotor = advPurchLines
421
+ .filter((l) => !(l.measurableUnitOfMeasure === "miles" && typeof l.measurableQuantity === "number"))
422
+ .filter((l) => SE_PURCHASE_CODE_MAP[l.accountMainID] === "v")
423
+ .reduce((sum, l) => sum + l.amount, 0);
424
+ const advToml = formatScenarioToml(
425
+ {
426
+ name: "Precision Code - advanced self employed",
427
+ description: "SE-scoped extract from Precision Code Ltd master data. Sales + purchases + bank + payroll, with VAT.",
428
+ product: "se",
429
+ tax_regime: "se",
430
+ vat_registered: true,
431
+ business: {
432
+ name: "Precision Code Trading",
433
+ description: "IT consultancy and software development",
434
+ address: "123 High Street",
435
+ town: "Manchester",
436
+ postcode: "M1 1AA",
437
+ phone: "0161 555 0100",
438
+ utr: "1234567890",
439
+ vat_number: "123456789",
440
+ nino: "AB123456C",
441
+ },
442
+ employees: book.employees || [],
443
+ },
444
+ advGrouped,
445
+ {
446
+ total_sales: advTotalSales,
447
+ total_mileage: advBusinessMiles,
448
+ total_motor_net: Math.round((advCashMotor / 1.2 + calculateMileageAllowance(advBusinessMiles, HMRC_CAR_MILEAGE_RATES)) * 100) / 100,
449
+ total_legal_net: Math.round((advByCode.l || 0) / 1.2),
450
+ opening_stock: 10000,
451
+ closing_stock: 6000,
452
+ opening_fixed_assets: seOpeningFixedAssets,
453
+ opening_debtors: openingDebtors,
454
+ closing_debtors: closingDebtors,
455
+ opening_creditors: openingCreditors,
456
+ closing_creditors: closingCreditors,
457
+ vat_straddling_sales: straddlingSales,
458
+ vat_straddling_purchases: straddlingPurchases,
459
+ hp_agreements: hpAgreements,
460
+ },
461
+ );
462
+
463
+ const advV2 = {
464
+ stock: { openingValue: 10000, closingValue: 6000 },
465
+ debtors: book.debtors,
466
+ creditors: book.creditors,
467
+ // Same restriction as seOpeningFixedAssets above: SE's Schedule has no
468
+ // land block, so a land & buildings asset the master book holds is a Ltd
469
+ // fact, not one this subset can carry.
470
+ fixedAssets: book.fixedAssets.filter((asset) => asset.class !== "landBuildings"),
471
+ hpAgreements: book.hpAgreements,
472
+ };
473
+
474
+ writeFixture("se-scenario-advanced", advToml);
475
+ const advDiya = writeSubset(
476
+ PRECISION_DIR,
477
+ "advanced",
478
+ book,
479
+ {
480
+ entity: precisionSubsetEntity("SelfEmployed", { vatRegistered: true }),
481
+ taxSections: ["incomeTax", "nationalInsurance", "vat", "capitalAllowances", "mileage"],
482
+ accountFilter: seAccountFilter,
483
+ employees: book.employees,
484
+ tables: advV2,
485
+ },
486
+ withStraddling(advLines, { vatRegistered: true }),
487
+ );
488
+
489
+ // ============================================================================
490
+ // Extract Ltd (full)
491
+ // ============================================================================
492
+
493
+ const fullLines = filterFull(allLines);
494
+ const fullSalesLines = fullLines.filter((l) => l.sourceJournalID === "sales");
495
+ const LTD_TURNOVER_ACCOUNTS = new Set(["4000", "4001", "4002", "4003", "4004"]);
496
+ const fullTurnoverLines = fullSalesLines.filter((l) => LTD_TURNOVER_ACCOUNTS.has(l.accountMainID));
497
+ const fullTotalSales = computeSpreadsheetNetSales(fullTurnoverLines);
498
+ const fullGrouped = buildGrouped(fullLines, LTD_PURCHASE_CODE_MAP, { carriesSourceFields: true });
499
+ fullGrouped.payroll = buildPayroll(fullLines, { carriesSourceFields: true, employees: book.employees });
500
+ const fullPurchLines = fullLines.filter((l) => l.sourceJournalID === "purchases");
501
+ const fullByCode = {};
502
+ fullPurchLines.forEach((l) => {
503
+ const c = LTD_PURCHASE_CODE_MAP[l.accountMainID];
504
+ if (c) fullByCode[c] = (fullByCode[c] || 0) + l.amount;
505
+ });
506
+ // The share register and the board minute, both from the master book. The
507
+ // register is the directors who hold shares; the minute is the dividend they
508
+ // declared for the year. Each is tied back to the ledger it has to agree
509
+ // with, so master data that moves without the other moving stops the extract
510
+ // rather than publishing a book that does not add up.
511
+ const NOMINAL_SHARE_VALUE = 1;
512
+ const fullMembers = book.members.map((member) => ({ name: member.name, shares: member.shares, acquired: dateOnly(member.acquiredDate) }));
513
+ const fullOpeningBalance = buildOpeningBalance(fullLines);
514
+ const fullSharesIssued = fullMembers.reduce((total, m) => total + m.shares, 0);
515
+ if (fullSharesIssued * NOMINAL_SHARE_VALUE !== fullOpeningBalance.share_capital) {
516
+ throw new Error(
517
+ `Register of members holds ${fullSharesIssued} shares at ${NOMINAL_SHARE_VALUE} each, ` +
518
+ `against share capital of ${fullOpeningBalance.share_capital} on the opening balance sheet`,
519
+ );
520
+ }
521
+
522
+ const fullDividendsPaid = fullLines
523
+ .filter((l) => l["diya-gl:bankCode"] === "DV")
524
+ .reduce((total, l) => total + (l.debitCreditCode === "C" ? l.amount : -l.amount), 0);
525
+ if (masterDividend.amount !== fullDividendsPaid) {
526
+ throw new Error(`The board minuted a dividend of ${masterDividend.amount}, against ${fullDividendsPaid} paid out of the bank`);
527
+ }
528
+
529
+ // Each hire purchase agreement pays for one purchase, at the purchase's cost
530
+ // net of VAT -- the VAT is the buyer's to settle, not the finance company's.
531
+ // The purchase reaches the books as an ordinary trade creditor and the
532
+ // year-end journal then moves the amount financed onto creditors falling due
533
+ // after more than one year. HPfinance!E2 totals the amounts financed and the
534
+ // trial balance reads it on both rows, so an agreement whose purchase is
535
+ // missing leaves the asset off the schedule and the reclassification with
536
+ // nothing to move.
537
+ const hpFinanced = hpAgreements.reduce((total, agreement) => total + agreement.amount_financed, 0);
538
+ const hpPurchasedNet = fullPurchLines
539
+ .filter((l) => l[HP_AGREEMENT_FIELD])
540
+ .reduce((total, l) => total + l.amount / (1 + (l.taxRate || 0)), 0);
541
+ if (hpFinanced !== hpPurchasedNet) {
542
+ throw new Error(`Hire purchase agreements finance ${hpFinanced}, against ${hpPurchasedNet} of purchases net of VAT bought under them`);
543
+ }
544
+
545
+ const fullToml = formatScenarioToml(
546
+ {
547
+ name: "Precision Code Ltd - full",
548
+ description: "Full Ltd-scoped extract from Precision Code Ltd master data. All journals, all accounts.",
549
+ product: "ltd",
550
+ tax_regime: "ltd",
551
+ vat_registered: true,
552
+ business: {
553
+ name: "Precision Code Ltd",
554
+ description: "IT consultancy and software development",
555
+ company_number: "12345678",
556
+ address: "123 High Street",
557
+ town: "Manchester",
558
+ postcode: "M1 1AA",
559
+ phone: "0161 555 0100",
560
+ utr: "1234567890",
561
+ vat_number: "123456789",
562
+ },
563
+ employees: book.employees || [],
564
+ members: fullMembers,
565
+ },
566
+ fullGrouped,
567
+ {
568
+ total_sales: fullTotalSales,
569
+ total_premises_net: Math.round((fullByCode.r || 0) / 1.2),
570
+ total_legal_net: Math.round((fullByCode.l || 0) / 1.2),
571
+ opening_balance: fullOpeningBalance,
572
+ opening_stock: 10000,
573
+ closing_stock: 6000,
574
+ // Three per cent of the consultancy's net sales is direct materials.
575
+ // Without it the Stock sheet's bought and sold columns stay switched off
576
+ // and the calculated stock never leaves the opening figure.
577
+ stock_materials_percent: 0.03,
578
+ charges: chargesRegister,
579
+ dividend: {
580
+ board_meeting: masterDividend.boardMeetingDate.toISOString().slice(0, 10),
581
+ declared: masterDividend.amount,
582
+ },
583
+ opening_fixed_assets: openingFixedAssets,
584
+ opening_debtors: openingDebtors,
585
+ closing_debtors: closingDebtors,
586
+ opening_creditors: openingCreditors,
587
+ closing_creditors: closingCreditors,
588
+ vat_straddling_sales: straddlingSales,
589
+ vat_straddling_purchases: straddlingPurchases,
590
+ hp_agreements: hpAgreements,
591
+ },
592
+ );
593
+
594
+ const fullV2 = {
595
+ openingBalances: toV2OpeningBalances(fullOpeningBalance),
596
+ stock: { openingValue: 10000, closingValue: 6000, materialsPercent: 0.03 },
597
+ debtors: book.debtors,
598
+ creditors: book.creditors,
599
+ fixedAssets: book.fixedAssets,
600
+ hpAgreements: book.hpAgreements,
601
+ dividends: book.dividends,
602
+ members: book.members,
603
+ charges: book.charges,
604
+ };
605
+
606
+ writeFixture("ltd-scenario-full", fullToml);
607
+ const fullDiya = writeSubset(
608
+ PRECISION_DIR,
609
+ "full",
610
+ book,
611
+ {
612
+ entity: precisionEntity,
613
+ taxSections: ["corporationTax", "capitalAllowances", "vat", "nationalInsurance", "dividends", "mileage", "incomeTax"],
614
+ accountFilter: fullAccountFilter,
615
+ directors: book.directors,
616
+ employees: book.employees,
617
+ tables: fullV2,
618
+ },
619
+ withStraddling(fullLines, { vatRegistered: true }),
620
+ );
621
+
622
+ // ============================================================================
623
+ // BrickWork Pro — a builder kept as a company, a self employed trader and a
624
+ // basic sole trader, each in two sizes: the trade the master books, and the
625
+ // registered twin trading half as much again
626
+ // ============================================================================
627
+
628
+ const { dir: BRICKWORK_DIR, book: brickBook, lines: brickMasterLines } = readMaster("brickwork-pro");
629
+
630
+ for (const [name, map] of [
631
+ ["LTD_PURCHASE_CODE_MAP", LTD_PURCHASE_CODE_MAP],
632
+ ["SE_PURCHASE_CODE_MAP", SE_PURCHASE_CODE_MAP],
633
+ ["BST_PURCHASE_CODE_MAP", BST_PURCHASE_CODE_MAP],
634
+ ]) {
635
+ assertPurchaseCodesCoverChart(brickBook, map, name);
636
+ }
637
+
638
+ const brickEntity = brickBook.entityInformation;
639
+ const brickAddress = {
640
+ organizationAddressLine: brickEntity.organizationAddressLine,
641
+ organizationTown: brickEntity.organizationTown,
642
+ organizationPostcode: brickEntity.organizationPostcode,
643
+ organizationTelephone: brickEntity.organizationTelephone,
644
+ };
645
+
646
+ // The payslip identifiers the two employees carry. A diya-gl book's employee
647
+ // table has no field for a National Insurance number, so the Payslips
648
+ // workbook takes them from here.
649
+ const BRICKWORK_NI_NUMBERS = { EMP001: "AB123456C", EMP002: "CD654321A" };
650
+
651
+ function brickworkEmployees(employees) {
652
+ return employees.map((employee) => ({ ...employee, niNumber: BRICKWORK_NI_NUMBERS[employee.employeeID] }));
653
+ }
654
+
655
+ // ---------------------------------------------------------------------------
656
+ // The registered twin
657
+ // ---------------------------------------------------------------------------
658
+
659
+ // The same firm trading half as much again, which is what puts it over the
660
+ // registration threshold, with VAT at 20% on top of every trade amount. The
661
+ // van is the same vehicle at the same net cost, so it carries the VAT and not
662
+ // the change in size. Money banked against a scaled invoice scales with it;
663
+ // wages, PAYE and corporation tax do not.
664
+ const TWIN_TRADE_SCALE = 1.5;
665
+ const TWIN_VAT_RATE = 0.2;
666
+ const TWIN_VAT_NUMBER = "376543219";
667
+ const TWIN_SCALED_OPENING_ACCOUNTS = new Set(["1300", "2100"]);
668
+ const TWIN_VAT_ACCOUNT = "2200";
669
+ const TWIN_RETAINED_EARNINGS_ACCOUNT = "3100";
670
+
671
+ // What the twin owes HMRC at the year start, and the three quarterly
672
+ // settlements that fall inside the year. The fourth quarter is still owed at
673
+ // the year end, which is what leaves the VAT return with a closing balance to
674
+ // carry.
675
+ const TWIN_OPENING_VAT_DUE = { date: "2025-04-07", amount: 1000 };
676
+ const TWIN_VAT_SETTLEMENTS = [
677
+ { date: "2025-08-07", amount: 1900 },
678
+ { date: "2025-11-07", amount: 1900 },
679
+ { date: "2026-02-07", amount: 1900 },
680
+ ];
681
+
682
+ const round2 = (value) => Math.round(value * 100) / 100;
683
+
684
+ function twinBankLine(date, amount, comment, reference, entryNumber) {
685
+ return {
686
+ "sourceJournalID": "bank",
687
+ "postingDate": date,
688
+ "accountMainID": "1200",
689
+ amount,
690
+ "detailComment": "HMRC",
691
+ "lineItemComment": comment,
692
+ "documentType": "bank-statement",
693
+ "documentReference": reference,
694
+ "taxCode": "OS",
695
+ "taxRate": 0,
696
+ "diya-gl:bankCode": "RV",
697
+ "debitCreditCode": "C",
698
+ "diya-gl:bankAccountID": "1200",
699
+ "entryNumber": entryNumber,
700
+ };
701
+ }
702
+
703
+ // What a month's invoices come to on one journal. A supplier payment settles
704
+ // the purchases month less the tax withheld from the sub-contractors among
705
+ // them, and a customer receipt settles the sales month less the tax a
706
+ // contractor customer withheld from this business.
707
+ function invoicedByMonth(lines, journal) {
708
+ const invoiced = {};
709
+ for (const line of lines) {
710
+ if (line.sourceJournalID !== journal) continue;
711
+ const month = line.postingDate.slice(0, 7);
712
+ invoiced[month] = round2((invoiced[month] || 0) + line.amount);
713
+ }
714
+ return invoiced;
715
+ }
716
+
717
+ // The month's tax under the Construction Industry Scheme on one journal. On
718
+ // purchases that is what the company withheld from its own sub-contractors
719
+ // and owes over to HMRC; on sales it is the other side of the scheme, the tax
720
+ // a contractor customer withheld from this business, which is never part of
721
+ // what the business remits.
722
+ function cisByMonth(lines, journal) {
723
+ const deducted = {};
724
+ for (const line of lines) {
725
+ if (line.sourceJournalID !== journal) continue;
726
+ if (!line[CIS_DEDUCTION_FIELD]) continue;
727
+ const month = line.postingDate.slice(0, 7);
728
+ deducted[month] = round2((deducted[month] || 0) + line[CIS_DEDUCTION_FIELD]);
729
+ }
730
+ return deducted;
731
+ }
732
+
733
+ function monthsBefore(month, count) {
734
+ const [year, index] = month.split("-").map(Number);
735
+ const shifted = index - count;
736
+ return `${year + Math.floor((shifted - 1) / 12)}-${String(((((shifted - 1) % 12) + 12) % 12) + 1).padStart(2, "0")}`;
737
+ }
738
+
739
+ function registeredTwin(lines, book) {
740
+ const twinTrade = lines.map((line) => {
741
+ if (line.sourceJournalID !== "sales" && line.sourceJournalID !== "purchases") return line;
742
+ // A capital purchase buys the same asset either way, so only the VAT is
743
+ // added to it. The tax withheld from a sub-contractor is worked out on
744
+ // the amount net of VAT, so it follows the trade and not the invoice.
745
+ const scale = line["diya-gl:assetID"] ? 1 : TWIN_TRADE_SCALE;
746
+ const traded = { ...line, amount: round2(line.amount * scale * (1 + TWIN_VAT_RATE)), taxCode: "S", taxRate: TWIN_VAT_RATE };
747
+ if (line[CIS_DEDUCTION_FIELD]) traded[CIS_DEDUCTION_FIELD] = round2(line[CIS_DEDUCTION_FIELD] * TWIN_TRADE_SCALE);
748
+ return traded;
749
+ });
750
+
751
+ const invoiced = invoicedByMonth(twinTrade, "purchases");
752
+ const withheld = cisByMonth(twinTrade, "purchases");
753
+ const sold = invoicedByMonth(twinTrade, "sales");
754
+ const suffered = cisByMonth(twinTrade, "sales");
755
+ const openingMonth = dateOnly(book.documentInfo.periodCoveredStart).slice(0, 7);
756
+
757
+ const scaled = twinTrade.map((line) => {
758
+ if (line.sourceJournalID === "bank" && line["diya-gl:bankCode"] === "DR") {
759
+ // The receipt in the year's first month settles the debtors brought
760
+ // forward, which scale with the ledger. Every later one settles the
761
+ // month before it, net of the tax a contractor customer withheld from
762
+ // those invoices -- worked out on the amount before VAT, so it does not
763
+ // scale with the invoice the way the trade does.
764
+ const month = line.postingDate.slice(0, 7);
765
+ if (month === openingMonth) return { ...line, amount: round2(line.amount * TWIN_TRADE_SCALE * (1 + TWIN_VAT_RATE)) };
766
+ const settles = monthsBefore(month, 1);
767
+ return { ...line, amount: round2((sold[settles] || 0) - (suffered[settles] || 0)) };
768
+ }
769
+ if (line.sourceJournalID === "bank" && line["diya-gl:bankCode"] === "CR") {
770
+ // The payment in the year's first month settles the creditors brought
771
+ // forward, which scale with the ledger. Every later one settles the
772
+ // month before it, net of the tax withheld from the sub-contractors
773
+ // among those invoices.
774
+ const month = line.postingDate.slice(0, 7);
775
+ if (month === openingMonth) return { ...line, amount: round2(line.amount * TWIN_TRADE_SCALE * (1 + TWIN_VAT_RATE)) };
776
+ const settles = monthsBefore(month, 1);
777
+ return { ...line, amount: round2((invoiced[settles] || 0) - (withheld[settles] || 0)) };
778
+ }
779
+ if (line.sourceJournalID === "bank" && line["diya-gl:bankCode"] === "RC") {
780
+ return { ...line, amount: withheld[monthsBefore(line.postingDate.slice(0, 7), 2)] || 0 };
781
+ }
782
+ if (line.sourceJournalID === "journal" && TWIN_SCALED_OPENING_ACCOUNTS.has(line.accountMainID)) {
783
+ return { ...line, amount: round2(line.amount * TWIN_TRADE_SCALE * (1 + TWIN_VAT_RATE)) };
784
+ }
785
+ return line;
786
+ });
787
+
788
+ // vatBroughtForward and the four settlement bank lines below are new lines
789
+ // the twin invents, not lines the master already numbers -- each needs a
790
+ // number of its own, one past the highest the master hands out, or an
791
+ // edit naming one of them can never tell it apart from openingJournal[0]
792
+ // (vatBroughtForward otherwise inherits its entryNumber by spreading it)
793
+ // or from any other unnumbered bank line.
794
+ const twinEntryNumbers = nextEntryNumbers(lines, 1 + 1 + TWIN_VAT_SETTLEMENTS.length);
795
+
796
+ const openingJournal = scaled.filter((line) => line.sourceJournalID === "journal");
797
+ const vatBroughtForward = {
798
+ ...openingJournal[0],
799
+ accountMainID: TWIN_VAT_ACCOUNT,
800
+ amount: TWIN_OPENING_VAT_DUE.amount,
801
+ lineItemComment: "VAT outstanding at the year start",
802
+ debitCreditCode: "C",
803
+ lineNumber: openingJournal.length + 1,
804
+ entryNumber: twinEntryNumbers[0],
805
+ };
806
+ const withVatDue = [...openingJournal, vatBroughtForward];
807
+ const sideTotal = (side) =>
808
+ withVatDue
809
+ .filter((line) => line.debitCreditCode === side && line.accountMainID !== TWIN_RETAINED_EARNINGS_ACCOUNT)
810
+ .reduce((total, line) => total + line.amount, 0);
811
+ const retainedEarnings = round2(sideTotal("D") - sideTotal("C"));
812
+
813
+ const twinLines = scaled.map((line) => {
814
+ if (line.sourceJournalID === "journal" && line.accountMainID === TWIN_RETAINED_EARNINGS_ACCOUNT) {
815
+ return { ...line, amount: retainedEarnings };
816
+ }
817
+ return line;
818
+ });
819
+
820
+ const settlements = [TWIN_OPENING_VAT_DUE, ...TWIN_VAT_SETTLEMENTS].map((settlement, index) =>
821
+ twinBankLine(
822
+ settlement.date,
823
+ settlement.amount,
824
+ index === 0 ? "VAT outstanding at the year start" : "Quarterly VAT payment",
825
+ `BNK-RV-${String(index + 1).padStart(3, "0")}`,
826
+ twinEntryNumbers[index + 1],
827
+ ),
828
+ );
829
+
830
+ return [...twinLines, vatBroughtForward, ...settlements].sort((a, b) =>
831
+ a.postingDate < b.postingDate ? -1 : a.postingDate > b.postingDate ? 1 : 0,
832
+ );
833
+ }
834
+
835
+ // ---------------------------------------------------------------------------
836
+ // The sole trader adaptation
837
+ // ---------------------------------------------------------------------------
838
+
839
+ // A sole trader is not his own employee and pays no corporation tax, so the
840
+ // director's payslip becomes monthly drawings and the corporation tax
841
+ // payment leaves the bank statement. The Self Employed package analyses every
842
+ // HMRC payment under one code, so the company's VAT and Construction Industry
843
+ // Scheme payments join its PAYE payments there.
844
+ const SOLE_TRADER_OPENING_BANK = 15000;
845
+ const SOLE_TRADER_MONTHLY_DRAWINGS = 1200;
846
+ const SOLE_TRADER_DRAWINGS_DAY = 25;
847
+ const SOLE_TRADER_NINO = "EF112233B";
848
+
849
+ // The next entry numbers in the master's own scheme, one past the highest it
850
+ // hands out. A line the adaptation invents still has to be addressable: an
851
+ // edit and a fix-it helper both name the line they change by its entry
852
+ // number, so a line without one can never be changed or removed.
853
+ function nextEntryNumbers(lines, count) {
854
+ let highest = 0;
855
+ for (const line of lines) {
856
+ const digits = String(line.entryNumber || "").match(/^TXN-(\d+)$/);
857
+ if (digits) highest = Math.max(highest, Number(digits[1]));
858
+ }
859
+ return Array.from({ length: count }, (unused, index) => `TXN-${String(highest + 1 + index).padStart(4, "0")}`);
860
+ }
861
+
862
+ function soleTraderAdaptation(lines, book) {
863
+ const staffOnly = withoutDirectorPayroll(lines, book);
864
+ const periodStart = dateOnly(book.documentInfo.periodCoveredStart);
865
+ const netWagesByMonth = {};
866
+ for (const line of staffOnly.filter((l) => l.sourceJournalID === "payroll")) {
867
+ const month = line.postingDate.slice(0, 7);
868
+ netWagesByMonth[month] = round2((netWagesByMonth[month] || 0) + line["diya-gl:netPay"]);
869
+ }
870
+
871
+ const adapted = [];
872
+ for (const line of staffOnly) {
873
+ if (line.sourceJournalID === "journal") continue;
874
+ if (line.sourceJournalID !== "bank") {
875
+ adapted.push(line);
876
+ continue;
877
+ }
878
+ const code = line["diya-gl:bankCode"];
879
+ if (code === "RT") continue;
880
+ if (isLtdOpeningBankLine(line, periodStart)) {
881
+ adapted.push({ ...line, amount: SOLE_TRADER_OPENING_BANK, lineItemComment: "Bank account opening balance" });
882
+ continue;
883
+ }
884
+ if (LTD_BANK_TRANSFER_CODES.has(code)) {
885
+ adapted.push(mapLtdBankCodeForSe(line, periodStart));
886
+ continue;
887
+ }
888
+ if (code === "RV" || code === "RC") {
889
+ adapted.push({ ...line, "diya-gl:bankCode": "RP" });
890
+ continue;
891
+ }
892
+ if (code === "W") {
893
+ adapted.push({ ...line, amount: netWagesByMonth[line.postingDate.slice(0, 7)] });
894
+ continue;
895
+ }
896
+ adapted.push(line);
897
+ }
898
+
899
+ const drawingsMonths = Object.keys(netWagesByMonth).sort();
900
+ const drawingsEntryNumbers = nextEntryNumbers(adapted, drawingsMonths.length);
901
+ const drawings = drawingsMonths.map((month, index) => ({
902
+ "entryNumber": drawingsEntryNumbers[index],
903
+ "sourceJournalID": "bank",
904
+ "postingDate": `${month}-${SOLE_TRADER_DRAWINGS_DAY}`,
905
+ "accountMainID": "1200",
906
+ "amount": SOLE_TRADER_MONTHLY_DRAWINGS,
907
+ "detailComment": "Proprietor",
908
+ "lineItemComment": "Drawings",
909
+ "documentType": "bank-statement",
910
+ "documentReference": `BNK-DL-${String(index + 1).padStart(3, "0")}`,
911
+ "taxCode": "OS",
912
+ "taxRate": 0,
913
+ "diya-gl:bankCode": "DL",
914
+ "debitCreditCode": "C",
915
+ "diya-gl:bankAccountID": "1200",
916
+ }));
917
+
918
+ return [...adapted, ...drawings].sort((a, b) => (a.postingDate < b.postingDate ? -1 : a.postingDate > b.postingDate ? 1 : 0));
919
+ }
920
+
921
+ // ---------------------------------------------------------------------------
922
+ // The five fixtures
923
+ // ---------------------------------------------------------------------------
924
+
925
+ const BRICKWORK_TWIN_NOTE =
926
+ "The trade scales 1.5 times against the non-VAT twin of this scenario, but both buy the same van at the same £12,000 net cost, " +
927
+ "so the £14,400 here is that same asset with VAT on it and net purchases across the pair do not scale by 1.5.";
928
+ const BRICKWORK_PLAIN_NOTE =
929
+ "The VAT twin of this scenario scales the trade 1.5 times but buys the same van at the same £12,000 net cost, " +
930
+ "so net purchases across the pair do not scale by 1.5.";
931
+ const BRICKWORK_ALLOWANCE_NOTE = "The Employment Allowance covers the employer's National Insurance, so that line is nil.";
932
+
933
+ function brickworkLedgers(vatRegistered) {
934
+ const scale = vatRegistered ? TWIN_TRADE_SCALE * (1 + TWIN_VAT_RATE) : 1;
935
+ const scaled = (entries, nameField, timing) =>
936
+ ledgerListing(entries, nameField, timing).map((entry) => ({ ...entry, amount: round2(entry.amount * scale) }));
937
+ return {
938
+ opening_debtors: scaled(brickBook.debtors, "customer", "opening"),
939
+ closing_debtors: scaled(brickBook.debtors, "customer", "closing"),
940
+ opening_creditors: scaled(brickBook.creditors, "supplier", "opening"),
941
+ closing_creditors: scaled(brickBook.creditors, "supplier", "closing"),
942
+ };
943
+ }
944
+
945
+ function brickworkLedgerTables(vatRegistered) {
946
+ const scale = vatRegistered ? TWIN_TRADE_SCALE * (1 + TWIN_VAT_RATE) : 1;
947
+ const scaled = (entries) => entries.map((entry) => ({ ...entry, amount: round2(entry.amount * scale) }));
948
+ return { debtors: scaled(brickBook.debtors), creditors: scaled(brickBook.creditors) };
949
+ }
950
+
951
+ function brickworkEntity(product, { vatRegistered, soleTrader }) {
952
+ const entity = {
953
+ "organizationIdentifier": soleTrader ? "BrickWork Pro Trading" : brickEntity.organizationIdentifier,
954
+ "organizationDescription": brickEntity.organizationDescription,
955
+ ...brickAddress,
956
+ "taxRegistrationNumber": brickEntity.taxRegistrationNumber,
957
+ "taxAuthorityIdentifier": "HMRC",
958
+ "diya-gl:product": product,
959
+ "diya-gl:vatRegistered": vatRegistered,
960
+ "diya-gl:basisOfAccounting": soleTrader ? "cash" : "accrual",
961
+ };
962
+ if (soleTrader) entity["diya-gl:nino"] = SOLE_TRADER_NINO;
963
+ else entity["diya-gl:companyNumber"] = brickEntity["diya-gl:companyNumber"];
964
+ if (vatRegistered) entity["diya-gl:vatNumber"] = TWIN_VAT_NUMBER;
965
+ entity["diya-gl:cisRegistered"] = brickEntity["diya-gl:cisRegistered"];
966
+ return entity;
967
+ }
968
+
969
+ // --- Basic Sole Trader, the trade the master books ---------------------------
970
+
971
+ const brickBstLines = filterBst(bstStaffWagesAsPurchases(withoutDirectorPayroll(brickMasterLines, brickBook)));
972
+ const brickBstFigures = bstExpectedFigures(brickBstLines, brickBook.stock);
973
+ const brickBstAdditions = fixedAssetAdditions(brickBstLines, BST_PURCHASE_CODE_MAP, "f");
974
+ const brickBstEntity = brickworkEntity("BasicSoleTrader", { vatRegistered: false, soleTrader: true });
975
+ const brickBstLedgers = brickworkLedgers(false);
976
+ const brickBstOpeningLedger = bstOpeningBalances(brickBstLedgers.opening_debtors, brickBstLedgers.opening_creditors);
977
+
978
+ const brickBstToml = formatScenarioToml(
979
+ {
980
+ name: "BrickWork Pro BST",
981
+ description:
982
+ "Construction sole trader under the VAT registration threshold, on the Basic Sole Trader package. Sub-contract labour is bought in as a direct cost, the labourer's wage is an employee cost, and there is no bank journal. " +
983
+ BRICKWORK_PLAIN_NOTE,
984
+ product: "bst",
985
+ tax_regime: "se",
986
+ vat_registered: false,
987
+ business: businessBlock(brickBstEntity),
988
+ },
989
+ buildGrouped(brickBstLines, BST_PURCHASE_CODE_MAP, {
990
+ carriesCisDeductions: false,
991
+ carriesPaymentLabels: true,
992
+ carriesSourceFields: true,
993
+ carriesMileage: "claims",
994
+ }),
995
+ {
996
+ ...brickBstFigures,
997
+ ...bstOpeningBalanceBlock(brickBstOpeningLedger),
998
+ fixed_asset_additions: brickBstAdditions,
999
+ },
1000
+ );
1001
+
1002
+ writeFixture("bst-brickwork-pro-nonvat", brickBstToml);
1003
+ const brickBstDiya = writeSubset(
1004
+ BRICKWORK_DIR,
1005
+ "bst-nonvat",
1006
+ brickBook,
1007
+ {
1008
+ entity: brickBstEntity,
1009
+ taxSections: ["incomeTax", "nationalInsurance", "capitalAllowances", "mileage"],
1010
+ accountFilter: bstAccountFilter,
1011
+ tables: {
1012
+ stock: brickBook.stock,
1013
+ openingBalances: brickBstOpeningLedger,
1014
+ ...brickworkLedgerTables(false),
1015
+ fixedAssets: brickBook.fixedAssets,
1016
+ },
1017
+ },
1018
+ brickBstLines,
1019
+ );
1020
+
1021
+ // --- Self Employed, both sizes ----------------------------------------------
1022
+
1023
+ function writeBrickworkSe(vatRegistered) {
1024
+ const masterLines = vatRegistered ? registeredTwin(brickMasterLines, brickBook) : brickMasterLines;
1025
+ const lines = filterAdvanced(soleTraderAdaptation(masterLines, brickBook));
1026
+ const salesLines = lines.filter((line) => line.sourceJournalID === "sales");
1027
+ const byCode = totalsByCode(lines, SE_PURCHASE_CODE_MAP);
1028
+ const vatDivisor = 1 + (vatRegistered ? TWIN_VAT_RATE : 0);
1029
+ const grouped = buildGrouped(lines, SE_PURCHASE_CODE_MAP, { carriesSourceFields: true, carriesMileage: "claims" });
1030
+ grouped.payroll = buildPayroll(lines, { carriesSourceFields: true, employees: brickBook.employees });
1031
+ const entity = brickworkEntity("SelfEmployed", { vatRegistered, soleTrader: true });
1032
+ const employees = brickworkEmployees(brickBook.employees.filter((employee) => !employee.isDirector));
1033
+
1034
+ const expected = {
1035
+ total_sales: computeNetSales(salesLines),
1036
+ ...brickworkLedgers(vatRegistered),
1037
+ opening_stock: brickBook.stock.openingValue,
1038
+ closing_stock: brickBook.stock.closingValue,
1039
+ };
1040
+ if (byCode.v) expected.total_motor_net = Math.round(byCode.v / vatDivisor);
1041
+ if (byCode.l) expected.total_legal_net = Math.round(byCode.l / vatDivisor);
1042
+
1043
+ const toml = formatScenarioToml(
1044
+ {
1045
+ name: `BrickWork Pro SE ${vatRegistered ? "VAT" : "non-VAT"}`,
1046
+ description:
1047
+ "Construction sole trader, CIS sub-contractors, one labourer on the payroll. " +
1048
+ (vatRegistered
1049
+ ? `Turnover is over the VAT registration threshold, which is why the business is registered. Journal amounts include VAT at 20%. ${BRICKWORK_TWIN_NOTE}`
1050
+ : `Turnover is under the VAT registration threshold. Journal amounts carry no VAT. ${BRICKWORK_PLAIN_NOTE}`) +
1051
+ ` ${BRICKWORK_ALLOWANCE_NOTE}`,
1052
+ product: "se",
1053
+ tax_regime: "se",
1054
+ vat_registered: vatRegistered,
1055
+ business: businessBlock(entity, { vat_number: entity["diya-gl:vatNumber"], nino: SOLE_TRADER_NINO }),
1056
+ employees,
1057
+ },
1058
+ grouped,
1059
+ expected,
1060
+ );
1061
+
1062
+ writeFixture(`se-brickwork-pro-${vatRegistered ? "vat" : "nonvat"}`, toml);
1063
+ return writeSubset(
1064
+ BRICKWORK_DIR,
1065
+ `se-${vatRegistered ? "vat" : "nonvat"}`,
1066
+ brickBook,
1067
+ {
1068
+ entity,
1069
+ taxSections: ["incomeTax", "nationalInsurance", "vat", "capitalAllowances", "mileage"],
1070
+ accountFilter: seAccountFilter,
1071
+ employees,
1072
+ tables: {
1073
+ stock: brickBook.stock,
1074
+ ...brickworkLedgerTables(vatRegistered),
1075
+ fixedAssets: brickBook.fixedAssets,
1076
+ },
1077
+ },
1078
+ lines,
1079
+ );
1080
+ }
1081
+
1082
+ const brickSeNonVatDiya = writeBrickworkSe(false);
1083
+ const brickSeVatDiya = writeBrickworkSe(true);
1084
+
1085
+ // --- Company, both sizes ----------------------------------------------------
1086
+
1087
+ function writeBrickworkLtd(vatRegistered) {
1088
+ const lines = filterFull(vatRegistered ? registeredTwin(brickMasterLines, brickBook) : brickMasterLines);
1089
+ const salesLines = lines.filter((line) => line.sourceJournalID === "sales");
1090
+ const purchaseLines = lines.filter((line) => line.sourceJournalID === "purchases");
1091
+ const byCode = totalsByCode(lines, LTD_PURCHASE_CODE_MAP);
1092
+ const vatRate = vatRegistered ? TWIN_VAT_RATE : 0;
1093
+ const vatDivisor = 1 + vatRate;
1094
+ const grouped = buildGrouped(lines, LTD_PURCHASE_CODE_MAP, { carriesSourceFields: true });
1095
+ grouped.payroll = buildPayroll(lines, { carriesSourceFields: true, employees: brickBook.employees });
1096
+ const openingBalance = buildOpeningBalance(lines);
1097
+ const entity = brickworkEntity("Company", { vatRegistered, soleTrader: false });
1098
+ const employees = brickworkEmployees(brickBook.employees);
1099
+ const members = brickBook.members.map((member) => ({
1100
+ name: member.name,
1101
+ shares: member.shares,
1102
+ acquired: dateOnly(member.acquiredDate),
1103
+ }));
1104
+
1105
+ const sharesIssued = members.reduce((total, member) => total + member.shares, 0);
1106
+ if (sharesIssued !== openingBalance.share_capital) {
1107
+ throw new Error(
1108
+ `Register of members holds ${sharesIssued} shares at 1 each, against share capital of ${openingBalance.share_capital} on the opening balance sheet`,
1109
+ );
1110
+ }
1111
+
1112
+ const expected = {
1113
+ total_sales: computeNetSales(salesLines),
1114
+ opening_balance: openingBalance,
1115
+ ...brickworkLedgers(vatRegistered),
1116
+ opening_stock: brickBook.stock.openingValue,
1117
+ closing_stock: brickBook.stock.closingValue,
1118
+ // Nothing in this book's VAT periods falls outside the accounting year,
1119
+ // so the return's boxes are the year's own journals and nothing else.
1120
+ vat_output_total: Math.round(salesLines.reduce((total, line) => total + VAT_ON(line.amount, line.taxRate || 0), 0)),
1121
+ vat_input_total: Math.round(purchaseLines.reduce((total, line) => total + VAT_ON(line.amount, line.taxRate || 0), 0)),
1122
+ };
1123
+ if (byCode.r) expected.total_premises_net = Math.round(byCode.r / vatDivisor);
1124
+ if (byCode.l) expected.total_legal_net = Math.round(byCode.l / vatDivisor);
1125
+
1126
+ const toml = formatScenarioToml(
1127
+ {
1128
+ name: `BrickWork Pro Ltd ${vatRegistered ? "VAT" : "non-VAT"}`,
1129
+ description:
1130
+ "Construction company, CIS sub-contractors, a director and one labourer on the payroll. " +
1131
+ (vatRegistered
1132
+ ? `Turnover is over the VAT registration threshold, which is why the business is registered. Journal amounts include VAT at 20%. ${BRICKWORK_TWIN_NOTE}`
1133
+ : `Turnover is under the VAT registration threshold. Journal amounts carry no VAT. ${BRICKWORK_PLAIN_NOTE}`) +
1134
+ ` ${BRICKWORK_ALLOWANCE_NOTE}`,
1135
+ product: "ltd",
1136
+ tax_regime: "ltd",
1137
+ vat_registered: vatRegistered,
1138
+ business: businessBlock(entity, { company_number: entity["diya-gl:companyNumber"], vat_number: entity["diya-gl:vatNumber"] }),
1139
+ employees,
1140
+ members,
1141
+ },
1142
+ grouped,
1143
+ expected,
1144
+ );
1145
+
1146
+ writeFixture(`ltd-brickwork-pro-${vatRegistered ? "vat" : "nonvat"}`, toml);
1147
+ return writeSubset(
1148
+ BRICKWORK_DIR,
1149
+ `ltd-${vatRegistered ? "vat" : "nonvat"}`,
1150
+ brickBook,
1151
+ {
1152
+ entity,
1153
+ taxSections: ["corporationTax", "capitalAllowances", "vat", "nationalInsurance", "mileage", "incomeTax"],
1154
+ accountFilter: fullAccountFilter,
1155
+ directors: brickBook.directors,
1156
+ employees,
1157
+ tables: {
1158
+ openingBalances: toV2OpeningBalances(openingBalance),
1159
+ stock: brickBook.stock,
1160
+ ...brickworkLedgerTables(vatRegistered),
1161
+ fixedAssets: brickBook.fixedAssets,
1162
+ members: brickBook.members,
1163
+ },
1164
+ },
1165
+ lines,
1166
+ );
1167
+ }
1168
+
1169
+ const brickLtdNonVatDiya = writeBrickworkLtd(false);
1170
+ const brickLtdVatDiya = writeBrickworkLtd(true);
1171
+
1172
+ // ============================================================================
1173
+ // The Taxi Driver books — SP Sixty Driving, Kestrel Executive Cars and the
1174
+ // basic owner-driver
1175
+ // ============================================================================
1176
+
1177
+ const TAXI_TAX_SECTIONS = ["incomeTax", "nationalInsurance", "capitalAllowances", "mileage"];
1178
+
1179
+ // A taxi book is all takings and running costs, so the whole master reaches
1180
+ // the fixture. The Sales sheet takes the day's gross takings against a
1181
+ // pre-filled date, and a purchase coded to the capital column is registered
1182
+ // on the Fixed Assets schedule as well, which is where it earns its
1183
+ // allowance.
1184
+ function writeTaxiScenario(master, { fixtureName, subsetName, name, description }) {
1185
+ const { dir, book, lines } = master;
1186
+ assertPurchaseCodesCoverChart(book, TAXI_PURCHASE_CODE_MAP, "TAXI_PURCHASE_CODE_MAP");
1187
+
1188
+ const grouped = takingsOnlySales(
1189
+ buildGrouped(lines, TAXI_PURCHASE_CODE_MAP, { carriesCisDeductions: false, carriesSourceFields: true, carriesMileage: "all" }),
1190
+ );
1191
+ const additions = fixedAssetAdditions(lines, TAXI_PURCHASE_CODE_MAP, "f");
1192
+ const entity = book.entityInformation;
1193
+
1194
+ const toml = formatScenarioToml(
1195
+ {
1196
+ name,
1197
+ description,
1198
+ product: "taxi",
1199
+ tax_regime: "se",
1200
+ vat_registered: entity["diya-gl:vatRegistered"],
1201
+ business: businessBlock(entity),
1202
+ },
1203
+ grouped,
1204
+ {
1205
+ ...taxiExpectedFigures(lines, book.documentInfo.periodCoveredStart),
1206
+ fixed_asset_additions: additions,
1207
+ },
1208
+ );
1209
+
1210
+ writeFixture(fixtureName, toml);
1211
+ return writeSubset(
1212
+ dir,
1213
+ subsetName,
1214
+ book,
1215
+ { entity, taxSections: TAXI_TAX_SECTIONS, accountFilter: fullAccountFilter, tables: { fixedAssets: book.fixedAssets } },
1216
+ lines,
1217
+ );
1218
+ }
1219
+
1220
+ const spSixty = readMaster("sp-sixty-driving");
1221
+ const kestrel = readMaster("kestrel-executive-cars");
1222
+ const basicTaxi = readMaster("basic-taxi-driver");
1223
+ const autumnStart = readMaster("autumn-start-cabs");
1224
+
1225
+ const spSixtyTaxiDiya = writeTaxiScenario(spSixty, {
1226
+ fixtureName: "taxi-scenario-sp-sixty",
1227
+ subsetName: "taxi",
1228
+ name: "SP Sixty Driving",
1229
+ description: "Private hire driver with varying daily fares, fuel, insurance, repairs, admin, licence, accountant, dashcam, and signage",
1230
+ });
1231
+
1232
+ const kestrelDiya = writeTaxiScenario(kestrel, {
1233
+ fixtureName: "taxi-scenario-kestrel",
1234
+ subsetName: "taxi",
1235
+ name: "Kestrel Executive Cars",
1236
+ description:
1237
+ "Executive chauffeur operator banking weekly settlements, with employed drivers, a leased yard and a profit into the additional rate band",
1238
+ });
1239
+
1240
+ const basicTaxiDiya = writeTaxiScenario(basicTaxi, {
1241
+ fixtureName: "taxi-scenario-basic",
1242
+ subsetName: "taxi",
1243
+ name: "Basic taxi driver",
1244
+ description:
1245
+ "Owner-driver taxi with steady daily fares, fuel, road tax and insurance, and a vehicle purchase. Owns the vehicle, so no car hire or rental.",
1246
+ });
1247
+
1248
+ const autumnStartDiya = writeTaxiScenario(autumnStart, {
1249
+ fixtureName: "taxi-scenario-autumn-start",
1250
+ subsetName: "taxi",
1251
+ name: "Autumn Start Cabs",
1252
+ description: "Owner-driver who started trading in October, so the year's takings and costs sit in the last six month tabs",
1253
+ });
1254
+
1255
+ // ---------------------------------------------------------------------------
1256
+ // SP Sixty Driving on the Basic Sole Trader package
1257
+ // ---------------------------------------------------------------------------
1258
+
1259
+ // The Basic Sole Trader sales sheet keeps one row a line, which a year of
1260
+ // daily fares does not fit, so the takings reach it as the monthly banking
1261
+ // the driver actually pays in. The purchase columns are the sole trader's
1262
+ // fourteen, not the taxi trade's, so the same accounts read under a chart of
1263
+ // their own.
1264
+ assertPurchaseCodesCoverChart(spSixty.book, TAXI_BST_PURCHASE_CODE_MAP, "TAXI_BST_PURCHASE_CODE_MAP");
1265
+
1266
+ const spSixtyBstGrouped = buildGrouped(spSixty.lines, TAXI_BST_PURCHASE_CODE_MAP, {
1267
+ carriesCisDeductions: false,
1268
+ carriesPaymentLabels: true,
1269
+ carriesSourceFields: true,
1270
+ carriesMileage: "claims",
1271
+ });
1272
+ const spSixtySalesLines = spSixty.lines.filter((line) => line.sourceJournalID === "sales");
1273
+ spSixtyBstGrouped.sales = {};
1274
+ for (const banking of monthlySalesTotals(spSixtySalesLines)) {
1275
+ const month = getMonthKey(banking.date);
1276
+ spSixtyBstGrouped.sales[month] = [
1277
+ { date: banking.date, customer: spSixtySalesLines[0].detailComment, payment: "Bank", amount: banking.amount },
1278
+ ];
1279
+ }
1280
+
1281
+ const spSixtyBstEntity = { ...spSixty.book.entityInformation, "diya-gl:product": "BasicSoleTrader" };
1282
+ const spSixtyBstAdditions = fixedAssetAdditions(spSixty.lines, TAXI_BST_PURCHASE_CODE_MAP, "f");
1283
+
1284
+ const spSixtyBstToml = formatScenarioToml(
1285
+ {
1286
+ name: "SP Sixty Driving BST",
1287
+ description: "Private hire driver adapted for BST package. Motoring as actual costs, bar the March month claimed on mileage.",
1288
+ product: "bst",
1289
+ tax_regime: "se",
1290
+ vat_registered: false,
1291
+ business: businessBlock(spSixtyBstEntity),
1292
+ },
1293
+ spSixtyBstGrouped,
1294
+ {
1295
+ ...bstExpectedFigures(spSixty.lines, spSixty.book.stock, TAXI_BST_PURCHASE_CODE_MAP),
1296
+ fixed_asset_additions: spSixtyBstAdditions,
1297
+ },
1298
+ );
1299
+
1300
+ writeFixture("bst-sp-sixty", spSixtyBstToml);
1301
+ const spSixtyBstDiya = writeSubset(
1302
+ spSixty.dir,
1303
+ "bst",
1304
+ spSixty.book,
1305
+ {
1306
+ entity: spSixtyBstEntity,
1307
+ taxSections: TAXI_TAX_SECTIONS,
1308
+ accountFilter: fullAccountFilter,
1309
+ tables: { fixedAssets: spSixty.book.fixedAssets },
1310
+ },
1311
+ spSixty.lines,
1312
+ );
1313
+
1314
+ // ============================================================================
1315
+ // Summary
1316
+ // ============================================================================
1317
+
1318
+ const subsetLines = [
1319
+ ["precision-code-ltd/bst", bstDiya],
1320
+ ["precision-code-ltd/advanced", advDiya],
1321
+ ["precision-code-ltd/full", fullDiya],
1322
+ ["brickwork-pro/bst-nonvat", brickBstDiya],
1323
+ ["brickwork-pro/se-nonvat", brickSeNonVatDiya],
1324
+ ["brickwork-pro/se-vat", brickSeVatDiya],
1325
+ ["brickwork-pro/ltd-nonvat", brickLtdNonVatDiya],
1326
+ ["brickwork-pro/ltd-vat", brickLtdVatDiya],
1327
+ ["sp-sixty-driving/bst", spSixtyBstDiya],
1328
+ ["sp-sixty-driving/taxi", spSixtyTaxiDiya],
1329
+ ["kestrel-executive-cars/taxi", kestrelDiya],
1330
+ ["basic-taxi-driver/taxi", basicTaxiDiya],
1331
+ ["autumn-start-cabs/taxi", autumnStartDiya],
1332
+ ];
1333
+
1334
+ console.log(`Extracted ${extracted.length} fixtures and ${subsetLines.length} diya-gl subsets`);
1335
+ console.log("");
1336
+ for (const fixture of extracted) {
1337
+ const journals = [
1338
+ `${fixture.sales} sales`,
1339
+ `${fixture.purchases} purchases`,
1340
+ fixture.bank ? `${fixture.bank} bank` : null,
1341
+ fixture.payroll ? `${fixture.payroll} payroll` : null,
1342
+ ].filter(Boolean);
1343
+ console.log(` ${fixture.name.padEnd(30)} ${journals.join(", ")}`);
1344
+ }
1345
+ console.log("");
1346
+ for (const [subset, counts] of subsetLines) {
1347
+ console.log(` ${subset.padEnd(30)} ${counts.dataLines} lines`);
1348
+ }