@diy-accounting-uk/diya-submit 0.1.0 → 0.1.2

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.
@@ -3,259 +3,26 @@
3
3
 
4
4
  // app/services/smallCompanyAccounts.js
5
5
  //
6
- // deriveSmallCompanyAccounts: the figures a small company's FRS 102 section 1A filing takes from
7
- // a loaded Company book: the full profit and loss account (PubP&L), the balance sheet sub-lines
8
- // (PubBalSht), the tangible fixed asset note (PubNotes) and the directors. The prior-year balance
9
- // sheet comes from the book's opening balance. The engine publishes no prior-year profit and loss
10
- // account (its comparative cells are 0), so none is derived here.
6
+ // deriveSmallCompanyAccounts: calculates a loaded Company book and gives the figures a small
7
+ // company's FRS 102 section 1A filing takes (smallCompanyAccountsFromResults).
11
8
 
12
9
  import { calculatedResultsFor } from "@diy-accounting-uk/diya-gl/dist/app/bin/export.js";
13
10
  import { diyaGlToScenario } from "@diy-accounting-uk/diya-gl/dist/app/lib/diya-gl-loader.js";
14
11
  import { loadTaxDataForBook, productOf } from "@diy-accounting-uk/diya-gl/dist/app/lib/product-workbook.js";
