@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.
- package/README.md +63 -0
- package/bin/diya-gl-mcp.js +10 -0
- package/bin/diya-gl-read-workbook.js +11 -0
- package/bin/diya-gl-recalc.js +10 -0
- package/bin/diya-gl-write-workbook.js +12 -0
- package/bin/diya-gl.js +24 -0
- package/bin/run-dist-bin.js +23 -0
- package/dist/app/bin/build-diya-gl-spec.js +680 -0
- package/dist/app/bin/build-packages.js +149 -0
- package/dist/app/bin/build-reconciliation-pages.js +1052 -0
- package/dist/app/bin/build-sitemaps.js +51 -0
- package/dist/app/bin/compliance-report.js +125 -0
- package/dist/app/bin/cross-package-reconciliation.js +92 -0
- package/dist/app/bin/diya-gl-mcp.js +27 -0
- package/dist/app/bin/export.js +318 -0
- package/dist/app/bin/extract-scenarios.js +1348 -0
- package/dist/app/bin/generate.js +353 -0
- package/dist/app/bin/judge-reconciliation.js +649 -0
- package/dist/app/bin/reconcile.js +247 -0
- package/dist/app/bin/report.js +291 -0
- package/dist/app/bin/verify-roundtrip.js +941 -0
- package/dist/app/bin/verify-stability.js +429 -0
- package/dist/app/bin/write-workbook.js +106 -0
- package/dist/app/data/filing/ct-computation-v1.1.toml +1033 -0
- package/dist/app/data/filing/ct600-v3.toml +2329 -0
- package/dist/app/data/filing/frs105-formats.toml +244 -0
- package/dist/app/data/fixture-master-gaps.json +247 -0
- package/dist/app/data/hmrc/SOURCE.md +14 -0
- package/dist/app/data/hmrc/form-layouts/bst.json +116 -0
- package/dist/app/data/hmrc/form-layouts/ltd.json +452 -0
- package/dist/app/data/hmrc/form-layouts/se.json +485 -0
- package/dist/app/data/hmrc/form-layouts/taxi.json +117 -0
- package/dist/app/data/hmrc/sa103-mtd-mapping.json +1078 -0
- package/dist/app/data/hmrc/sa103f_mapping_v3.csv +111 -0
- package/dist/app/data/judge-rubric.md +52 -0
- package/dist/app/data/ltd-2020.toml +49 -0
- package/dist/app/data/ltd-2021.toml +49 -0
- package/dist/app/data/ltd-2022.toml +49 -0
- package/dist/app/data/ltd-2023.toml +49 -0
- package/dist/app/data/ltd-2024.toml +49 -0
- package/dist/app/data/ltd-2025.toml +49 -0
- package/dist/app/data/ltd-2026.toml +53 -0
- package/dist/app/data/ltd-2027.toml +51 -0
- package/dist/app/data/render-unrepresentable/bst.json +24 -0
- package/dist/app/data/render-unrepresentable/ltd.json +863 -0
- package/dist/app/data/render-unrepresentable/se.json +455 -0
- package/dist/app/data/render-unrepresentable/taxi.json +16 -0
- package/dist/app/data/roundtrip-budget.json +38 -0
- package/dist/app/data/roundtrip-matrix-budget.json +26 -0
- package/dist/app/data/roundtrip-unrepresentable.json +401 -0
- package/dist/app/data/se-2020-2021.toml +52 -0
- package/dist/app/data/se-2021-2022.toml +52 -0
- package/dist/app/data/se-2022-2023.toml +55 -0
- package/dist/app/data/se-2023-2024.toml +54 -0
- package/dist/app/data/se-2024-2025.toml +51 -0
- package/dist/app/data/se-2025-2026.toml +51 -0
- package/dist/app/data/se-2026-2027.toml +51 -0
- package/dist/app/data/volatile-cells.json +16 -0
- package/dist/app/lib/anchors/bst.js +79 -0
- package/dist/app/lib/anchors/ltd.js +626 -0
- package/dist/app/lib/anchors/run.js +100 -0
- package/dist/app/lib/anchors/se.js +456 -0
- package/dist/app/lib/anchors/taxi.js +164 -0
- package/dist/app/lib/app-resources.js +80 -0
- package/dist/app/lib/book-checks/ltd.js +408 -0
- package/dist/app/lib/book-checks/se.js +687 -0
- package/dist/app/lib/book-checks/taxi.js +215 -0
- package/dist/app/lib/book-checks.js +872 -0
- package/dist/app/lib/books-engine.js +197 -0
- package/dist/app/lib/books-interchange.js +533 -0
- package/dist/app/lib/calculators/bst.js +381 -0
- package/dist/app/lib/calculators/ltd.js +1938 -0
- package/dist/app/lib/calculators/se.js +1239 -0
- package/dist/app/lib/calculators/shared.js +131 -0
- package/dist/app/lib/calculators/taxi.js +461 -0
- package/dist/app/lib/canonical-report-value.js +77 -0
- package/dist/app/lib/compliance-report.js +341 -0
- package/dist/app/lib/diya-gl-calculator.js +52 -0
- package/dist/app/lib/diya-gl-canonical.js +355 -0
- package/dist/app/lib/diya-gl-edits-ltd.js +144 -0
- package/dist/app/lib/diya-gl-edits.js +361 -0
- package/dist/app/lib/diya-gl-loader.js +774 -0
- package/dist/app/lib/diya-gl-schema.js +212 -0
- package/dist/app/lib/generator.js +1912 -0
- package/dist/app/lib/guide.js +33 -0
- package/dist/app/lib/headlines.js +293 -0
- package/dist/app/lib/link-caches.js +421 -0
- package/dist/app/lib/ltd-layout.js +139 -0
- package/dist/app/lib/mcp/diya-gl-tools.js +330 -0
- package/dist/app/lib/mcp/jsonrpc-stdio.js +66 -0
- package/dist/app/lib/mcp/server.js +65 -0
- package/dist/app/lib/overtype-sidecar.js +180 -0
- package/dist/app/lib/package-builder.js +202 -0
- package/dist/app/lib/payslips-date-chain.js +481 -0
- package/dist/app/lib/payslips-layout.js +235 -0
- package/dist/app/lib/period-shift.js +111 -0
- package/dist/app/lib/product-workbook.js +317 -0
- package/dist/app/lib/products.js +27 -0
- package/dist/app/lib/provenance-data.js +36 -0
- package/dist/app/lib/provenance.js +92 -0
- package/dist/app/lib/report-generator.js +374 -0
- package/dist/app/lib/report-indicators.js +468 -0
- package/dist/app/lib/report-serializer.js +392 -0
- package/dist/app/lib/scenario-extractor.js +1403 -0
- package/dist/app/lib/scenario-loader.js +84 -0
- package/dist/app/lib/sitemap-builder.js +59 -0
- package/dist/app/lib/spreadsheet-runner.js +566 -0
- package/dist/app/lib/tax/capital-allowances.js +77 -0
- package/dist/app/lib/tax/corporation-tax.js +144 -0
- package/dist/app/lib/tax/income-tax.js +122 -0
- package/dist/app/lib/tax/mileage.js +69 -0
- package/dist/app/lib/tax/national-insurance.js +31 -0
- package/dist/app/lib/tax/vat.js +188 -0
- package/dist/app/lib/tax-year.js +31 -0
- package/dist/app/lib/template-formula-map.js +253 -0
- package/dist/app/lib/workbook-set.js +153 -0
- package/dist/app/lib/xlsx-exporter.js +2815 -0
- package/dist/app/lib/xlsx-parts.js +111 -0
- package/dist/app/lib/xlsx-reader.js +84 -0
- package/dist/app/products/bst.js +727 -0
- package/dist/app/products/ltd.js +4270 -0
- package/dist/app/products/se.js +3403 -0
- package/dist/app/products/taxi.js +912 -0
- package/dist/app/templates/bst/bst-excel.xlsx +0 -0
- package/dist/app/templates/bst/meta.toml +27 -0
- package/dist/app/templates/ltd/Cashaccount.xlsx +0 -0
- package/dist/app/templates/ltd/Companysecretary.xlsx +0 -0
- package/dist/app/templates/ltd/Creditcardaccount.xlsx +0 -0
- package/dist/app/templates/ltd/Currentaccount.xlsx +0 -0
- package/dist/app/templates/ltd/Dividend Voucher.docx +0 -0
- package/dist/app/templates/ltd/Financialaccounts.xlsx +0 -0
- package/dist/app/templates/ltd/Fixedassets.xlsx +0 -0
- package/dist/app/templates/ltd/Payslips.xlsx +0 -0
- package/dist/app/templates/ltd/Purchases.xlsx +0 -0
- package/dist/app/templates/ltd/Sales.xlsx +0 -0
- package/dist/app/templates/ltd/Salesinvoice.xlsx +0 -0
- package/dist/app/templates/ltd/Savingaccount.xlsx +0 -0
- package/dist/app/templates/ltd/Vatreturns.xlsx +0 -0
- package/dist/app/templates/ltd/expensesform.xlsx +0 -0
- package/dist/app/templates/ltd/meta.toml +54 -0
- package/dist/app/templates/meta.toml +12 -0
- package/dist/app/templates/se/Bank.xlsx +0 -0
- package/dist/app/templates/se/Cash.xlsx +0 -0
- package/dist/app/templates/se/Financialaccounts.xlsx +0 -0
- package/dist/app/templates/se/Fixedassets.xlsx +0 -0
- package/dist/app/templates/se/Payslips.xlsx +0 -0
- package/dist/app/templates/se/Purchases.xlsx +0 -0
- package/dist/app/templates/se/Sales.xlsx +0 -0
- package/dist/app/templates/se/Salesinvoice.xlsx +0 -0
- package/dist/app/templates/se/Vat.xlsx +0 -0
- package/dist/app/templates/se/meta.toml +43 -0
- package/dist/app/templates/taxi/meta.toml +43 -0
- package/dist/app/templates/taxi/taxi-excel.xlsx +0 -0
- package/dist/web/spreadsheets.diyaccounting.co.uk/public/schema/diya-gl-book-v2.schema.json +713 -0
- package/dist/web/spreadsheets.diyaccounting.co.uk/public/schema/diya-gl-docs.md +930 -0
- package/dist/web/spreadsheets.diyaccounting.co.uk/public/schema/diya-gl-lines-v2.schema.json +220 -0
- package/package.json +37 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
// Copyright (C) 2025-2026 DIY Accounting Ltd
|
|
3
|
+
//
|
|
4
|
+
// package-builder.js — Pure functions for package directory parsing,
|
|
5
|
+
// company variant generation, and catalogue TOML output.
|
|
6
|
+
|
|
7
|
+
// Regex to parse standard package directory names
|
|
8
|
+
// e.g. "GB Accounts Basic Sole Trader 2025-04-05 (Apr25) Excel 2007"
|
|
9
|
+
export const PACKAGE_RE = /^GB Accounts (.+?) (\d{4}-\d{2}-\d{2}) \((\w+)\) (Excel \d{4})$/;
|
|
10
|
+
|
|
11
|
+
// Regex to parse Company (Any) directory names
|
|
12
|
+
// e.g. "GB Accounts Company 2024-2025 (Any) Excel 2007"
|
|
13
|
+
export const ANY_RE = /^GB Accounts Company (\d{4})-(\d{4}) \(Any\) (Excel \d{4})$/;
|
|
14
|
+
|
|
15
|
+
// Product display names and IDs for the catalogue
|
|
16
|
+
export const PRODUCTS = {
|
|
17
|
+
"Basic Sole Trader": {
|
|
18
|
+
id: "BasicSoleTrader",
|
|
19
|
+
description:
|
|
20
|
+
"Simple bookkeeping spreadsheet for sole traders not registered for VAT. Includes profit & loss, self assessment tax, and fixed assets.",
|
|
21
|
+
},
|
|
22
|
+
"Self Employed": {
|
|
23
|
+
id: "SelfEmployed",
|
|
24
|
+
description:
|
|
25
|
+
"Full bookkeeping spreadsheet for self-employed businesses. Includes sales, purchases, VAT returns, bank reconciliation, payslips, and self assessment.",
|
|
26
|
+
},
|
|
27
|
+
"Company": {
|
|
28
|
+
id: "Company",
|
|
29
|
+
description:
|
|
30
|
+
"Complete accounting spreadsheet for limited companies. Includes sales, purchases, VAT, corporation tax, payroll, dividends, and year-end accounts.",
|
|
31
|
+
},
|
|
32
|
+
"Taxi Driver": {
|
|
33
|
+
id: "TaxiDriver",
|
|
34
|
+
description:
|
|
35
|
+
"Bookkeeping spreadsheet designed for taxi drivers. Branded as Cabsmart, includes income tax, VAT, profit & loss, receipts, and expenses tracking.",
|
|
36
|
+
},
|
|
37
|
+
"Payslip 05": {
|
|
38
|
+
id: "Payslip05",
|
|
39
|
+
description: "Payslip generator for up to 5 employees. Calculates PAYE, National Insurance, student loans, and pension contributions.",
|
|
40
|
+
},
|
|
41
|
+
"Payslip 10": {
|
|
42
|
+
id: "Payslip10",
|
|
43
|
+
description: "Payslip generator for up to 10 employees. Calculates PAYE, National Insurance, student loans, and pension contributions.",
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// Months for Company (Any) generation
|
|
48
|
+
export const MONTHS = [
|
|
49
|
+
{ month: 4, abbr: "Apr" },
|
|
50
|
+
{ month: 5, abbr: "May" },
|
|
51
|
+
{ month: 6, abbr: "Jun" },
|
|
52
|
+
{ month: 7, abbr: "Jul" },
|
|
53
|
+
{ month: 8, abbr: "Aug" },
|
|
54
|
+
{ month: 9, abbr: "Sep" },
|
|
55
|
+
{ month: 10, abbr: "Oct" },
|
|
56
|
+
{ month: 11, abbr: "Nov" },
|
|
57
|
+
{ month: 12, abbr: "Dec" },
|
|
58
|
+
{ month: 1, abbr: "Jan" },
|
|
59
|
+
{ month: 2, abbr: "Feb" },
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
export function pad2(n) {
|
|
63
|
+
return String(n).padStart(2, "0");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function isLeapYear(year) {
|
|
67
|
+
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function monthEndDate(year, month) {
|
|
71
|
+
if (month === 2 && isLeapYear(year)) return 29;
|
|
72
|
+
const daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
73
|
+
return daysInMonth[month];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function parsePackageDir(dirName) {
|
|
77
|
+
const match = dirName.match(PACKAGE_RE);
|
|
78
|
+
if (!match) return null;
|
|
79
|
+
const [, productName, date, shortLabel, format] = match;
|
|
80
|
+
return { productName, date, shortLabel, format };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function parseCompanyAnyDir(dirName) {
|
|
84
|
+
const match = dirName.match(ANY_RE);
|
|
85
|
+
if (!match) return null;
|
|
86
|
+
return { startYear: parseInt(match[1], 10), endYear: parseInt(match[2], 10), format: match[3] };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Generate the list of Company month-end variants for a given tax year range.
|
|
91
|
+
* Returns metadata only (no I/O).
|
|
92
|
+
* @param {number} startYear - e.g. 2024
|
|
93
|
+
* @param {number} endYear - e.g. 2025
|
|
94
|
+
* @param {string} format - e.g. "Excel 2007"
|
|
95
|
+
* @param {Date} now - current date for cutoff calculation
|
|
96
|
+
* @returns {{ variants: Array<{date, shortLabel, format, zipName}>, skipped: string[] }}
|
|
97
|
+
*/
|
|
98
|
+
export function generateCompanyVariantNames(startYear, endYear, format, now) {
|
|
99
|
+
const variants = [];
|
|
100
|
+
const skipped = [];
|
|
101
|
+
const firstYearEnd = startYear + 1;
|
|
102
|
+
const secondYearEnd = endYear + 1;
|
|
103
|
+
const currentYM = now.getFullYear() * 12 + (now.getMonth() + 1);
|
|
104
|
+
|
|
105
|
+
for (const m of MONTHS) {
|
|
106
|
+
const year = m.month >= 4 ? firstYearEnd : secondYearEnd;
|
|
107
|
+
|
|
108
|
+
// Financial year start: month after year-end, one year earlier
|
|
109
|
+
const fyStartMonth = m.month === 12 ? 1 : m.month + 1;
|
|
110
|
+
const fyStartYear = m.month === 12 ? year : year - 1;
|
|
111
|
+
const fyStartYM = fyStartYear * 12 + fyStartMonth;
|
|
112
|
+
|
|
113
|
+
if (currentYM < fyStartYM) {
|
|
114
|
+
skipped.push(`${m.abbr}${String(year).slice(-2)}`);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const yr2 = String(year).slice(-2);
|
|
119
|
+
const days = monthEndDate(year, m.month);
|
|
120
|
+
const date = `${year}-${pad2(m.month)}-${pad2(days)}`;
|
|
121
|
+
const shortLabel = `${m.abbr}${yr2}`;
|
|
122
|
+
const zipName = `GB Accounts Company ${date} (${shortLabel}) ${format}`;
|
|
123
|
+
|
|
124
|
+
variants.push({ date, shortLabel, format, zipName });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return { variants, skipped };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function dateToLabel(date) {
|
|
131
|
+
const [y, m] = date.split("-").map(Number);
|
|
132
|
+
const months = [
|
|
133
|
+
"",
|
|
134
|
+
"January",
|
|
135
|
+
"February",
|
|
136
|
+
"March",
|
|
137
|
+
"April",
|
|
138
|
+
"May",
|
|
139
|
+
"June",
|
|
140
|
+
"July",
|
|
141
|
+
"August",
|
|
142
|
+
"September",
|
|
143
|
+
"October",
|
|
144
|
+
"November",
|
|
145
|
+
"December",
|
|
146
|
+
];
|
|
147
|
+
return `${months[m]} ${y}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Stable product order for catalogue output
|
|
151
|
+
export const PRODUCT_ORDER = ["Basic Sole Trader", "Self Employed", "Company", "Taxi Driver", "Payslip 05", "Payslip 10"];
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Generate catalogue.toml content from a list of package records.
|
|
155
|
+
* @param {Array<{product, date, shortLabel, format, filename}>} allPackages
|
|
156
|
+
* @param {string} generatedDate - ISO date string (YYYY-MM-DD)
|
|
157
|
+
* @returns {string} TOML content
|
|
158
|
+
*/
|
|
159
|
+
export function generateCatalogue(allPackages, generatedDate) {
|
|
160
|
+
// Group by product
|
|
161
|
+
const byProduct = {};
|
|
162
|
+
for (const pkg of allPackages) {
|
|
163
|
+
if (!byProduct[pkg.product]) byProduct[pkg.product] = [];
|
|
164
|
+
byProduct[pkg.product].push(pkg);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Sort each product's packages by date descending (newest first)
|
|
168
|
+
for (const product of Object.keys(byProduct)) {
|
|
169
|
+
byProduct[product].sort((a, b) => b.date.localeCompare(a.date));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const lines = [
|
|
173
|
+
"# catalogue.toml — Auto-generated by app/bin/build-packages.js",
|
|
174
|
+
"# Do not edit manually; regenerated on each deploy from packages/ directory.",
|
|
175
|
+
"",
|
|
176
|
+
`generated = "${generatedDate}"`,
|
|
177
|
+
"",
|
|
178
|
+
];
|
|
179
|
+
|
|
180
|
+
for (const productName of PRODUCT_ORDER) {
|
|
181
|
+
const meta = PRODUCTS[productName];
|
|
182
|
+
if (!meta || !byProduct[productName]) continue;
|
|
183
|
+
|
|
184
|
+
lines.push(`[[products]]`);
|
|
185
|
+
lines.push(`id = "${meta.id}"`);
|
|
186
|
+
lines.push(`name = "${productName}"`);
|
|
187
|
+
lines.push(`description = "${meta.description}"`);
|
|
188
|
+
lines.push("");
|
|
189
|
+
|
|
190
|
+
for (const pkg of byProduct[productName]) {
|
|
191
|
+
lines.push(` [[products.periods]]`);
|
|
192
|
+
lines.push(` date = "${pkg.date}"`);
|
|
193
|
+
lines.push(` label = "${dateToLabel(pkg.date)}"`);
|
|
194
|
+
lines.push(` short = "${pkg.shortLabel}"`);
|
|
195
|
+
lines.push(` format = "${pkg.format}"`);
|
|
196
|
+
lines.push(` filename = "${pkg.filename}"`);
|
|
197
|
+
lines.push("");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return lines.join("\n");
|
|
202
|
+
}
|
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
// Copyright (C) 2026 DIY Accounting Ltd
|
|
3
|
+
//
|
|
4
|
+
// payslips-date-chain.js — recomputes the cached dates the Payslips workbook
|
|
5
|
+
// carries downstream of its Admin calendar.
|
|
6
|
+
//
|
|
7
|
+
// The Admin sheet's B column is a daily calendar anchored on the payroll
|
|
8
|
+
// year's 6 April, and the generator rewrites both the anchor and every cached
|
|
9
|
+
// day on it. The rest of the workbook does not read that calendar day by day.
|
|
10
|
+
// A month tab's first weekly block reads it once and then the blocks chain:
|
|
11
|
+
// each one counts days off the block above it, and the first block of a month
|
|
12
|
+
// counts off the last block of the month before, on the tab before. Only the
|
|
13
|
+
// seeds are Admin reads, so rolling the Admin reads alone leaves every counted
|
|
14
|
+
// cell on the template's own year -- a week ending a year before it starts, on
|
|
15
|
+
// the workbook a customer downloads and opens without recalculating.
|
|
16
|
+
//
|
|
17
|
+
// So the chain is evaluated rather than pattern-rolled: the cells the layout
|
|
18
|
+
// says carry a date are computed from their own formulas, over the calendar
|
|
19
|
+
// the generator has just written, and their caches replaced. A formula the
|
|
20
|
+
// evaluator does not recognise throws, because the alternative is keeping a
|
|
21
|
+
// stale cache and calling it rolled.
|
|
22
|
+
|
|
23
|
+
import { PAYROLL_WEEKS_PER_MONTH, PAYSLIP_PRINT_SHEET, PAYSLIP_PRINT_CELLS } from "./payslips-layout.js";
|
|
24
|
+
|
|
25
|
+
const PAYSLIPS_EMPLOYEE_SHEET = "Employee";
|
|
26
|
+
const PAYSLIPS_ADMIN_SHEET = "Admin";
|
|
27
|
+
const PAYSLIPS_PAYMENT_SHEET = "Payment";
|
|
28
|
+
|
|
29
|
+
// The twelve month tabs are whichever sheets carry a month's name, in workbook
|
|
30
|
+
// order -- the names move with the package's year end, their order does not.
|
|
31
|
+
const MONTH_TAB_NAMES = new Set(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]);
|
|
32
|
+
|
|
33
|
+
// The Admin daily calendar: B2 is the payroll year's first day and every row
|
|
34
|
+
// below it one day later, down to the last row the chain reaches.
|
|
35
|
+
const ADMIN_CALENDAR_FIRST_ROW = 2;
|
|
36
|
+
const ADMIN_CALENDAR_LAST_ROW = 381;
|
|
37
|
+
// I1 is the payroll year's last day, the day before the next year's B2.
|
|
38
|
+
const ADMIN_YEAR_END_CELL = "I1";
|
|
39
|
+
|
|
40
|
+
// The Admin sheet's own "Date code" column reads two days back off the B
|
|
41
|
+
// chain: the payroll year's first (E2) and its last (E366).
|
|
42
|
+
const ADMIN_DATE_CODE_CELLS = ["E2", "E366"];
|
|
43
|
+
|
|
44
|
+
// The Employee sheet dates its calendar column straight off the Admin chain,
|
|
45
|
+
// which the Admin roll already reaches. M9 and O9 are the year's two ends the
|
|
46
|
+
// sheet prints as a caption, O9 through Admin's I1 rather than its B column.
|
|
47
|
+
const EMPLOYEE_CHAIN_CELLS = ["M9", "O9"];
|
|
48
|
+
|
|
49
|
+
// The PAYE remittance schedule's rows: B the tax month end, C the day the
|
|
50
|
+
// payment is due, M the online filing month code the first row builds from
|
|
51
|
+
// the calendar's own year and the rest count up from.
|
|
52
|
+
const PAYMENT_FIRST_ROW = 4;
|
|
53
|
+
const PAYMENT_LAST_ROW = 15;
|
|
54
|
+
const PAYMENT_CHAIN_COLUMNS = ["B", "C", "M"];
|
|
55
|
+
|
|
56
|
+
// The printed page's "Tax Week ended" and the four copies of it further down
|
|
57
|
+
// the page. Each is an INDIRECT through the page's own join, so the date on
|
|
58
|
+
// the page a customer prints is the chain's, one step removed.
|
|
59
|
+
const PRINT_PERIOD_END_CELLS = [PAYSLIP_PRINT_CELLS.periodEnd, "I23", "I38", "I52", "I67"];
|
|
60
|
+
|
|
61
|
+
// The page's join to a month tab: H3 the tab name, H4 the row its block starts
|
|
62
|
+
// on. Both are LOOKUPs down the Admin calendar, which this evaluator does not
|
|
63
|
+
// compute -- the generator sets H3's cache when it renames the tabs and the
|
|
64
|
+
// template ships H4's, so the join is read from there. Their values are
|
|
65
|
+
// checked before use, because a join read from a stale cache would move every
|
|
66
|
+
// figure on the page rather than fail.
|
|
67
|
+
const PRINT_JOIN_CELLS = [PAYSLIP_PRINT_CELLS.tab, PAYSLIP_PRINT_CELLS.blockRow];
|
|
68
|
+
|
|
69
|
+
const EXCEL_EPOCH_UTC = Date.UTC(1899, 11, 30);
|
|
70
|
+
const MS_PER_DAY = 86400000;
|
|
71
|
+
|
|
72
|
+
const serialToUtc = (serial) => new Date(EXCEL_EPOCH_UTC + Math.round(serial) * MS_PER_DAY);
|
|
73
|
+
const utcToSerial = (date) => Math.round((date.getTime() - EXCEL_EPOCH_UTC) / MS_PER_DAY);
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The cells this evaluator recomputes, in the order the layout lays them out.
|
|
77
|
+
* The month tabs come from the workbook rather than from a name list, because
|
|
78
|
+
* the tabs are renamed for a non-March year end and their place in the book is
|
|
79
|
+
* what fixes the block rows.
|
|
80
|
+
* @param {string[]} monthTabs - the twelve month tabs in workbook order
|
|
81
|
+
* @returns {{sheet: string, ref: string}[]}
|
|
82
|
+
*/
|
|
83
|
+
export function payslipsChainedDateCells(monthTabs) {
|
|
84
|
+
if (monthTabs.length !== PAYROLL_WEEKS_PER_MONTH.length) {
|
|
85
|
+
throw new Error(`The Payslips workbook has ${monthTabs.length} month tabs, not ${PAYROLL_WEEKS_PER_MONTH.length}`);
|
|
86
|
+
}
|
|
87
|
+
const cells = [];
|
|
88
|
+
monthTabs.forEach((tab, monthIndex) => {
|
|
89
|
+
// One ten-row block per tax week from row 8, then the monthly block below
|
|
90
|
+
// them. Each block opens its period on its second row: K the first day, M
|
|
91
|
+
// the last.
|
|
92
|
+
const blocks = PAYROLL_WEEKS_PER_MONTH[monthIndex] + 1;
|
|
93
|
+
for (let block = 0; block < blocks; block++) {
|
|
94
|
+
const row = 9 + 10 * block;
|
|
95
|
+
cells.push({ sheet: tab, ref: `K${row}` }, { sheet: tab, ref: `M${row}` });
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
for (const ref of EMPLOYEE_CHAIN_CELLS) cells.push({ sheet: PAYSLIPS_EMPLOYEE_SHEET, ref });
|
|
99
|
+
for (const ref of ADMIN_DATE_CODE_CELLS) cells.push({ sheet: PAYSLIPS_ADMIN_SHEET, ref });
|
|
100
|
+
for (let row = PAYMENT_FIRST_ROW; row <= PAYMENT_LAST_ROW; row++) {
|
|
101
|
+
for (const column of PAYMENT_CHAIN_COLUMNS) cells.push({ sheet: PAYSLIPS_PAYMENT_SHEET, ref: `${column}${row}` });
|
|
102
|
+
}
|
|
103
|
+
for (const ref of PRINT_PERIOD_END_CELLS) cells.push({ sheet: PAYSLIP_PRINT_SHEET, ref });
|
|
104
|
+
return cells;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ── Reading a sheet's cells out of its XML ──────────────────────────────────
|
|
108
|
+
|
|
109
|
+
const CELL_PATTERN = /<c\s+r="([A-Z]+\d+)"([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g;
|
|
110
|
+
const FORMULA_PATTERN = /<f([^>]*?)(?:\/>|>([\s\S]*?)<\/f>)/;
|
|
111
|
+
|
|
112
|
+
function decodeXml(text) {
|
|
113
|
+
return text
|
|
114
|
+
.replace(/</g, "<")
|
|
115
|
+
.replace(/>/g, ">")
|
|
116
|
+
.replace(/"/g, '"')
|
|
117
|
+
.replace(/'/g, "'")
|
|
118
|
+
.replace(/&/g, "&");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// One sheet's cells, with shared formulas resolved back to the text their
|
|
122
|
+
// master cell declares. A shared formula's continuation cells carry no text of
|
|
123
|
+
// their own, so a chain running through one would otherwise look like a cell
|
|
124
|
+
// with no formula at all.
|
|
125
|
+
function readSheet(name, xml, sharedStrings) {
|
|
126
|
+
const cells = new Map();
|
|
127
|
+
const sharedMasters = new Map();
|
|
128
|
+
for (const match of xml.matchAll(CELL_PATTERN)) {
|
|
129
|
+
const [, ref, attrs, body] = match;
|
|
130
|
+
const type = (attrs.match(/\st="([^"]+)"/) || [])[1] || "n";
|
|
131
|
+
const valueMatch = body ? body.match(/<v>([\s\S]*?)<\/v>/) : null;
|
|
132
|
+
const formulaMatch = body ? body.match(FORMULA_PATTERN) : null;
|
|
133
|
+
const cell = { ref, type, raw: valueMatch ? decodeXml(valueMatch[1]) : null, formula: null, shared: null };
|
|
134
|
+
if (formulaMatch) {
|
|
135
|
+
const formulaAttrs = formulaMatch[1] || "";
|
|
136
|
+
const text = formulaMatch[2] ? decodeXml(formulaMatch[2]) : null;
|
|
137
|
+
const si = (formulaAttrs.match(/\ssi="(\d+)"/) || [])[1];
|
|
138
|
+
if (si !== undefined && text) sharedMasters.set(si, { ref, text });
|
|
139
|
+
cell.formula = text;
|
|
140
|
+
cell.shared = si;
|
|
141
|
+
}
|
|
142
|
+
cells.set(ref, cell);
|
|
143
|
+
}
|
|
144
|
+
for (const cell of cells.values()) {
|
|
145
|
+
if (cell.formula || cell.shared === null || cell.shared === undefined) continue;
|
|
146
|
+
const master = sharedMasters.get(cell.shared);
|
|
147
|
+
if (!master) throw new Error(`Payslips ${name}!${cell.ref} shares formula ${cell.shared}, which no cell declares`);
|
|
148
|
+
cell.formula = translateFormula(master.text, master.ref, cell.ref);
|
|
149
|
+
}
|
|
150
|
+
return { name, cells, sharedStrings };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const columnToNumber = (column) => [...column].reduce((n, letter) => n * 26 + (letter.charCodeAt(0) - 64), 0);
|
|
154
|
+
|
|
155
|
+
function numberToColumn(number) {
|
|
156
|
+
let column = "";
|
|
157
|
+
let n = number;
|
|
158
|
+
while (n > 0) {
|
|
159
|
+
const remainder = (n - 1) % 26;
|
|
160
|
+
column = String.fromCharCode(65 + remainder) + column;
|
|
161
|
+
n = Math.floor((n - remainder) / 26);
|
|
162
|
+
}
|
|
163
|
+
return column;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const splitRef = (ref) => {
|
|
167
|
+
const parts = /^([A-Z]+)(\d+)$/.exec(ref);
|
|
168
|
+
if (!parts) throw new Error(`${ref} is not a cell reference`);
|
|
169
|
+
return { column: parts[1], row: parseInt(parts[2], 10) };
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// A shared formula's continuation cells hold the master's formula with every
|
|
173
|
+
// relative reference shifted by the distance between the two cells. An
|
|
174
|
+
// absolute part ($A, $1) does not move.
|
|
175
|
+
const SHIFTABLE_REF = /(\$?)([A-Z]{1,3})(\$?)(\d+)/g;
|
|
176
|
+
|
|
177
|
+
function translateFormula(text, masterRef, targetRef) {
|
|
178
|
+
const master = splitRef(masterRef);
|
|
179
|
+
const target = splitRef(targetRef);
|
|
180
|
+
const columnShift = columnToNumber(target.column) - columnToNumber(master.column);
|
|
181
|
+
const rowShift = target.row - master.row;
|
|
182
|
+
return text.replace(SHIFTABLE_REF, (whole, columnAbsolute, column, rowAbsolute, row) => {
|
|
183
|
+
const newColumn = columnAbsolute ? column : numberToColumn(columnToNumber(column) + columnShift);
|
|
184
|
+
const newRow = rowAbsolute ? row : String(parseInt(row, 10) + rowShift);
|
|
185
|
+
return `${columnAbsolute}${newColumn}${rowAbsolute}${newRow}`;
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ── The formula grammar the chain is written in ─────────────────────────────
|
|
190
|
+
|
|
191
|
+
const TOKEN_PATTERN =
|
|
192
|
+
/\s*(?:(?<number>\d+(?:\.\d+)?)|(?<string>"(?:[^"]|"")*")|(?<sheetRef>(?:'[^']+'|[A-Za-z_][A-Za-z0-9_.]*)!\$?[A-Z]{1,3}\$?\d+)|(?<call>[A-Za-z][A-Za-z0-9.]*)\s*\(|(?<ref>\$?[A-Z]{1,3}\$?\d+)|(?<word>[A-Za-z][A-Za-z0-9.]*)|(?<symbol>[-+*/(),]))/y;
|
|
193
|
+
|
|
194
|
+
function tokenize(formula, where) {
|
|
195
|
+
const tokens = [];
|
|
196
|
+
TOKEN_PATTERN.lastIndex = 0;
|
|
197
|
+
while (TOKEN_PATTERN.lastIndex < formula.length) {
|
|
198
|
+
const start = TOKEN_PATTERN.lastIndex;
|
|
199
|
+
const match = TOKEN_PATTERN.exec(formula);
|
|
200
|
+
if (!match) {
|
|
201
|
+
if (/^\s*$/.test(formula.slice(start))) break;
|
|
202
|
+
throw new Error(`${where} reads ${formula}, which this evaluator cannot read from column ${start + 1}`);
|
|
203
|
+
}
|
|
204
|
+
const groups = match.groups;
|
|
205
|
+
if (groups.number !== undefined) tokens.push({ kind: "number", text: groups.number });
|
|
206
|
+
else if (groups.string !== undefined) tokens.push({ kind: "string", text: groups.string.slice(1, -1).replace(/""/g, '"') });
|
|
207
|
+
else if (groups.sheetRef !== undefined) tokens.push({ kind: "ref", text: groups.sheetRef });
|
|
208
|
+
else if (groups.call !== undefined) tokens.push({ kind: "call", text: groups.call.toUpperCase() });
|
|
209
|
+
else if (groups.ref !== undefined) tokens.push({ kind: "ref", text: groups.ref });
|
|
210
|
+
else if (groups.word !== undefined) tokens.push({ kind: "word", text: groups.word.toUpperCase() });
|
|
211
|
+
else tokens.push({ kind: "symbol", text: groups.symbol });
|
|
212
|
+
}
|
|
213
|
+
return tokens;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ADDRESS() hands INDIRECT() a reference rather than a value, so it evaluates
|
|
217
|
+
// to one. Nothing else in this grammar takes or returns a reference.
|
|
218
|
+
const isReference = (value) => value !== null && typeof value === "object" && "sheet" in value;
|
|
219
|
+
|
|
220
|
+
function parseFormula(tokens, where, formula) {
|
|
221
|
+
let position = 0;
|
|
222
|
+
const peek = () => tokens[position];
|
|
223
|
+
const take = () => tokens[position++];
|
|
224
|
+
const expect = (text) => {
|
|
225
|
+
const token = take();
|
|
226
|
+
if (!token || token.text !== text) throw new Error(`${where} reads ${formula}, which this evaluator cannot read: expected ${text}`);
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
function parseExpression() {
|
|
230
|
+
let node = parseTerm();
|
|
231
|
+
while (peek() && (peek().text === "+" || peek().text === "-")) {
|
|
232
|
+
const operator = take().text;
|
|
233
|
+
node = { kind: "binary", operator, left: node, right: parseTerm() };
|
|
234
|
+
}
|
|
235
|
+
return node;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function parseTerm() {
|
|
239
|
+
let node = parseUnary();
|
|
240
|
+
while (peek() && (peek().text === "*" || peek().text === "/")) {
|
|
241
|
+
const operator = take().text;
|
|
242
|
+
node = { kind: "binary", operator, left: node, right: parseUnary() };
|
|
243
|
+
}
|
|
244
|
+
return node;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function parseUnary() {
|
|
248
|
+
if (peek() && peek().text === "-") {
|
|
249
|
+
take();
|
|
250
|
+
return { kind: "negate", operand: parseUnary() };
|
|
251
|
+
}
|
|
252
|
+
return parsePrimary();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function parsePrimary() {
|
|
256
|
+
const token = take();
|
|
257
|
+
if (!token) throw new Error(`${where} reads ${formula}, which ends before it is finished`);
|
|
258
|
+
if (token.kind === "number") return { kind: "number", value: Number(token.text) };
|
|
259
|
+
if (token.kind === "string") return { kind: "string", value: token.text };
|
|
260
|
+
if (token.kind === "ref") return { kind: "ref", text: token.text };
|
|
261
|
+
if (token.kind === "word") {
|
|
262
|
+
if (token.text === "TRUE") return { kind: "boolean", value: true };
|
|
263
|
+
if (token.text === "FALSE") return { kind: "boolean", value: false };
|
|
264
|
+
throw new Error(`${where} reads ${formula}, whose ${token.text} this evaluator does not know`);
|
|
265
|
+
}
|
|
266
|
+
if (token.kind === "call") {
|
|
267
|
+
const args = [];
|
|
268
|
+
if (peek() && peek().text === ")") take();
|
|
269
|
+
else {
|
|
270
|
+
for (;;) {
|
|
271
|
+
args.push(parseExpression());
|
|
272
|
+
const next = take();
|
|
273
|
+
if (!next) throw new Error(`${where} reads ${formula}, whose ${token.text}( never closes`);
|
|
274
|
+
if (next.text === ")") break;
|
|
275
|
+
if (next.text !== ",") throw new Error(`${where} reads ${formula}, which this evaluator cannot read at ${next.text}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return { kind: "call", name: token.text, args };
|
|
279
|
+
}
|
|
280
|
+
if (token.text === "(") {
|
|
281
|
+
const node = parseExpression();
|
|
282
|
+
expect(")");
|
|
283
|
+
return node;
|
|
284
|
+
}
|
|
285
|
+
throw new Error(`${where} reads ${formula}, which this evaluator cannot read at ${token.text}`);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const node = parseExpression();
|
|
289
|
+
if (position !== tokens.length) throw new Error(`${where} reads ${formula}, which has more in it than this evaluator can read`);
|
|
290
|
+
return node;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ── Walking the chain ───────────────────────────────────────────────────────
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Recompute every cached date the Payslips workbook carries downstream of its
|
|
297
|
+
* Admin calendar, and hand back the sheets whose XML changed.
|
|
298
|
+
*
|
|
299
|
+
* @param {Map<string, string>} sheetXmls - sheet name to worksheet XML, in workbook order
|
|
300
|
+
* @param {number} startYear - the year the package's payroll calendar opens in
|
|
301
|
+
* @param {string[]} sharedStrings - the workbook's shared string table
|
|
302
|
+
* @param {(xml: string, ref: string, value: string|number) => string} writeCachedValue
|
|
303
|
+
* @returns {Map<string, string>} the same sheet names, with the recomputed caches written
|
|
304
|
+
*/
|
|
305
|
+
export function rollPayslipsCachedDateChain(sheetXmls, startYear, sharedStrings, writeCachedValue) {
|
|
306
|
+
const sheets = new Map();
|
|
307
|
+
for (const [name, xml] of sheetXmls) sheets.set(name, readSheet(name, xml, sharedStrings));
|
|
308
|
+
|
|
309
|
+
const monthTabs = [...sheetXmls.keys()].filter((name) => MONTH_TAB_NAMES.has(name));
|
|
310
|
+
const yearStartSerial = utcToSerial(new Date(Date.UTC(startYear, 3, 6)));
|
|
311
|
+
const yearEndSerial = utcToSerial(new Date(Date.UTC(startYear + 1, 3, 5)));
|
|
312
|
+
|
|
313
|
+
const values = new Map();
|
|
314
|
+
const inProgress = new Set();
|
|
315
|
+
|
|
316
|
+
const cellValue = (sheetName, ref) => {
|
|
317
|
+
const key = `${sheetName}!${ref}`;
|
|
318
|
+
if (values.has(key)) return values.get(key);
|
|
319
|
+
if (inProgress.has(key)) throw new Error(`Payslips ${key} is on a chain that comes back to itself`);
|
|
320
|
+
inProgress.add(key);
|
|
321
|
+
const value = computeCell(sheetName, ref, key);
|
|
322
|
+
inProgress.delete(key);
|
|
323
|
+
values.set(key, value);
|
|
324
|
+
return value;
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
function computeCell(sheetName, ref, key) {
|
|
328
|
+
// The Admin calendar is the chain's floor: the generator has just written
|
|
329
|
+
// it, so it is read from the year rather than from the sheet.
|
|
330
|
+
if (sheetName === PAYSLIPS_ADMIN_SHEET) {
|
|
331
|
+
const parts = /^\$?B\$?(\d+)$/.exec(ref);
|
|
332
|
+
if (parts) {
|
|
333
|
+
const row = parseInt(parts[1], 10);
|
|
334
|
+
if (row < ADMIN_CALENDAR_FIRST_ROW || row > ADMIN_CALENDAR_LAST_ROW) {
|
|
335
|
+
throw new Error(`Payslips ${key} is off the Admin calendar, which runs B${ADMIN_CALENDAR_FIRST_ROW}:B${ADMIN_CALENDAR_LAST_ROW}`);
|
|
336
|
+
}
|
|
337
|
+
return yearStartSerial + (row - ADMIN_CALENDAR_FIRST_ROW);
|
|
338
|
+
}
|
|
339
|
+
if (ref.replace(/\$/g, "") === ADMIN_YEAR_END_CELL) return yearEndSerial;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const sheet = sheets.get(sheetName);
|
|
343
|
+
if (!sheet) throw new Error(`Payslips ${key} names a sheet the workbook does not have`);
|
|
344
|
+
const cell = sheet.cells.get(ref.replace(/\$/g, ""));
|
|
345
|
+
if (!cell) throw new Error(`Payslips ${key} is not on the sheet`);
|
|
346
|
+
|
|
347
|
+
// The page's join is a LOOKUP this evaluator does not compute. Its cache
|
|
348
|
+
// is set by the pass that renames the tabs, so it is read from there --
|
|
349
|
+
// checked, because a wrong join moves every figure on the printed page.
|
|
350
|
+
if (sheetName === PAYSLIP_PRINT_SHEET && PRINT_JOIN_CELLS.includes(ref)) {
|
|
351
|
+
return printJoinValue(ref, cell, key, monthTabs);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (cell.formula === null) return cachedValue(cell, key);
|
|
355
|
+
const tokens = tokenize(cell.formula, `Payslips ${key}`);
|
|
356
|
+
return evaluate(parseFormula(tokens, `Payslips ${key}`, cell.formula), sheetName, key, cell.formula);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function cachedValue(cell, key) {
|
|
360
|
+
if (cell.raw === null) throw new Error(`Payslips ${key} holds neither a formula nor a value`);
|
|
361
|
+
if (cell.type === "s") {
|
|
362
|
+
const text = sharedStrings[parseInt(cell.raw, 10)];
|
|
363
|
+
if (text === undefined) throw new Error(`Payslips ${key} names shared string ${cell.raw}, which the workbook does not have`);
|
|
364
|
+
return text;
|
|
365
|
+
}
|
|
366
|
+
if (cell.type === "str" || cell.type === "inlineStr") return cell.raw;
|
|
367
|
+
const number = Number(cell.raw);
|
|
368
|
+
if (!Number.isFinite(number)) throw new Error(`Payslips ${key} holds ${cell.raw}, which is not a number`);
|
|
369
|
+
return number;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function printJoinValue(ref, cell, key, tabs) {
|
|
373
|
+
const value = cachedValue(cell, key);
|
|
374
|
+
if (ref === PAYSLIP_PRINT_CELLS.tab) {
|
|
375
|
+
if (!tabs.includes(value)) throw new Error(`Payslips ${key} joins to ${value}, which is not a month tab`);
|
|
376
|
+
return value;
|
|
377
|
+
}
|
|
378
|
+
if (!Number.isInteger(value) || value < 1) throw new Error(`Payslips ${key} starts the block at ${value}, which is not a row`);
|
|
379
|
+
return value;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function evaluate(node, sheetName, key, formula) {
|
|
383
|
+
switch (node.kind) {
|
|
384
|
+
case "number":
|
|
385
|
+
case "string":
|
|
386
|
+
case "boolean":
|
|
387
|
+
return node.value;
|
|
388
|
+
case "negate":
|
|
389
|
+
return -asNumber(evaluate(node.operand, sheetName, key, formula), key, formula);
|
|
390
|
+
case "binary": {
|
|
391
|
+
const left = asNumber(evaluate(node.left, sheetName, key, formula), key, formula);
|
|
392
|
+
const right = asNumber(evaluate(node.right, sheetName, key, formula), key, formula);
|
|
393
|
+
if (node.operator === "+") return left + right;
|
|
394
|
+
if (node.operator === "-") return left - right;
|
|
395
|
+
if (node.operator === "*") return left * right;
|
|
396
|
+
if (right === 0) throw new Error(`Payslips ${key} reads ${formula}, which divides by zero`);
|
|
397
|
+
return left / right;
|
|
398
|
+
}
|
|
399
|
+
case "ref": {
|
|
400
|
+
const reference = resolveRef(node.text, sheetName);
|
|
401
|
+
return cellValue(reference.sheet, reference.ref);
|
|
402
|
+
}
|
|
403
|
+
case "call":
|
|
404
|
+
return callFunction(node, sheetName, key, formula);
|
|
405
|
+
default:
|
|
406
|
+
throw new Error(`Payslips ${key} reads ${formula}, which this evaluator cannot read`);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function callFunction(node, sheetName, key, formula) {
|
|
411
|
+
const argument = (index) => evaluate(node.args[index], sheetName, key, formula);
|
|
412
|
+
const number = (index) => asNumber(argument(index), key, formula);
|
|
413
|
+
const arity = (expected) => {
|
|
414
|
+
if (node.args.length !== expected) {
|
|
415
|
+
throw new Error(`Payslips ${key} reads ${formula}, whose ${node.name} takes ${node.args.length} arguments, not ${expected}`);
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
switch (node.name) {
|
|
419
|
+
case "DATE": {
|
|
420
|
+
arity(3);
|
|
421
|
+
const months = number(0) * 12 + (number(1) - 1);
|
|
422
|
+
return utcToSerial(new Date(Date.UTC(Math.floor(months / 12), months % 12, number(2))));
|
|
423
|
+
}
|
|
424
|
+
case "YEAR":
|
|
425
|
+
arity(1);
|
|
426
|
+
return serialToUtc(number(0)).getUTCFullYear();
|
|
427
|
+
case "MONTH":
|
|
428
|
+
arity(1);
|
|
429
|
+
return serialToUtc(number(0)).getUTCMonth() + 1;
|
|
430
|
+
case "DAY":
|
|
431
|
+
arity(1);
|
|
432
|
+
return serialToUtc(number(0)).getUTCDate();
|
|
433
|
+
case "WEEKDAY": {
|
|
434
|
+
// Only return type 2 -- Monday 1 through Sunday 7 -- is in the chain,
|
|
435
|
+
// and the other types number the week differently enough that reading
|
|
436
|
+
// one as another silently moves every week end.
|
|
437
|
+
arity(2);
|
|
438
|
+
if (number(1) !== 2) throw new Error(`Payslips ${key} reads ${formula}, whose WEEKDAY return type this evaluator does not know`);
|
|
439
|
+
return ((serialToUtc(number(0)).getUTCDay() + 6) % 7) + 1;
|
|
440
|
+
}
|
|
441
|
+
case "ADDRESS": {
|
|
442
|
+
// ADDRESS(row, column, 1, TRUE, sheet) -- an absolute A1 reference on
|
|
443
|
+
// a named sheet, which is the only form the printed page builds.
|
|
444
|
+
arity(5);
|
|
445
|
+
if (number(2) !== 1) throw new Error(`Payslips ${key} reads ${formula}, whose ADDRESS is not an absolute reference`);
|
|
446
|
+
if (argument(3) !== true) throw new Error(`Payslips ${key} reads ${formula}, whose ADDRESS is not in A1 style`);
|
|
447
|
+
const sheet = argument(4);
|
|
448
|
+
if (typeof sheet !== "string") throw new Error(`Payslips ${key} reads ${formula}, whose ADDRESS names no sheet`);
|
|
449
|
+
return { sheet, ref: `${numberToColumn(number(1))}${number(0)}` };
|
|
450
|
+
}
|
|
451
|
+
case "INDIRECT": {
|
|
452
|
+
arity(1);
|
|
453
|
+
const reference = argument(0);
|
|
454
|
+
if (!isReference(reference)) throw new Error(`Payslips ${key} reads ${formula}, whose INDIRECT is not built from ADDRESS`);
|
|
455
|
+
return cellValue(reference.sheet, reference.ref);
|
|
456
|
+
}
|
|
457
|
+
default:
|
|
458
|
+
throw new Error(`Payslips ${key} reads ${formula}, whose ${node.name} this evaluator does not know`);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function asNumber(value, key, formula) {
|
|
463
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
464
|
+
throw new Error(`Payslips ${key} reads ${formula}, which works on ${JSON.stringify(value)} as though it were a number`);
|
|
465
|
+
}
|
|
466
|
+
return value;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function resolveRef(text, sheetName) {
|
|
470
|
+
const qualified = /^(?:'([^']+)'|([A-Za-z_][A-Za-z0-9_.]*))!(\$?[A-Z]{1,3}\$?\d+)$/.exec(text);
|
|
471
|
+
if (qualified) return { sheet: qualified[1] ?? qualified[2], ref: (qualified[3] || "").replace(/\$/g, "") };
|
|
472
|
+
return { sheet: sheetName, ref: text.replace(/\$/g, "") };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const rolled = new Map(sheetXmls);
|
|
476
|
+
for (const { sheet, ref } of payslipsChainedDateCells(monthTabs)) {
|
|
477
|
+
const value = cellValue(sheet, ref);
|
|
478
|
+
rolled.set(sheet, writeCachedValue(rolled.get(sheet), ref, value));
|
|
479
|
+
}
|
|
480
|
+
return rolled;
|
|
481
|
+
}
|