@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,144 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // corporation-tax.js — UK Corporation Tax calculation.
5
+
6
+ /**
7
+ * Calculate corporation tax with marginal relief.
8
+ *
9
+ * The upper limit arrives as main_rate_limit in the ltd-<year>.toml rate
10
+ * tables and as small_profits_limit_upper from callers that build the rates
11
+ * by hand, so both names are read. The relief fraction is taken as it comes:
12
+ * the financial years before 2023 carry a zero fraction and a zero upper
13
+ * limit because there was one rate and no relief, and defaulting either of
14
+ * those away invents a relief those years never had.
15
+ *
16
+ * @param {number} profit - profit chargeable to CT
17
+ * @param {Object} ctRates - { small_profits_rate, main_rate, small_profits_limit, main_rate_limit, marginal_relief_fraction }
18
+ * @returns {{ profitChargeable, smallProfitsRate, mainRate, corporationTax, marginalRelief }}
19
+ */
20
+ export function calculateCorporationTax(profit, ctRates) {
21
+ const spr = ctRates.small_profits_rate;
22
+ const mr = ctRates.main_rate;
23
+ const spl = ctRates.small_profits_limit;
24
+ const splu = ctRates.main_rate_limit ?? ctRates.small_profits_limit_upper ?? 250000;
25
+ const mrf = ctRates.marginal_relief_fraction ?? 0.015;
26
+
27
+ if (profit <= 0) {
28
+ return { profitChargeable: profit, smallProfitsRate: spr, mainRate: mr, corporationTax: 0, marginalRelief: 0 };
29
+ }
30
+
31
+ if (profit <= spl) {
32
+ // Small profits rate
33
+ return { profitChargeable: profit, smallProfitsRate: spr, mainRate: mr, corporationTax: profit * spr, marginalRelief: 0 };
34
+ }
35
+
36
+ if (profit > splu) {
37
+ // Main rate
38
+ return { profitChargeable: profit, smallProfitsRate: spr, mainRate: mr, corporationTax: profit * mr, marginalRelief: 0 };
39
+ }
40
+
41
+ // Marginal relief band
42
+ const mainTax = profit * mr;
43
+ const relief = (splu - profit) * mrf;
44
+ const corporationTax = mainTax - relief;
45
+
46
+ return { profitChargeable: profit, smallProfitsRate: spr, mainRate: mr, corporationTax, marginalRelief: relief };
47
+ }
48
+
49
+ /**
50
+ * The financial years an accounting period falls across.
51
+ *
52
+ * A UK financial year runs from 1 April, and it is named for the calendar
53
+ * year it starts in. A period can span at most two of them, and the second
54
+ * one is empty whenever the period ends on or before the first one does.
55
+ *
56
+ * @param {Date} periodStart
57
+ * @param {Date} periodEnd
58
+ * @returns {{ years: Array<{ year: number, start: Date, end: Date, days: number }>, totalDays: number }}
59
+ */
60
+ export function financialYearsInPeriod(periodStart, periodEnd) {
61
+ const firstYearEnd = financialYearEndOnOrAfter(periodStart);
62
+ const firstEnd = firstYearEnd.getTime() < periodEnd.getTime() ? firstYearEnd : periodEnd;
63
+ const secondStart = addDays(firstEnd, 1);
64
+
65
+ const first = {
66
+ year: financialYearNumber(periodStart),
67
+ start: periodStart,
68
+ end: firstEnd,
69
+ days: dayCount(periodStart, firstEnd),
70
+ };
71
+ const second = {
72
+ year: financialYearNumber(secondStart),
73
+ start: secondStart,
74
+ end: periodEnd,
75
+ days: Math.max(0, dayCount(secondStart, periodEnd)),
76
+ };
77
+ return { years: [first, second], totalDays: dayCount(periodStart, periodEnd) };
78
+ }
79
+
80
+ /**
81
+ * Corporation tax charged financial year by financial year, the way the
82
+ * working sheet charges it: the chargeable profit is split across the two
83
+ * years by day count, each share meets its own year's rate, and marginal
84
+ * relief applies to a share that sits between the two limits, with both
85
+ * limits apportioned by the same day count.
86
+ *
87
+ * @param {number} profitChargeable
88
+ * @param {Array<{ year: number, days: number }>} financialYears - two entries, the second possibly nil
89
+ * @param {number} totalDays
90
+ * @param {Object} rates
91
+ * @param {number[]} rates.smallProfitsRatePercent - one whole-number rate per financial year
92
+ * @param {number} rates.mainRatePercent
93
+ * @param {number} rates.marginalReliefFraction
94
+ * @param {number} rates.lowerLimit
95
+ * @param {number} rates.upperLimit
96
+ * @returns {{ rows: Array<{ year, days, profitShare, ratePercent, taxBeforeRelief, marginalRelief, tax }>, tax: number, marginalRelief: number, taxBeforeRelief: number }}
97
+ */
98
+ export function apportionCorporationTax(profitChargeable, financialYears, totalDays, rates) {
99
+ const rows = financialYears.map((financialYear, index) => {
100
+ const share = totalDays > 0 ? financialYear.days / totalDays : 0;
101
+ const profitShare = profitChargeable > 0 ? profitChargeable * share : 0;
102
+ const lowerLimit = rates.lowerLimit * share;
103
+ const upperLimit = rates.upperLimit * share;
104
+ const ratePercent = profitShare <= lowerLimit ? rates.smallProfitsRatePercent[index] : rates.mainRatePercent;
105
+ const taxBeforeRelief = (profitShare * ratePercent) / 100;
106
+ const marginalRelief =
107
+ profitShare > lowerLimit && profitShare < upperLimit ? (upperLimit - profitShare) * rates.marginalReliefFraction : 0;
108
+ return {
109
+ year: financialYear.year,
110
+ days: financialYear.days,
111
+ profitShare,
112
+ ratePercent,
113
+ taxBeforeRelief,
114
+ marginalRelief,
115
+ tax: taxBeforeRelief - marginalRelief,
116
+ };
117
+ });
118
+
119
+ return {
120
+ rows,
121
+ taxBeforeRelief: rows.reduce((total, row) => total + row.taxBeforeRelief, 0),
122
+ marginalRelief: rows.reduce((total, row) => total + row.marginalRelief, 0),
123
+ tax: rows.reduce((total, row) => total + row.tax, 0),
124
+ };
125
+ }
126
+
127
+ const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
128
+
129
+ function financialYearEndOnOrAfter(date) {
130
+ const sameYear = new Date(Date.UTC(date.getUTCFullYear(), 2, 31));
131
+ return sameYear.getTime() >= date.getTime() ? sameYear : new Date(Date.UTC(date.getUTCFullYear() + 1, 2, 31));
132
+ }
133
+
134
+ function financialYearNumber(date) {
135
+ return date.getUTCFullYear() - (date.getUTCMonth() < 3 ? 1 : 0);
136
+ }
137
+
138
+ function addDays(date, days) {
139
+ return new Date(date.getTime() + days * MILLISECONDS_PER_DAY);
140
+ }
141
+
142
+ function dayCount(start, end) {
143
+ return Math.round((end.getTime() - start.getTime()) / MILLISECONDS_PER_DAY) + 1;
144
+ }
@@ -0,0 +1,122 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // income-tax.js — UK income tax calculation for self-employed individuals.
5
+
6
+ /**
7
+ * Calculate income tax from profit and tax rates.
8
+ *
9
+ * The personal allowance falls by one pound for every two pounds of income
10
+ * above the taper threshold (ITA 2007 s35). That divisor has not moved since
11
+ * 2010, so it sits in the formula rather than in the tax data.
12
+ *
13
+ * @param {number} profit - taxable profit before personal allowance
14
+ * @param {Object} taxRates - { personal_allowance, personal_allowance_taper_threshold, basic_band_end,
15
+ * higher_band_end, basic_rate, higher_rate, additional_rate }
16
+ * @returns {{ personalAllowance, taxableIncome, basicRateTax, higherRateTax, additionalRateTax, totalIncomeTax }}
17
+ */
18
+ export function calculateIncomeTax(profit, taxRates) {
19
+ const withdrawn = Math.max(0, profit - taxRates.personal_allowance_taper_threshold) / 2;
20
+ const pa = Math.max(0, taxRates.personal_allowance - withdrawn);
21
+ const taxableIncome = Math.max(0, profit - pa);
22
+ const basicBandEnd = taxRates.basic_band_end;
23
+ const higherBandEnd = taxRates.higher_band_end;
24
+ const basicRateTax = Math.min(taxableIncome, basicBandEnd) * taxRates.basic_rate;
25
+ const higherRateTax = Math.max(0, Math.min(taxableIncome, higherBandEnd) - basicBandEnd) * taxRates.higher_rate;
26
+ const additionalRateTax = Math.max(0, taxableIncome - higherBandEnd) * taxRates.additional_rate;
27
+ const totalIncomeTax = basicRateTax + higherRateTax + additionalRateTax;
28
+
29
+ return {
30
+ personalAllowance: pa,
31
+ taxableIncome,
32
+ basicRateTax,
33
+ higherRateTax,
34
+ additionalRateTax,
35
+ totalIncomeTax,
36
+ };
37
+ }
38
+
39
+ // Half up to the penny, for the voluntary Class 2 figure below.
40
+ function round2(value) {
41
+ return Math.round(value * 100) / 100;
42
+ }
43
+
44
+ /**
45
+ * Backward-compatible wrapper matching reconcile.js calculateExpectedTax signature.
46
+ * Computes income tax + NI Class 4 from profit and full tax data.
47
+ * @param {number} profit - taxable profit
48
+ * @param {Object} taxData - full tax data object (from app/data/*.toml)
49
+ * @returns {{ income_tax, personal_allowance, income_tax_basic, income_tax_higher, income_tax_additional,
50
+ * ni_class4_lower, ni_class4_upper, total_tax_and_ni, ni_class2_weekly, ni_class2_threshold, ni_class2 }}
51
+ */
52
+ export function calculateExpectedTax(profit, taxData) {
53
+ const { totalIncomeTax, personalAllowance, basicRateTax, higherRateTax, additionalRateTax } = calculateIncomeTax(
54
+ profit,
55
+ taxData.income_tax,
56
+ );
57
+
58
+ const lowerLimit = taxData.national_insurance.class4_lower_limit;
59
+ const upperLimit = taxData.national_insurance.class4_upper_limit;
60
+ const lowerRate = taxData.national_insurance.class4_lower_rate;
61
+ const upperRate = taxData.national_insurance.class4_upper_rate;
62
+ const niLower = profit > lowerLimit ? (Math.min(profit, upperLimit) - lowerLimit) * lowerRate : 0;
63
+ const niUpper = profit > upperLimit ? (profit - upperLimit) * upperRate : 0;
64
+
65
+ // Class 2 is voluntary below the small profits threshold (a customer may
66
+ // choose to pay it to protect their state pension record) and nil above
67
+ // it, where the NI record is credited without payment.
68
+ const class2Weekly = taxData.national_insurance.class2_weekly_rate;
69
+ const class2Threshold = taxData.national_insurance.class2_small_profits_threshold;
70
+
71
+ // income_tax, ni_class4_lower, ni_class4_upper and total_tax_and_ni carry
72
+ // no rounding of their own, matching the Income Tax sheet: E11 (BST/SE) /
73
+ // E11 (Taxi) is SUM(E8:E10) and the total (E18 BST/SE, E17 Taxi) is
74
+ // SUM(E11:E17) with every intermediate row a plain formula -- the sheet
75
+ // never rounds this chain, so the JS mirror does not either.
76
+ return {
77
+ income_tax: totalIncomeTax,
78
+ personal_allowance: personalAllowance,
79
+ income_tax_basic: basicRateTax,
80
+ income_tax_higher: higherRateTax,
81
+ income_tax_additional: additionalRateTax,
82
+ ni_class4_lower: niLower,
83
+ ni_class4_upper: niUpper,
84
+ total_tax_and_ni: totalIncomeTax + niLower + niUpper,
85
+ ni_class2_weekly: class2Weekly,
86
+ ni_class2_threshold: class2Threshold,
87
+ ni_class2: profit < class2Threshold ? round2(class2Weekly * 52) : 0,
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Runs the six checks the SE Profit Forecast and Taxi Wages Forecast sheets
93
+ * share: personal allowance after taper, tax at each of the three income
94
+ * tax rates, Class 4 National Insurance, and the total liability. Read
95
+ * against both templates' own formulas (Profit Forecast C40-C46, Wages
96
+ * Forecast C35-C41), neither carries a ROUND() anywhere in this chain --
97
+ * every intermediate cell is a plain arithmetic or IF formula over the
98
+ * Admin sheet's own rate cells, the same rates calculateExpectedTax takes.
99
+ * So every comparison here runs to the penny: a wider tolerance would only
100
+ * hide a genuine mismatch between the sheet's formula and this mirror.
101
+ *
102
+ * Both templates also floor the personal allowance at nil when the
103
+ * forecast has no taxable profit (C39/C34 <= 0), rather than showing the
104
+ * taper's full, unclamped allowance -- calculateExpectedTax has no such
105
+ * floor, so the comparison applies it here.
106
+ *
107
+ * @param {function} check - (name, actual, expected, tolerance) => void, the caller's own check()
108
+ * @param {number} forecastProfit - the sheet's own taxable profit cell (Profit Forecast C39 / Wages Forecast C34)
109
+ * @param {{personalAllowance: number, standard: number, higher: number, additional: number, ni: number, total: number}} cells
110
+ * - the sheet's own personal allowance, tax-at-rate, NI and total cells
111
+ * @param {Object} taxData
112
+ * @param {function} calculateExpectedTax
113
+ */
114
+ export function checkForecastTaxAndNi(check, forecastProfit, cells, taxData, calculateExpectedTax) {
115
+ const expected = calculateExpectedTax(forecastProfit, taxData);
116
+ check("Forecast: personal allowance after taper", cells.personalAllowance, forecastProfit <= 0 ? 0 : expected.personal_allowance, 0.01);
117
+ check("Forecast: tax at standard rate", cells.standard, expected.income_tax_basic, 0.01);
118
+ check("Forecast: tax at higher rate", cells.higher, expected.income_tax_higher, 0.01);
119
+ check("Forecast: tax at additional rate", cells.additional, expected.income_tax_additional, 0.01);
120
+ check("Forecast: National Insurance", cells.ni, expected.ni_class4_lower + expected.ni_class4_upper, 0.01);
121
+ check("Forecast: tax and NI liability", cells.total, expected.total_tax_and_ni, 0.01);
122
+ }
@@ -0,0 +1,69 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // mileage.js — the HMRC approved mileage allowance, shared by the Basic
5
+ // Sole Trader and Taxi Driver engines.
6
+
7
+ // HMRC's approved mileage rate for a car: 45p to the first 10,000 business
8
+ // miles in the tax year, 25p beyond. It has held since 2011/12 and matches
9
+ // every tax year this app's own data files carry (app/data/*.toml). A figure
10
+ // worked out from it ahead of any one tax year's data -- an expected value at
11
+ // fixture-extraction time, say -- does not go stale the way a rate that does
12
+ // change year to year would.
13
+ export const HMRC_CAR_MILEAGE_RATES = { higher_rate_limit: 10000, higher_rate_pence: 0.45, lower_rate_pence: 0.25 };
14
+
15
+ /**
16
+ * The allowance a year's business miles claim: the first band of miles at
17
+ * the higher rate, the rest at the lower one.
18
+ *
19
+ * The packages band it a month at a time off a running mileage total (BST:
20
+ * PurchasesApr!G4 = IF(C1<Admin!F22, C1*Admin!G21, C1*G21-(C1-F21)*(G21-G22)),
21
+ * each later month subtracting what the months before it already claimed;
22
+ * Taxi: the same shape at PurchasesApr!U4 off its own A1). Month by month
23
+ * those subtractions telescope, so the year's total is this one calculation.
24
+ *
25
+ * @param {number} totalMiles - business miles for the year
26
+ * @param {Object} mileageRates - the tax year's [mileage] table
27
+ * @returns {number} the allowance claimed
28
+ */
29
+ export function calculateMileageAllowance(totalMiles, mileageRates) {
30
+ const higherBandMiles = Math.min(totalMiles, mileageRates.higher_rate_limit);
31
+ const lowerBandMiles = Math.max(0, totalMiles - mileageRates.higher_rate_limit);
32
+ return higherBandMiles * mileageRates.higher_rate_pence + lowerBandMiles * mileageRates.lower_rate_pence;
33
+ }
34
+
35
+ /**
36
+ * Business miles a journal's lines carry. A line records them as a measurable
37
+ * quantity in miles beside the money it moves — a taxi day's fares carry the
38
+ * miles driven to earn them, a purchase carries the miles the journey to make
39
+ * it took.
40
+ *
41
+ * @param {Array} lines - journal lines
42
+ * @returns {number} total miles
43
+ */
44
+ export function totalBusinessMiles(lines) {
45
+ return lines
46
+ .filter((line) => line.measurableUnitOfMeasure === "miles" && typeof line.measurableQuantity === "number")
47
+ .reduce((sum, line) => sum + line.measurableQuantity, 0);
48
+ }
49
+
50
+ /**
51
+ * Business miles a scenario's own sales and purchase rows carry. This is what
52
+ * cellWrites puts on the sheets' mileage columns, so it is what the recalculated
53
+ * package's allowance is worked out from.
54
+ *
55
+ * @param {Object} scenario - a loaded scenario (or a merged scenario/expected)
56
+ * @returns {number} total miles
57
+ */
58
+ export function scenarioBusinessMiles(scenario) {
59
+ let miles = 0;
60
+ for (const table of [scenario.sales, scenario.purchases]) {
61
+ if (!table) continue;
62
+ for (const transactions of Object.values(table)) {
63
+ for (const tx of transactions) {
64
+ if (typeof tx.mileage === "number") miles += tx.mileage;
65
+ }
66
+ }
67
+ }
68
+ return miles;
69
+ }
@@ -0,0 +1,31 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // national-insurance.js — UK National Insurance calculations.
5
+
6
+ /**
7
+ * Calculate NI Class 4 contributions for self-employed.
8
+ * @param {number} profit - annual profit
9
+ * @param {Object} niRates - { class4_lower_limit, class4_upper_limit, class4_lower_rate, class4_upper_rate }
10
+ * @returns {{ lowerBand, upperBand, total }}
11
+ */
12
+ export function calculateNIClass4(profit, niRates) {
13
+ const { class4_lower_limit, class4_upper_limit, class4_lower_rate, class4_upper_rate } = niRates;
14
+ const lowerBand = profit > class4_lower_limit ? (Math.min(profit, class4_upper_limit) - class4_lower_limit) * class4_lower_rate : 0;
15
+ const upperBand = profit > class4_upper_limit ? (profit - class4_upper_limit) * class4_upper_rate : 0;
16
+ return { lowerBand, upperBand, total: lowerBand + upperBand };
17
+ }
18
+
19
+ /**
20
+ * Calculate NI Class 2 contributions for self-employed.
21
+ * @param {number} profit - annual profit
22
+ * @param {Object} niRates - { class2_weekly_rate, class2_small_profits_threshold? }
23
+ * @returns {number} annual Class 2 NI
24
+ */
25
+ export function calculateNIClass2(profit, niRates) {
26
+ const weeklyRate = niRates.class2_weekly_rate || niRates.class2_rate || 0;
27
+ if (weeklyRate === 0) return 0;
28
+ const threshold = niRates.class2_small_profits_threshold || 0;
29
+ if (threshold > 0 && profit < threshold) return 0;
30
+ return weeklyRate * 52;
31
+ }
@@ -0,0 +1,188 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // vat.js — The VAT interface and the return forms a package carries, computed
5
+ // the way Vat.xlsx computes them.
6
+ //
7
+ // Vatinterface holds one row per VAT period in date order. Rows 6 to 17 are the
8
+ // twelve accounting months, each fed by its own Sales and Purchases month tab.
9
+ // Rows 4 and 5 are the two periods before the accounting year and rows 18 to 20
10
+ // the three after it, each fed by its own straddling entry sheet. Column B is
11
+ // the period end, C the payment due date, D/F the period's sales net and output
12
+ // VAT, H/J its purchases net and input VAT, and E/G/I/K the rolling
13
+ // three-period sums the return boxes read.
14
+ //
15
+ // A return form names a period end in G5 and looks every box up against the
16
+ // interface row carrying that date.
17
+
18
+ import { VAT_RETURN_END_MONTHS } from "../generator.js";
19
+ import { SHEET_BLANK } from "../calculators/shared.js";
20
+
21
+ export { VAT_RETURN_END_MONTHS };
22
+
23
+ // The interface's first and last row, and the row the first accounting month
24
+ // lands on.
25
+ export const VATINTERFACE_FIRST_ROW = 4;
26
+ export const VATINTERFACE_LAST_ROW = 20;
27
+ export const VATINTERFACE_FIRST_MONTH_ROW = 6;
28
+
29
+ // Each interface row's period end, as the Admin B-column row its formula reads.
30
+ // Rows 4 and 5 take the two months before the accounting year, rows 6 to 17 the
31
+ // twelve month ends within it, and rows 18 to 20 the three that follow.
32
+ const PERIOD_END_ADMIN_ROWS = [2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20];
33
+
34
+ // The straddling entry sheet feeding each interface row outside the accounting
35
+ // year. Every other row is fed by a month tab.
36
+ export const STRADDLING_PERIOD_ROWS = { "02Y1": 4, "03Y1": 5, "04Y2": 18, "05Y2": 19, "06Y2": 20 };
37
+
38
+ /**
39
+ * Take VAT off a gross figure the way a journal row does: the rate is held as a
40
+ * percentage and the row divides by 100 plus it, rounding nothing.
41
+ * @param {number} gross
42
+ * @param {number} rate - a fraction, 0.2 for 20%
43
+ * @returns {{ vat: number, net: number }}
44
+ */
45
+ export function splitVat(gross, rate) {
46
+ const percent = rate * 100;
47
+ const vat = (gross * percent) / (100 + percent);
48
+ return { vat, net: gross - vat };
49
+ }
50
+
51
+ /**
52
+ * Sum straddling entries into the period totals their own sheet holds. Each
53
+ * sheet takes VAT off each entry, so the totals are sums of row figures.
54
+ * @param {Array} entries - scenario entries carrying { period, amount }
55
+ * @param {number} rate
56
+ * @returns {Object} period name -> { vat, net }
57
+ */
58
+ export function straddlingPeriodTotals(entries, rate) {
59
+ const totals = {};
60
+ for (const entry of entries || []) {
61
+ const { vat, net } = splitVat(entry.amount, rate);
62
+ const period = (totals[entry.period] ||= { vat: 0, net: 0 });
63
+ period.vat += vat;
64
+ period.net += net;
65
+ }
66
+ return totals;
67
+ }
68
+
69
+ /**
70
+ * Build the Vatinterface rows.
71
+ *
72
+ * @param {Object} options
73
+ * @param {Array<{ vat: number, net: number }>} options.salesMonths - twelve month tabs, the first accounting month first
74
+ * @param {Array<{ vat: number, net: number }>} options.purchasesMonths - the same, on the purchase journal
75
+ * @param {Object} options.straddlingSales - period name -> { vat, net }
76
+ * @param {Object} options.straddlingPurchases - the same, on the purchase side
77
+ * @param {Object} options.adminDateSerials - Admin B-column row -> Excel serial
78
+ * @param {number} [options.flatRateFlag] - the flat rate percentage column M carries
79
+ * @returns {Object} row number -> { B, C, D, E, F, G, H, I, J, K, M }
80
+ */
81
+ export function buildVatinterface({
82
+ salesMonths,
83
+ purchasesMonths,
84
+ straddlingSales = {},
85
+ straddlingPurchases = {},
86
+ adminDateSerials,
87
+ flatRateFlag = 0,
88
+ }) {
89
+ const periodByRow = {};
90
+ for (const [period, row] of Object.entries(STRADDLING_PERIOD_ROWS)) periodByRow[row] = period;
91
+
92
+ const rows = {};
93
+ for (let row = VATINTERFACE_FIRST_ROW; row <= VATINTERFACE_LAST_ROW; row++) {
94
+ const adminRow = PERIOD_END_ADMIN_ROWS[row - VATINTERFACE_FIRST_ROW];
95
+ const period = periodByRow[row];
96
+ const monthIndex = row - VATINTERFACE_FIRST_MONTH_ROW;
97
+ const sales = period ? straddlingSales[period] || { vat: 0, net: 0 } : salesMonths[monthIndex] || { vat: 0, net: 0 };
98
+ const purchases = period ? straddlingPurchases[period] || { vat: 0, net: 0 } : purchasesMonths[monthIndex] || { vat: 0, net: 0 };
99
+ rows[row] = {
100
+ B: adminDateSerials[adminRow],
101
+ D: sales.net,
102
+ F: sales.vat,
103
+ H: purchases.net,
104
+ J: purchases.vat,
105
+ M: flatRateFlag,
106
+ };
107
+ }
108
+
109
+ // The payment due date is the next period's end, and the last row takes the
110
+ // extra date the Admin sheet carries for it.
111
+ for (let row = VATINTERFACE_FIRST_ROW; row < VATINTERFACE_LAST_ROW; row++) {
112
+ rows[row].C = rows[row + 1].B;
113
+ }
114
+ rows[VATINTERFACE_LAST_ROW].C = adminDateSerials[25];
115
+
116
+ // A quarter column sums its own period row and the two before it. The first
117
+ // two rows close no quarter, so the sheet leaves their quarter columns empty.
118
+ for (const row of [VATINTERFACE_FIRST_ROW, VATINTERFACE_FIRST_ROW + 1]) {
119
+ for (const column of ["E", "G", "I", "K"]) rows[row][column] = SHEET_BLANK;
120
+ }
121
+ for (let row = VATINTERFACE_FIRST_MONTH_ROW; row <= VATINTERFACE_LAST_ROW; row++) {
122
+ const window = [rows[row - 2], rows[row - 1], rows[row]];
123
+ rows[row].E = window.reduce((total, r) => total + r.D, 0);
124
+ rows[row].G = window.reduce((total, r) => total + r.F, 0);
125
+ rows[row].I = window.reduce((total, r) => total + r.H, 0);
126
+ rows[row].K = window.reduce((total, r) => total + r.J, 0);
127
+ }
128
+
129
+ return rows;
130
+ }
131
+
132
+ /**
133
+ * The interface row a period end date lands on, or null when no row carries it.
134
+ * @param {Object} interfaceRows - buildVatinterface() output
135
+ * @param {number} periodEndSerial
136
+ * @returns {number|null}
137
+ */
138
+ export function vatinterfaceRowFor(interfaceRows, periodEndSerial) {
139
+ for (const [row, values] of Object.entries(interfaceRows)) {
140
+ if (Math.round(values.B) === Math.round(periodEndSerial)) return Number(row);
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /**
146
+ * The nine cells a VATQtr form carries, looked up against the interface the way
147
+ * the form's own LOOKUP formulas do.
148
+ *
149
+ * @param {Object} interfaceRows - buildVatinterface() output
150
+ * @param {number} periodEndSerial - the period the form is filled in for
151
+ * @returns {Object} { G5, G7, G9, G11, G13, G15, G17, G21, G23 }
152
+ */
153
+ export function vatReturnBoxes(interfaceRows, periodEndSerial) {
154
+ const row = vatinterfaceRowFor(interfaceRows, periodEndSerial);
155
+ const period = row === null ? { C: 0, E: 0, G: 0, I: 0, K: 0, M: 0 } : interfaceRows[row];
156
+ const flatRate = (period.M || 0) > 0;
157
+ const outputVat = period.G || 0;
158
+ const inputVat = period.K || 0;
159
+ // Box 2, VAT due on acquisitions from other EU states, is a nil the form
160
+ // never computes and the customer overwrites by hand.
161
+ const euAcquisitions = 0;
162
+ return {
163
+ G5: periodEndSerial,
164
+ G7: period.C || 0,
165
+ G9: outputVat,
166
+ G11: euAcquisitions,
167
+ G13: outputVat + euAcquisitions,
168
+ G15: inputVat,
169
+ G17: outputVat + euAcquisitions - inputVat,
170
+ G21: (period.E || 0) + (flatRate ? outputVat : 0),
171
+ G23: period.I || 0,
172
+ };
173
+ }
174
+
175
+ /**
176
+ * The period end each of the five return forms defaults to: a quarter apart,
177
+ * counted in months from the book's first accounting month.
178
+ * @param {Date} firstMonthStart - any day in the book's first month tab
179
+ * @param {function(Date): number} toSerial
180
+ * @returns {Array<number>} five Excel serials
181
+ */
182
+ export function vatReturnPeriodEnds(firstMonthStart, toSerial) {
183
+ return VAT_RETURN_END_MONTHS.map((months) => {
184
+ const year = firstMonthStart.getUTCFullYear();
185
+ const month = firstMonthStart.getUTCMonth() + months;
186
+ return toSerial(new Date(Date.UTC(year, month, 0)));
187
+ });
188
+ }
@@ -0,0 +1,31 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright (C) 2026 DIY Accounting Ltd
3
+ //
4
+ // tax-year.js — which app/data/<year>.toml file a date falls in. Shared by
5
+ // the package writer (product-workbook.js, which needs the file to apply)
6
+ // and the book loader (diya-gl-loader.js, which needs the file to fall back
7
+ // to when no --years override names one), so the two never resolve the
8
+ // same date to different years.
9
+
10
+ /**
11
+ * The tax year or financial year a date falls in, as the name of its file in
12
+ * app/data. A self-employment year turns on 6 April, so 31 March 2026 and
13
+ * 5 April 2026 are both se-2025-2026. A corporation tax financial year turns
14
+ * on 1 April, and a company's file is named for the calendar year of the
15
+ * 1 April on or before its year end: a period ending 31 March 2026 is FY2025,
16
+ * one ending 30 April 2026 is FY2026. It is the same rule the exporter reads
17
+ * back off a package's Admin sheet (packageTaxDataFile, xlsx-exporter.js).
18
+ *
19
+ * @param {Date} date - the end of the book's accounting period
20
+ * @param {"se"|"ltd"} [taxRegime]
21
+ * @returns {string}
22
+ */
23
+ export function taxYearFileName(date, taxRegime = "se") {
24
+ const year = date.getUTCFullYear();
25
+ if (taxRegime === "ltd") return `ltd-${date.getUTCMonth() < 3 ? year - 1 : year}`;
26
+ if (taxRegime !== "se") throw new Error(`no tax data file is named for the "${taxRegime}" regime`);
27
+
28
+ const beforeSixthOfApril = date.getUTCMonth() < 3 || (date.getUTCMonth() === 3 && date.getUTCDate() < 6);
29
+ const startYear = beforeSixthOfApril ? year - 1 : year;
30
+ return `se-${startYear}-${startYear + 1}`;
31
+ }