15
- import { FIXED_ASSET_CLASSES } from "./smallCompanyAccountsIxbrl.js";
16
-
17
- const BALANCE_TOLERANCE = 0.005;
18
-
19
- // PubNotes columns B to F hold land, plant, fixtures, computer and motor, in that order.
20
- const NOTE_COLUMN_OF_CLASS = {
21
- landBuildings: "B",
22
- plantMachinery: "C",
23
- furnitureFittings: "D",
24
- computerEquipment: "E",
25
- motorVehicles: "F",
26
- };
27
-
28
- const NOTE_ROW_OF_FIELD = {
29
- costAtStart: 8,
30
- additions: 9,
31
- disposals: 10,
32
- depreciationAtStart: 14,
33
- depreciationCharge: 15,
34
- depreciationOnDisposals: 16,
35
- };
36
-
37
- function isoDate(value) {
38
- if (value === undefined || value === null) return null;
39
- return new Date(value).toISOString().slice(0, 10);
40
- }
41
-
42
- function dayBefore(isoDay) {
43
- return new Date(new Date(isoDay).getTime() - 86_400_000).toISOString().slice(0, 10);
44
- }
45
-
46
- function pence(value) {
47
- return Math.round(value * 100) / 100;
48
- }
49
-
50
- function sumValues(object) {
51
- return Object.values(object || {}).reduce((total, value) => total + (value || 0), 0);
52
- }
53
-
54
- /**
55
- * The balance sheet sub-lines, unrounded, from the engine's published balance sheet. Refuses a
56
- * sheet whose net assets (F33) do not equal shareholders' funds (F39).
57
- * @param {Object} sheet - results.PubBalSht
58
- */
59
- export function smallCompanyLinesFromPublishedBalanceSheet(sheet) {
60
- if (!sheet)
61
- throw new Error("The book's product carries no published balance sheet; only a Company (ltd) book answers small company accounts");
62
- const netAssets = sheet.F33 ?? 0;
63
- const shareholdersFunds = sheet.F39 ?? 0;
64
- if (Math.abs(netAssets - shareholdersFunds) > BALANCE_TOLERANCE) {
65
- throw new Error(
66
- `The published balance sheet does not balance: net assets ${pence(netAssets)} against shareholders' funds ${pence(shareholdersFunds)} ` +
67
- `(a difference of ${pence(netAssets - shareholdersFunds)}); a long-term debtor sits on no published line and is the usual cause`,
68
- );
69
- }
70
- return {
71
- fixedAssets: sheet.F6 ?? 0,
72
- stocks: sheet.E10 ?? 0,
73
- debtors: sheet.E11 ?? 0,
74
- cashAtBank: sheet.E12 ?? 0,
75
- tradeCreditors: sheet.E16 ?? 0,
76
- corporationTax: sheet.E17 ?? 0,
77
- otherCreditors: sheet.E18 ?? 0,
78
- creditorsAfterOneYear: sheet.F31 ?? 0,
79
- calledUpShareCapital: sheet.F36 ?? 0,
80
- profitAndLossAccount: shareholdersFunds - (sheet.F36 ?? 0),
81
- capitalAndReserves: shareholdersFunds,
82
- };
83
- }
84
-
85
- /**
86
- * The balance sheet sub-lines, unrounded, from the book's opening balance. Refuses an opening
87
- * balance whose assets do not equal its liabilities and equity.
88
- * @param {Object} opening - scenario.opening_balance, snake_case keys
89
- */
90
- export function smallCompanyLinesFromOpeningBalance(opening = {}) {
91
- const at = (key) => opening[key] || 0;
92
- const fixedAssets = sumValues(opening.fixed_asset_cost) - sumValues(opening.fixed_asset_depreciation);
93
- const stocks = at("stock");
94
- const debtors = at("trade_debtors") + at("long_term_debtors");
95
- const cashAtBank = at("current_account") + at("savings_account") + at("credit_card") + at("cash");
96
- const tradeCreditors = at("trade_creditors");
97
- const corporationTax = at("corporation_tax");
98
- const otherCreditors =
99
- at("net_wages_due") + at("wage_deductions_due") + at("dividends_due") + at("cis_due") + at("vat_due") + at("paye_due");
100
- const creditorsAfterOneYear = at("directors_loan") + at("long_term_creditors");
101
- const calledUpShareCapital = at("share_capital");
102
- const profitAndLossAccount = at("retained_earnings") + at("capital_reserves");
103
- const capitalAndReserves = calledUpShareCapital + profitAndLossAccount;
104
- const netAssets = fixedAssets + stocks + debtors + cashAtBank - tradeCreditors - corporationTax - otherCreditors - creditorsAfterOneYear;
105
- if (Math.abs(netAssets - capitalAndReserves) > BALANCE_TOLERANCE) {
106
- throw new Error(
107
- `The opening balance sheet does not balance: net assets ${pence(netAssets)} against capital and reserves ${pence(capitalAndReserves)} ` +
108
- `(a difference of ${pence(netAssets - capitalAndReserves)})`,
109
- );
110
- }
111
- return {
112
- fixedAssets,
113
- stocks,
114
- debtors,
115
- cashAtBank,
116
- tradeCreditors,
117
- corporationTax,
118
- otherCreditors,
119
- creditorsAfterOneYear,
120
- calledUpShareCapital,
121
- profitAndLossAccount,
122
- capitalAndReserves,
123
- };
124
- }
125
-
126
- /**
127
- * Whole pounds with the filing's identity intact: every sub-line and share capital is rounded,
128
- * capital and reserves is derived from them, and the profit and loss account is the remainder.
129
- */
130
- export function roundSmallCompanyBalanceSheet(lines) {
131
- const fixedAssets = Math.round(lines.fixedAssets);
132
- const stocks = Math.round(lines.stocks);
133
- const debtors = Math.round(lines.debtors);
134
- const cashAtBank = Math.round(lines.cashAtBank);
135
- const tradeCreditors = Math.round(lines.tradeCreditors);
136
- const corporationTax = Math.round(lines.corporationTax);
137
- const otherCreditors = Math.round(lines.otherCreditors);
138
- const creditorsAfterOneYear = Math.round(lines.creditorsAfterOneYear);
139
- const calledUpShareCapital = Math.round(lines.calledUpShareCapital);
140
- const capitalAndReserves =
141
- fixedAssets + stocks + debtors + cashAtBank - tradeCreditors - corporationTax - otherCreditors - creditorsAfterOneYear;
142
- return {
143
- fixedAssets,
144
- stocks,
145
- debtors,
146
- cashAtBank,
147
- tradeCreditors,
148
- corporationTax,
149
- otherCreditors,
150
- creditorsAfterOneYear,
151
- calledUpShareCapital,
152
- profitAndLossAccount: capitalAndReserves - calledUpShareCapital,
153
- capitalAndReserves,
154
- };
155
- }
156
-
157
- /**
158
- * The full profit and loss account for the financial year, in whole pounds, from the engine's
159
- * published account. Turnover, cost of sales, administrative expenses, profit before tax and tax
160
- * are rounded; gross profit, operating profit and the interest line are derived from them so every
161
- * subtotal holds exactly.
162
- * @param {Object} sheet - results["PubP&L"]
163
- */
164
- export function smallCompanyProfitAndLossFromPublishedAccount(sheet) {
165
- if (!sheet)
166
- throw new Error(
167
- "The book's product carries no published profit and loss account; only a Company (ltd) book answers small company accounts",
168
- );
169
- const turnover = Math.round(sheet.F9 ?? 0);
170
- const costOfSales = Math.round(sheet.F16 ?? 0);
171
- const administrativeExpenses = Math.round(sheet.F44 ?? 0);
172
- const profitBeforeTax = Math.round(sheet.F49 ?? 0);
173
- const tax = Math.round(sheet.F50 ?? 0);
174
- const grossProfit = turnover - costOfSales;
175
- const operatingProfit = grossProfit - administrativeExpenses;
176
- return {
177
- turnover,
178
- costOfSales,
179
- grossProfit,
180
- administrativeExpenses,
181
- operatingProfit,
182
- interestReceivable: profitBeforeTax - operatingProfit,
183
- profitBeforeTax,
184
- tax,
185
- profit: profitBeforeTax - tax,
186
- };
187
- }
188
-
189
- /**
190
- * The tangible fixed asset note, per asset class that holds anything, from the engine's published
191
- * notes, in whole pounds with each class's closing net book value rounded from its own movements.
192
- * @param {Object} sheet - results.PubNotes
193
- */
194
- export function fixedAssetNoteFromPublishedNotes(sheet) {
195
- const note = {};
196
- for (const className of FIXED_ASSET_CLASSES) {
197
- const column = NOTE_COLUMN_OF_CLASS[className];
198
- const figures = {};
199
- for (const [field, row] of Object.entries(NOTE_ROW_OF_FIELD)) figures[field] = Math.round(sheet?.[`${column}${row}`] ?? 0);
200
- if (Object.values(figures).some((value) => value !== 0)) note[className] = figures;
201
- }
202
- return note;
203
- }
12
+ import { smallCompanyAccountsFromResults } from "./smallCompanyAccountsFromResults.js";
204
13
 
205
14
  /**
206
15
  * derive_small_company_accounts: the figures a small company accounts filing takes, from the
207
16
  * session's loaded book.
208
17
  * @param {Object} session
18
+ * @param {Object} [options]
19
+ * @param {Object} [options.priorYearProfitAndLoss] - the prior year's profit and loss lines, whole pounds, when the company has them; the book publishes none
209
20
  */
210
- export async function deriveSmallCompanyAccounts(session) {
21
+ export async function deriveSmallCompanyAccounts(session, { priorYearProfitAndLoss } = {}) {
211
22
  if (!session.book || !session.lines) throw new Error("No book is loaded. Call open_book first.");
212
23
  const { book, lines } = session;
213
- const info = book.documentInfo ?? {};
214
- const entity = book.entityInformation ?? {};
215
- const periodStart = isoDate(info.periodCoveredStart);
216
- const periodEnd = isoDate(info.periodCoveredEnd);
217
- if (!periodStart || !periodEnd) throw new Error("The book's documentInfo carries no periodCoveredStart and periodCoveredEnd");
218
-
219
24
  const taxData = await loadTaxDataForBook(book);
220
25
  const results = calculatedResultsFor(book, lines, taxData);
221
26
  const scenario = diyaGlToScenario(book, lines, productOf(book));
222
-
223
- const current = smallCompanyLinesFromPublishedBalanceSheet(results.PubBalSht);
224
- const prior = smallCompanyLinesFromOpeningBalance(scenario.opening_balance);
225
- const currentYear = roundSmallCompanyBalanceSheet(current);
226
- const priorYear = roundSmallCompanyBalanceSheet(prior);
227
- const profitAndLoss = smallCompanyProfitAndLossFromPublishedAccount(results["PubP&L"]);
228
- const fixedAssetNote = fixedAssetNoteFromPublishedNotes(results.PubNotes);
229
-
230
- const capitalReserve = scenario.opening_balance?.capital_reserves || 0;
231
- const notes = [
232
- "Whole pounds: capital and reserves is derived from the rounded sub-lines, and the profit and loss account is the remainder after share capital.",
233
- "The interest line is profit before tax less operating profit, so every profit and loss subtotal holds after rounding.",
234
- "The average number of employees is the count of the book's employees table; confirm it before filing.",
235
- "The book publishes no prior-year profit and loss account: supply the comparatives when the company has them, or leave them out.",
236
- "The principal activity and the accounting policies text are typed on the page; the book holds neither.",
237
- ];
238
- if (capitalReserve)
239
- notes.push(
240
- `A capital reserve of ${pence(capitalReserve)} is folded into the profit and loss account; the sub-line set has no other reserve line.`,
241
- );
242
-
243
- return {
244
- companyNumber: entity["diya-gl:companyNumber"] ?? null,
245
- companyName: entity.organizationIdentifier ?? null,
246
- periodStart,
247
- periodEnd,
248
- priorBalanceSheetDate: dayBefore(periodStart),
249
- averageNumberOfEmployees: (book.employees ?? []).length,
250
- directors: (book.directors ?? []).map((director) => director.name).filter(Boolean),
251
- directorName: book.directors?.[0]?.name ?? null,
252
- profitAndLoss: { currentYear: profitAndLoss },
253
- balanceSheet: { currentYear, priorYear },
254
- fixedAssetNote,
255
- derivation: {
256
- currentYear: { sheet: "PubBalSht", lines: Object.fromEntries(Object.entries(current).map(([key, value]) => [key, pence(value)])) },
257
- priorYear: { sheet: "OpenAccounts", lines: Object.fromEntries(Object.entries(prior).map(([key, value]) => [key, pence(value)])) },
258
- },
259
- notes,
260
- };
27
+ return smallCompanyAccountsFromResults(book, results, scenario, { priorYearProfitAndLoss });
261
28
  }
@@ -0,0 +1,333 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // app/services/smallCompanyAccountsFromResults.js
5
+ //
6
+ // The figures a small company's FRS 102 section 1A filing takes from a loaded Company book's
7
+ // calculated results: the full profit and loss account (PubP&L), the balance sheet sub-lines
8
+ // (PubBalSht), the tangible fixed asset note (PubNotes) and the directors. The prior-year balance
9
+ // sheet comes from the book's opening balance. The engine publishes no prior-year profit and loss
10
+ // account (its comparative cells are 0), so none is derived here. The module has no fs, so the
11
+ // browser's books bundle runs it too.
12
+
13
+ import { smallCompanyProfitAndLossFromPublishedAccount } from "./ct600Figures.js";
14
+ import { directorsAdvancesFrom } from "./microEntityAccountsFromResults.js";
15
+
16
+ const BALANCE_TOLERANCE = 0.005;
17
+
18
+ // PubNotes columns B to F hold land, plant, fixtures, computer and motor, in that order.
19
+ const NOTE_COLUMN_OF_CLASS = {
20
+ landBuildings: "B",
21
+ plantMachinery: "C",
22
+ furnitureFittings: "D",
23
+ computerEquipment: "E",
24
+ motorVehicles: "F",
25
+ };
26
+
27
+ const NOTE_ROW_OF_FIELD = {
28
+ costAtStart: 8,
29
+ additions: 9,
30
+ disposals: 10,
31
+ depreciationAtStart: 14,
32
+ depreciationCharge: 15,
33
+ depreciationOnDisposals: 16,
34
+ };
35
+
36
+ function isoDate(value) {
37
+ if (value === undefined || value === null) return null;
38
+ return new Date(value).toISOString().slice(0, 10);
39
+ }
40
+
41
+ function dayBefore(isoDay) {
42
+ return new Date(new Date(isoDay).getTime() - 86_400_000).toISOString().slice(0, 10);
43
+ }
44
+
45
+ function pence(value) {
46
+ return Math.round(value * 100) / 100;
47
+ }
48
+
49
+ function sumValues(object) {
50
+ return Object.values(object || {}).reduce((total, value) => total + (value || 0), 0);
51
+ }
52
+
53
+ /**
54
+ * The balance sheet sub-lines, unrounded, from the engine's published balance sheet. Refuses a
55
+ * sheet whose net assets (F33) do not equal shareholders' funds (F39).
56
+ * @param {Object} sheet - results.PubBalSht
57
+ */
58
+ export function smallCompanyLinesFromPublishedBalanceSheet(sheet) {
59
+ if (!sheet)
60
+ throw new Error("The book's product carries no published balance sheet; only a Company (ltd) book answers small company accounts");
61
+ const netAssets = sheet.F33 ?? 0;
62
+ const shareholdersFunds = sheet.F39 ?? 0;
63
+ if (Math.abs(netAssets - shareholdersFunds) > BALANCE_TOLERANCE) {
64
+ throw new Error(
65
+ `The published balance sheet does not balance: net assets ${pence(netAssets)} against shareholders' funds ${pence(shareholdersFunds)} ` +
66
+ `(a difference of ${pence(netAssets - shareholdersFunds)}); a long-term debtor sits on no published line and is the usual cause`,
67
+ );
68
+ }
69
+ // An overdrawn director's loan account (E29 below 0) is a debtor, not a negative creditor.
70
+ const owedByDirectors = Math.max(0, -(sheet.E29 ?? 0));
71
+ return {
72
+ fixedAssets: sheet.F6 ?? 0,
73
+ stocks: sheet.E10 ?? 0,
74
+ debtors: (sheet.E11 ?? 0) + owedByDirectors,
75
+ tradeDebtors: sheet.E11 ?? 0,
76
+ otherDebtors: 0,
77
+ amountsOwedByDirectors: owedByDirectors,
78
+ cashAtBank: sheet.E12 ?? 0,
79
+ bankLoansOverdrafts: sheet.E19 ?? 0,
80
+ tradeCreditors: sheet.E16 ?? 0,
81
+ corporationTax: sheet.E17 ?? 0,
82
+ taxationSocialSecurity: sheet.E18 ?? 0,
83
+ otherCreditors: 0,
84
+ creditorsAfterOneYear: (sheet.F31 ?? 0) + owedByDirectors,
85
+ amountsOwedToDirectors: Math.max(0, sheet.E29 ?? 0),
86
+ calledUpShareCapital: sheet.F36 ?? 0,
87
+ profitAndLossAccount: shareholdersFunds - (sheet.F36 ?? 0),
88
+ capitalAndReserves: shareholdersFunds,
89
+ };
90
+ }
91
+
92
+ /**
93
+ * The balance sheet sub-lines, unrounded, from the book's opening balance. Refuses an opening
94
+ * balance whose assets do not equal its liabilities and equity.
95
+ * @param {Object} opening - scenario.opening_balance, snake_case keys
96
+ */
97
+ export function smallCompanyLinesFromOpeningBalance(opening = {}) {
98
+ const at = (key) => opening[key] || 0;
99
+ const fixedAssets = sumValues(opening.fixed_asset_cost) - sumValues(opening.fixed_asset_depreciation);
100
+ const stocks = at("stock");
101
+ const tradeDebtors = at("trade_debtors");
102
+ const otherDebtors = at("long_term_debtors");
103
+ const amountsOwedByDirectors = Math.max(0, -at("directors_loan"));
104
+ const debtors = tradeDebtors + otherDebtors + amountsOwedByDirectors;
105
+ const statementAccounts = at("current_account") + at("savings_account") + at("credit_card");
106
+ const bankLoansOverdrafts = statementAccounts < 0 ? -statementAccounts : 0;
107
+ const cashAtBank = (statementAccounts < 0 ? 0 : statementAccounts) + at("cash");
108
+ const tradeCreditors = at("trade_creditors");
109
+ const corporationTax = at("corporation_tax");
110
+ const taxationSocialSecurity = at("paye_due") + at("vat_due") + at("cis_due");
111
+ const otherCreditors = at("net_wages_due") + at("wage_deductions_due") + at("dividends_due");
112
+ const amountsOwedToDirectors = Math.max(0, at("directors_loan"));
113
+ const creditorsAfterOneYear = amountsOwedToDirectors + at("long_term_creditors");
114
+ const calledUpShareCapital = at("share_capital");
115
+ const profitAndLossAccount = at("retained_earnings") + at("capital_reserves");
116
+ const capitalAndReserves = calledUpShareCapital + profitAndLossAccount;
117
+ const netAssets =
118
+ fixedAssets +
119
+ stocks +
120
+ debtors +
121
+ cashAtBank -
122
+ bankLoansOverdrafts -
123
+ tradeCreditors -
124
+ corporationTax -
125
+ taxationSocialSecurity -
126
+ otherCreditors -
127
+ creditorsAfterOneYear;
128
+ if (Math.abs(netAssets - capitalAndReserves) > BALANCE_TOLERANCE) {
129
+ throw new Error(
130
+ `The opening balance sheet does not balance: net assets ${pence(netAssets)} against capital and reserves ${pence(capitalAndReserves)} ` +
131
+ `(a difference of ${pence(netAssets - capitalAndReserves)})`,
132
+ );
133
+ }
134
+ return {
135
+ fixedAssets,
136
+ stocks,
137
+ debtors,
138
+ tradeDebtors,
139
+ otherDebtors,
140
+ amountsOwedByDirectors,
141
+ cashAtBank,
142
+ bankLoansOverdrafts,
143
+ tradeCreditors,
144
+ corporationTax,
145
+ taxationSocialSecurity,
146
+ otherCreditors,
147
+ creditorsAfterOneYear,
148
+ amountsOwedToDirectors,
149
+ calledUpShareCapital,
150
+ profitAndLossAccount,
151
+ capitalAndReserves,
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Whole pounds with the filing's identity intact: every sub-line and share capital is rounded,
157
+ * capital and reserves is derived from them, and the profit and loss account is the remainder.
158
+ */
159
+ export function roundSmallCompanyBalanceSheet(lines) {
160
+ const fixedAssets = Math.round(lines.fixedAssets);
161
+ const stocks = Math.round(lines.stocks);
162
+ const debtors = Math.round(lines.debtors);
163
+ const cashAtBank = Math.round(lines.cashAtBank);
164
+ const bankLoansOverdrafts = Math.round(lines.bankLoansOverdrafts);
165
+ const tradeCreditors = Math.round(lines.tradeCreditors);
166
+ const corporationTax = Math.round(lines.corporationTax);
167
+ const taxationSocialSecurity = Math.round(lines.taxationSocialSecurity);
168
+ const otherCreditors = Math.round(lines.otherCreditors);
169
+ const creditorsAfterOneYear = Math.round(lines.creditorsAfterOneYear);
170
+ // The debtors split adds up to the rounded debtors, and the directors' loan stays within the creditors it splits.
171
+ const otherDebtors = Math.round(lines.otherDebtors ?? 0);
172
+ const amountsOwedByDirectors = Math.round(lines.amountsOwedByDirectors ?? 0);
173
+ const tradeDebtors = debtors - otherDebtors - amountsOwedByDirectors;
174
+ const amountsOwedToDirectors = Math.min(Math.round(lines.amountsOwedToDirectors ?? 0), creditorsAfterOneYear);
175
+ const calledUpShareCapital = Math.round(lines.calledUpShareCapital);
176
+ const capitalAndReserves =
177
+ fixedAssets +
178
+ stocks +
179
+ debtors +
180
+ cashAtBank -
181
+ bankLoansOverdrafts -
182
+ tradeCreditors -
183
+ corporationTax -
184
+ taxationSocialSecurity -
185
+ otherCreditors -
186
+ creditorsAfterOneYear;
187
+ return {
188
+ fixedAssets,
189
+ stocks,
190
+ debtors,
191
+ tradeDebtors,
192
+ otherDebtors,
193
+ amountsOwedByDirectors,
194
+ cashAtBank,
195
+ bankLoansOverdrafts,
196
+ tradeCreditors,
197
+ corporationTax,
198
+ taxationSocialSecurity,
199
+ otherCreditors,
200
+ creditorsAfterOneYear,
201
+ amountsOwedToDirectors,
202
+ calledUpShareCapital,
203
+ profitAndLossAccount: capitalAndReserves - calledUpShareCapital,
204
+ capitalAndReserves,
205
+ };
206
+ }
207
+
208
+ /**
209
+ * The tangible fixed asset note, per asset class that holds anything, from the engine's published
210
+ * notes, in whole pounds with each class's closing net book value rounded from its own movements.
211
+ * @param {Object} sheet - results.PubNotes
212
+ */
213
+ export function fixedAssetNoteFromPublishedNotes(sheet) {
214
+ const note = {};
215
+ for (const className of Object.keys(NOTE_COLUMN_OF_CLASS)) {
216
+ const column = NOTE_COLUMN_OF_CLASS[className];
217
+ const figures = {};
218
+ for (const [field, row] of Object.entries(NOTE_ROW_OF_FIELD)) figures[field] = Math.round(sheet?.[`${column}${row}`] ?? 0);
219
+ if (Object.values(figures).some((value) => value !== 0)) note[className] = figures;
220
+ }
221
+ return note;
222
+ }
223
+
224
+ /**
225
+ * The Format 2 profit and loss lines (by nature), in whole pounds, from the engine's monthly and
226
+ * published profit and loss sheets. Turnover, operating profit, profit before tax and tax are
227
+ * rounded from the published figures; the cost lines are rounded from the monthly sheet and the
228
+ * remaining operating expenses line takes the rounding, so every identity holds to the pound. The
229
+ * book's stock movement sits inside raw materials, and its grants inside turnover, so the change
230
+ * in stocks, own work capitalised and other operating income are 0; its loan interest sits inside
231
+ * administrative expenses, so interest payable is 0.
232
+ * @param {Object} results - calculatedResultsFor output with MnthP&L and PubP&L
233
+ */
234
+ export function smallCompanyFormat2ProfitAndLossFromResults(results) {
235
+ const published = results["PubP&L"];
236
+ const monthly = results["MnthP&L"];
237
+ if (!published || !monthly)
238
+ throw new Error(
239
+ "The book's product carries no published profit and loss account; only a Company (ltd) book answers small company accounts",
240
+ );
241
+ const at = (cell) => monthly[cell] ?? 0;
242
+ const turnover = Math.round(published.F9 ?? 0);
243
+ const rawMaterialsConsumables = Math.round(at("B11"));
244
+ const otherExternalCharges = Math.round(at("B12") + at("B13"));
245
+ const staffCosts = Math.round(at("B18") + at("B19") + at("B20"));
246
+ const depreciation = Math.round(at("B38") + at("B40"));
247
+ const operatingProfit = Math.round(published.F46 ?? 0);
248
+ const profitBeforeTax = Math.round(published.F49 ?? 0);
249
+ const tax = Math.round(published.F50 ?? 0);
250
+ const otherOperatingExpenses = turnover - operatingProfit - rawMaterialsConsumables - otherExternalCharges - staffCosts - depreciation;
251
+ return {
252
+ turnover,
253
+ changeInStocks: 0,
254
+ ownWorkCapitalised: 0,
255
+ otherOperatingIncome: 0,
256
+ rawMaterialsConsumables,
257
+ otherExternalCharges,
258
+ staffCosts,
259
+ depreciation,
260
+ otherOperatingExpenses,
261
+ operatingProfit,
262
+ interestReceivable: profitBeforeTax - operatingProfit,
263
+ interestPayable: 0,
264
+ profitBeforeTax,
265
+ tax,
266
+ profit: profitBeforeTax - tax,
267
+ };
268
+ }
269
+
270
+ /**
271
+ * The figures a small company accounts filing takes, from a loaded Company book and its
272
+ * calculated results. Pure, so the browser's books bundle runs it too.
273
+ * @param {Object} book
274
+ * @param {Object} results - calculatedResultsFor output
275
+ * @param {Object} scenario - diyaGlToScenario output
276
+ * @param {Object} [options]
277
+ * @param {Object} [options.priorYearProfitAndLoss]
278
+ * @param {boolean} [options.requireDirectorsNote] - true (the default) throws when the book owes the company a director's loan and names no director; false leaves the note out
279
+ */
280
+ export function smallCompanyAccountsFromResults(book, results, scenario, { priorYearProfitAndLoss, requireDirectorsNote = true } = {}) {
281
+ const info = book.documentInfo ?? {};
282
+ const entity = book.entityInformation ?? {};
283
+ const periodStart = isoDate(info.periodCoveredStart);
284
+ const periodEnd = isoDate(info.periodCoveredEnd);
285
+ if (!periodStart || !periodEnd) throw new Error("The book's documentInfo carries no periodCoveredStart and periodCoveredEnd");
286
+
287
+ const current = smallCompanyLinesFromPublishedBalanceSheet(results.PubBalSht);
288
+ const prior = smallCompanyLinesFromOpeningBalance(scenario.opening_balance);
289
+ const currentYear = roundSmallCompanyBalanceSheet(current);
290
+ const priorYear = roundSmallCompanyBalanceSheet(prior);
291
+ const profitAndLoss = smallCompanyProfitAndLossFromPublishedAccount(results["PubP&L"]);
292
+ const fixedAssetNote = fixedAssetNoteFromPublishedNotes(results.PubNotes);
293
+
294
+ const capitalReserve = scenario.opening_balance?.capital_reserves || 0;
295
+ const notes = [
296
+ "Whole pounds: capital and reserves is derived from the rounded sub-lines, and the profit and loss account is the remainder after share capital.",
297
+ "The interest line is profit before tax less operating profit, so every profit and loss subtotal holds after rounding.",
298
+ "The average number of employees is the count of the book's employees table; confirm it before filing.",
299
+ priorYearProfitAndLoss
300
+ ? "The prior year's profit and loss account is the one supplied with the request; the book publishes none."
301
+ : "The book publishes no prior-year profit and loss account: supply the comparatives when the company has them, or leave them out.",
302
+ "The principal activity and the accounting policies text are typed on the page; the book holds neither.",
303
+ ];
304
+ if (currentYear.amountsOwedByDirectors > 0 || priorYear.amountsOwedByDirectors > 0)
305
+ notes.push(
306
+ "The director's loan account is overdrawn, so it is a debtor. Add the interest rate and the main conditions of the advance to the advances to directors note; the book holds neither.",
307
+ );
308
+ if (capitalReserve)
309
+ notes.push(
310
+ `A capital reserve of ${pence(capitalReserve)} is folded into the profit and loss account; the sub-line set has no other reserve line.`,
311
+ );
312
+
313
+ return {
314
+ companyNumber: entity["diya-gl:companyNumber"] ?? null,
315
+ companyName: entity.organizationIdentifier ?? null,
316
+ periodStart,
317
+ periodEnd,
318
+ priorBalanceSheetDate: dayBefore(periodStart),
319
+ averageNumberOfEmployees: (book.employees ?? []).length,
320
+ directors: (book.directors ?? []).map((director) => director.name).filter(Boolean),
321
+ directorName: book.directors?.[0]?.name ?? null,
322
+ ...directorsAdvancesFrom(currentYear, priorYear, book.directors?.[0]?.name, { requireNote: requireDirectorsNote }),
323
+ profitAndLoss: { currentYear: profitAndLoss, ...(priorYearProfitAndLoss ? { priorYear: priorYearProfitAndLoss } : {}) },
324
+ profitAndLossFormat2: { currentYear: smallCompanyFormat2ProfitAndLossFromResults(results) },
325
+ balanceSheet: { currentYear, priorYear },
326
+ fixedAssetNote,
327
+ derivation: {
328
+ currentYear: { sheet: "PubBalSht", lines: Object.fromEntries(Object.entries(current).map(([key, value]) => [key, pence(value)])) },
329
+ priorYear: { sheet: "OpenAccounts", lines: Object.fromEntries(Object.entries(prior).map(([key, value]) => [key, pence(value)])) },
330
+ },
331
+ notes,
332
+ };
333
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diy-accounting-uk/diya-submit",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "MCP server that opens a diya-gl book, derives filing figures and drives DIY Accounting Submit's HMRC and Companies House submissions",
5
5
  "type": "module",
6
6
  "license": "LicenseRef-PolyForm-Internal-Use-1.0.0",
@@ -33,16 +33,21 @@
33
33
  "test:system": "vitest run --config vitest.system.config.js"
34
34
  },
35
35
  "dependencies": {
36
- "@diy-accounting-uk/diya-gl": "1.2.49",
37
- "@modelcontextprotocol/sdk": "1.31.0",
38
- "happy-dom": "20.9.0",
39
- "zod": "^3.25.0"
36
+ "@diy-accounting-uk/diya-gl": "1.2.73",
37
+ "@modelcontextprotocol/sdk": "1.32.2",
38
+ "happy-dom": "21.0.4",
39
+ "zod": "^4.6.7"
40
40
  },
41
41
  "devDependencies": {
42
- "vitest": "^4.1.11"
42
+ "vitest": "^5.0.5"
43
43
  },
44
44
  "overrides": {
45
45
  "smol-toml": "^1.9.0",
46
- "source-map-js": "^1.2.2"
46
+ "source-map-js": "^1.2.2",
47
+ "qs": "^6.16.1",
48
+ "fast-uri": "^3.1.9",
49
+ "body-parser": "^2.4.0",
50
+ "ip-address": "^10.7.4",
51
+ "@hono/node-server": "^2.1.3"
47
52
  }
48
53
  }