@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.
@@ -1,224 +1,74 @@
1
1
  // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
2
  // Copyright (C) 2006-2026 DIY Accounting Limited
3
3
 
4
+ // @capability MCP-04 Derive micro-entity accounts figures for Companies House filing
5
+ // - **Use when:** a Company (ltd) book's FRS 105 balance-sheet lines are needed before a Companies House accounts filing.
6
+ // - **Does:** deriveMicroEntityAccounts in app/services/microEntityAccounts.js reads the current year from the engine's published balance sheet, PubBalSht. It reads the prior year from the book's opening balance. It checks each sheet balances before rounding both years to whole pounds. mcp/lib/accounts-tools.js re-exports it for the derive_micro_entity_accounts tool; DATA-52's nightly company book pull imports the same function.
7
+ // - **Run:** no command; see Does and Entry
8
+ // - **Entry:** `app/services/microEntityAccounts.js:deriveMicroEntityAccounts`
9
+ // - **Files:** app/services/microEntityAccounts.js, mcp/lib/accounts-tools.js, mcp/test/accounts-tools.test.js
10
+ // - **Keywords:** derive_micro_entity_accounts, frs 105, balance sheet, companies house, micro-entity, pubbalsht, accounts filing
11
+ // - **Related:** MCP-03, MCP-08, DATA-52
12
+ // @end-capability
13
+
4
14
  // app/services/microEntityAccounts.js
5
15
  //
6
- // deriveMicroEntityAccounts: the seven FRS 105 balance-sheet lines the
7
- // accounts filing takes, for the current year from the Ltd engine's
8
- // published balance sheet (PubBalSht) and for the prior year from the
9
- // book's opening balance, rounded to whole pounds so the filing endpoint's
10
- // own check (capital and reserves equals net assets) holds. The filing
11
- // maps seven FRS 105 lines from book balances; nothing here computes a
12
- // balance the engine has not already computed.
16
+ // deriveMicroEntityAccounts: calculates a loaded Company book and gives the figures the micro-entity
17
+ // accounts filing takes (microEntityAccountsFromResults).
13
18
 
14
19
  import { calculatedResultsFor } from "@diy-accounting-uk/diya-gl/dist/app/bin/export.js";
15
20
  import { diyaGlToScenario } from "@diy-accounting-uk/diya-gl/dist/app/lib/diya-gl-loader.js";
16
21
  import { loadTaxDataForBook, productOf } from "@diy-accounting-uk/diya-gl/dist/app/lib/product-workbook.js";
17
-
18
- export const BALANCE_SHEET_LINES = [
19
- "fixedAssets",
20
- "currentAssets",
21
- "creditorsWithinOneYear",
22
- "creditorsAfterOneYear",
23
- "calledUpShareCapital",
24
- "profitAndLossAccount",
25
- "capitalAndReserves",
26
- ];
27
-
28
- const BALANCE_TOLERANCE = 0.005;
29
-
30
- function isoDate(value) {
31
- if (value === undefined || value === null) return null;
32
- return new Date(value).toISOString().slice(0, 10);
33
- }
34
-
35
- function dayBefore(isoDay) {
36
- return new Date(new Date(isoDay).getTime() - 86_400_000).toISOString().slice(0, 10);
37
- }
38
-
39
- function pence(value) {
40
- return Math.round(value * 100) / 100;
41
- }
42
-
43
- function requireLoaded(session) {
44
- if (!session.book || !session.lines) {
45
- throw new Error("No book is loaded. Call open_book first.");
46
- }
47
- }
48
-
49
- /**
50
- * The seven lines, unrounded, from the engine's published balance sheet.
51
- * Refuses a sheet whose own net assets (F33) do not equal shareholders'
52
- * funds (F39).
53
- * @param {Object} sheet - results.PubBalSht
54
- */
55
- export function linesFromPublishedBalanceSheet(sheet) {
56
- if (!sheet)
57
- throw new Error("The book's product carries no published balance sheet; only a Company (ltd) book answers micro-entity accounts");
58
- const netAssets = sheet.F33 ?? 0;
59
- const shareholdersFunds = sheet.F39 ?? 0;
60
- if (Math.abs(netAssets - shareholdersFunds) > BALANCE_TOLERANCE) {
61
- throw new Error(
62
- `The published balance sheet does not balance: net assets ${pence(netAssets)} against shareholders' funds ${pence(shareholdersFunds)} ` +
63
- `(a difference of ${pence(netAssets - shareholdersFunds)}); a long-term debtor sits on no published line and is the usual cause`,
64
- );
65
- }
66
- return {
67
- fixedAssets: sheet.F6 ?? 0,
68
- currentAssets: sheet.E13 ?? 0,
69
- creditorsWithinOneYear: sheet.E20 ?? 0,
70
- creditorsAfterOneYear: sheet.F31 ?? 0,
71
- calledUpShareCapital: sheet.F36 ?? 0,
72
- profitAndLossAccount: shareholdersFunds - (sheet.F36 ?? 0),
73
- capitalAndReserves: shareholdersFunds,
74
- };
75
- }
76
-
77
- function sumValues(object) {
78
- return Object.values(object || {}).reduce((total, value) => total + (value || 0), 0);
79
- }
80
-
81
- /**
82
- * The three headline P&L figures for the financial year, from the engine's published profit
83
- * and loss account. Turnover and profit are rounded to whole pounds first and costs is their
84
- * difference, so turnover minus costs equals profit exactly rather than drifting from separate
85
- * roundings of cost of sales, administrative expenses and tax.
86
- * @param {Object} sheet - results["PubP&L"]
87
- */
88
- export function profitAndLossFromPublishedAccount(sheet) {
89
- if (!sheet)
90
- throw new Error(
91
- "The book's product carries no published profit and loss account; only a Company (ltd) book answers micro-entity accounts",
92
- );
93
- const turnover = Math.round(sheet.F9 ?? 0);
94
- const profit = Math.round(sheet.F51 ?? 0);
95
- return { turnover, costs: turnover - profit, profit };
96
- }
22
+ import { microEntityAccountsFromResults, cashAtBankFromResults } from "./microEntityAccountsFromResults.js";
97
23
 
98
24
  /**
99
- * The seven lines, unrounded, from the book's opening balance (the figures
100
- * the engine's OpenAccounts sheet shows). Refuses an opening balance whose
101
- * assets do not equal its liabilities and equity.
102
- * @param {Object} opening - scenario.opening_balance, snake_case keys
25
+ * The figures the accounts filing takes and the cash held across the bank nominal accounts, from
26
+ * one calculation of the session's loaded book.
27
+ * @param {Object} session
28
+ * @param {Object} [options]
29
+ * @param {boolean} [options.requireDirectorsNote] - false lets a book with an overdrawn director's loan and no director give its figures without the note
103
30
  */
104
- export function linesFromOpeningBalance(opening = {}) {
105
- const at = (key) => opening[key] || 0;
106
- const fixedAssets = sumValues(opening.fixed_asset_cost) - sumValues(opening.fixed_asset_depreciation);
107
- const currentAssets =
108
- at("stock") +
109
- at("trade_debtors") +
110
- at("current_account") +
111
- at("savings_account") +
112
- at("credit_card") +
113
- at("cash") +
114
- at("long_term_debtors");
115
- const creditorsWithinOneYear =
116
- at("trade_creditors") +
117
- at("net_wages_due") +
118
- at("wage_deductions_due") +
119
- at("dividends_due") +
120
- at("corporation_tax") +
121
- at("cis_due") +
122
- at("vat_due") +
123
- at("paye_due");
124
- const creditorsAfterOneYear = at("directors_loan") + at("long_term_creditors");
125
- const calledUpShareCapital = at("share_capital");
126
- const profitAndLossAccount = at("retained_earnings") + at("capital_reserves");
127
- const capitalAndReserves = calledUpShareCapital + profitAndLossAccount;
128
- const netAssets = fixedAssets + currentAssets - creditorsWithinOneYear - creditorsAfterOneYear;
129
- if (Math.abs(netAssets - capitalAndReserves) > BALANCE_TOLERANCE) {
130
- throw new Error(
131
- `The opening balance sheet does not balance: net assets ${pence(netAssets)} against capital and reserves ${pence(capitalAndReserves)} ` +
132
- `(a difference of ${pence(netAssets - capitalAndReserves)})`,
133
- );
31
+ export async function deriveCompanyBookFigures(session, { requireDirectorsNote = true } = {}) {
32
+ if (!session.book || !session.lines) {
33
+ throw new Error("No book is loaded. Call open_book first.");
134
34
  }
35
+ const { book, lines } = session;
36
+ const taxData = await loadTaxDataForBook(book);
37
+ const results = calculatedResultsFor(book, lines, taxData);
38
+ const scenario = diyaGlToScenario(book, lines, productOf(book));
135
39
  return {
136
- fixedAssets,
137
- currentAssets,
138
- creditorsWithinOneYear,
139
- creditorsAfterOneYear,
140
- calledUpShareCapital,
141
- profitAndLossAccount,
142
- capitalAndReserves,
143
- };
144
- }
145
-
146
- /**
147
- * Whole pounds with the filing's identity intact: the four asset and
148
- * liability lines and share capital are rounded, capital and reserves is
149
- * derived from the four, and the profit and loss account is the remainder.
150
- */
151
- export function roundForFiling(lines) {
152
- const fixedAssets = Math.round(lines.fixedAssets);
153
- const currentAssets = Math.round(lines.currentAssets);
154
- const creditorsWithinOneYear = Math.round(lines.creditorsWithinOneYear);
155
- const creditorsAfterOneYear = Math.round(lines.creditorsAfterOneYear);
156
- const calledUpShareCapital = Math.round(lines.calledUpShareCapital);
157
- const capitalAndReserves = fixedAssets + currentAssets - creditorsWithinOneYear - creditorsAfterOneYear;
158
- return {
159
- fixedAssets,
160
- currentAssets,
161
- creditorsWithinOneYear,
162
- creditorsAfterOneYear,
163
- calledUpShareCapital,
164
- profitAndLossAccount: capitalAndReserves - calledUpShareCapital,
165
- capitalAndReserves,
40
+ accounts: microEntityAccountsFromResults(book, results, scenario, { requireDirectorsNote }),
41
+ cashAtBank: cashAtBankFromResults(results),
166
42
  };
167
43
  }
168
44
 
169
- function rounded(lines) {
170
- return Object.fromEntries(Object.entries(lines).map(([key, value]) => [key, pence(value)]));
171
- }
172
-
173
45
  /**
174
46
  * derive_micro_entity_accounts: the figures the accounts filing takes, from
175
47
  * the session's loaded book.
176
48
  * @param {Object} session
177
49
  */
178
50
  export async function deriveMicroEntityAccounts(session) {
179
- requireLoaded(session);
180
- const { book, lines } = session;
181
- const info = book.documentInfo ?? {};
182
- const entity = book.entityInformation ?? {};
183
- const periodStart = isoDate(info.periodCoveredStart);
184
- const periodEnd = isoDate(info.periodCoveredEnd);
185
- if (!periodStart || !periodEnd) throw new Error("The book's documentInfo carries no periodCoveredStart and periodCoveredEnd");
186
-
187
- const taxData = await loadTaxDataForBook(book);
188
- const results = calculatedResultsFor(book, lines, taxData);
189
- const scenario = diyaGlToScenario(book, lines, productOf(book));
190
-
191
- const current = linesFromPublishedBalanceSheet(results.PubBalSht);
192
- const prior = linesFromOpeningBalance(scenario.opening_balance);
193
- const currentYear = roundForFiling(current);
194
- const priorYear = roundForFiling(prior);
195
- const profitAndLoss = profitAndLossFromPublishedAccount(results["PubP&L"]);
196
-
197
- const capitalReserve = scenario.opening_balance?.capital_reserves || 0;
198
- const notes = [
199
- "Whole pounds: capital and reserves is derived from the rounded assets and creditors, and the profit and loss account is the remainder after share capital.",
200
- "The average number of employees is the count of the book's employees table; confirm it before filing.",
201
- ];
202
- if (capitalReserve)
203
- notes.push(
204
- `A capital reserve of ${pence(capitalReserve)} is folded into the profit and loss account; the seven-line set has no other reserve line.`,
205
- );
51
+ return (await deriveCompanyBookFigures(session)).accounts;
52
+ }
206
53
 
54
+ /**
55
+ * One year of a micro-entity profit and loss account (MICRO_PROFIT_AND_LOSS_LINES) from a small
56
+ * company's profit and loss lines. The book keeps no staff cost or raw material line, so every
57
+ * cost other than the depreciation charge is an other charge and interest receivable is other
58
+ * income. Turnover, profit before tax, tax and profit are the small company's own.
59
+ * @param {{turnover: number, costOfSales: number, administrativeExpenses: number, interestReceivable: number, profitBeforeTax: number, tax: number, profit: number}} year
60
+ * @param {number} depreciation - the depreciation charge within the costs, whole pounds
61
+ */
62
+ export function microProfitAndLossYear(year, depreciation = 0) {
207
63
  return {
208
- companyNumber: entity["diya-gl:companyNumber"] ?? null,
209
- companyName: entity.organizationIdentifier ?? null,
210
- periodStart,
211
- periodEnd,
212
- priorBalanceSheetDate: dayBefore(periodStart),
213
- averageNumberOfEmployees: (book.employees ?? []).length,
214
- directorName: book.directors?.[0]?.name ?? null,
215
- dormant: false,
216
- profitAndLoss,
217
- balanceSheet: { currentYear, priorYear },
218
- derivation: {
219
- currentYear: { sheet: "PubBalSht", lines: rounded(current) },
220
- priorYear: { sheet: "OpenAccounts", lines: rounded(prior) },
221
- },
222
- notes,
64
+ turnover: year.turnover,
65
+ otherIncome: year.interestReceivable,
66
+ rawMaterials: 0,
67
+ staffCosts: 0,
68
+ depreciation,
69
+ otherCharges: year.costOfSales + year.administrativeExpenses - depreciation,
70
+ profitBeforeTax: year.profitBeforeTax,
71
+ tax: year.tax,
72
+ profit: year.profit,
223
73
  };
224
74
  }
@@ -0,0 +1,264 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // app/services/microEntityAccountsFromResults.js
5
+ //
6
+ // The seven FRS 105 balance-sheet lines the accounts filing takes, for the current year from the
7
+ // Ltd engine's published balance sheet (PubBalSht) and for the prior year from the book's opening
8
+ // balance, rounded to whole pounds so the filing endpoint's own check (capital and reserves equals
9
+ // net assets) holds. The module has no fs, so the browser's books bundle runs it too.
10
+
11
+ export const BALANCE_SHEET_LINES = [
12
+ "fixedAssets",
13
+ "currentAssets",
14
+ "creditorsWithinOneYear",
15
+ "creditorsAfterOneYear",
16
+ "calledUpShareCapital",
17
+ "profitAndLossAccount",
18
+ "capitalAndReserves",
19
+ ];
20
+
21
+ const BALANCE_TOLERANCE = 0.005;
22
+
23
+ function isoDate(value) {
24
+ if (value === undefined || value === null) return null;
25
+ return new Date(value).toISOString().slice(0, 10);
26
+ }
27
+
28
+ function dayBefore(isoDay) {
29
+ return new Date(new Date(isoDay).getTime() - 86_400_000).toISOString().slice(0, 10);
30
+ }
31
+
32
+ function pence(value) {
33
+ return Math.round(value * 100) / 100;
34
+ }
35
+
36
+ /**
37
+ * The seven lines, unrounded, from the engine's published balance sheet.
38
+ * Refuses a sheet whose own net assets (F33) do not equal shareholders'
39
+ * funds (F39).
40
+ * @param {Object} sheet - results.PubBalSht
41
+ */
42
+ export function linesFromPublishedBalanceSheet(sheet) {
43
+ if (!sheet)
44
+ throw new Error("The book's product carries no published balance sheet; only a Company (ltd) book answers micro-entity accounts");
45
+ const netAssets = sheet.F33 ?? 0;
46
+ const shareholdersFunds = sheet.F39 ?? 0;
47
+ if (Math.abs(netAssets - shareholdersFunds) > BALANCE_TOLERANCE) {
48
+ throw new Error(
49
+ `The published balance sheet does not balance: net assets ${pence(netAssets)} against shareholders' funds ${pence(shareholdersFunds)} ` +
50
+ `(a difference of ${pence(netAssets - shareholdersFunds)}); a long-term debtor sits on no published line and is the usual cause`,
51
+ );
52
+ }
53
+ // An overdrawn director's loan account (E29 below 0) is a current asset, not a negative creditor.
54
+ const owedByDirectors = Math.max(0, -(sheet.E29 ?? 0));
55
+ return {
56
+ fixedAssets: sheet.F6 ?? 0,
57
+ currentAssets: (sheet.E13 ?? 0) + owedByDirectors,
58
+ creditorsWithinOneYear: sheet.E20 ?? 0,
59
+ creditorsAfterOneYear: (sheet.F31 ?? 0) + owedByDirectors,
60
+ amountsOwedByDirectors: owedByDirectors,
61
+ calledUpShareCapital: sheet.F36 ?? 0,
62
+ profitAndLossAccount: shareholdersFunds - (sheet.F36 ?? 0),
63
+ capitalAndReserves: shareholdersFunds,
64
+ };
65
+ }
66
+
67
+ // The trial balance's closing cells for the bank nominal accounts 1200 current, 1210 savings,
68
+ // 1220 cash and 1230 credit card.
69
+ const BANK_CLOSING_CELLS = ["EJ22", "EJ23", "EJ25", "EJ24"];
70
+
71
+ /**
72
+ * Pounds held across the bank nominal accounts (1200 to 1230) at the book's last transaction, to
73
+ * the penny, from the engine's trial balance.
74
+ * @param {Object} results - calculatedResultsFor output
75
+ */
76
+ export function cashAtBankFromResults(results) {
77
+ const trialBalance = results.TrialBalance;
78
+ if (!trialBalance) throw new Error("The book's product carries no trial balance; only a Company (ltd) book answers a cash balance");
79
+ return pence(BANK_CLOSING_CELLS.reduce((total, cell) => total + (trialBalance[cell] ?? 0), 0));
80
+ }
81
+
82
+ function sumValues(object) {
83
+ return Object.values(object || {}).reduce((total, value) => total + (value || 0), 0);
84
+ }
85
+
86
+ /**
87
+ * The three headline P&L figures for the financial year, from the engine's published profit
88
+ * and loss account. Turnover and profit are rounded to whole pounds first and costs is their
89
+ * difference, so turnover minus costs equals profit exactly rather than drifting from separate
90
+ * roundings of cost of sales, administrative expenses and tax.
91
+ * @param {Object} sheet - results["PubP&L"]
92
+ */
93
+ export function profitAndLossFromPublishedAccount(sheet) {
94
+ if (!sheet)
95
+ throw new Error(
96
+ "The book's product carries no published profit and loss account; only a Company (ltd) book answers micro-entity accounts",
97
+ );
98
+ const turnover = Math.round(sheet.F9 ?? 0);
99
+ const profit = Math.round(sheet.F51 ?? 0);
100
+ return { turnover, costs: turnover - profit, profit };
101
+ }
102
+
103
+ /**
104
+ * The seven lines, unrounded, from the book's opening balance (the figures
105
+ * the engine's OpenAccounts sheet shows). Refuses an opening balance whose
106
+ * assets do not equal its liabilities and equity.
107
+ * @param {Object} opening - scenario.opening_balance, snake_case keys
108
+ */
109
+ export function linesFromOpeningBalance(opening = {}) {
110
+ const at = (key) => opening[key] || 0;
111
+ const fixedAssets = sumValues(opening.fixed_asset_cost) - sumValues(opening.fixed_asset_depreciation);
112
+ const amountsOwedByDirectors = Math.max(0, -at("directors_loan"));
113
+ const currentAssets =
114
+ at("stock") +
115
+ at("trade_debtors") +
116
+ at("current_account") +
117
+ at("savings_account") +
118
+ at("credit_card") +
119
+ at("cash") +
120
+ at("long_term_debtors") +
121
+ amountsOwedByDirectors;
122
+ const creditorsWithinOneYear =
123
+ at("trade_creditors") +
124
+ at("net_wages_due") +
125
+ at("wage_deductions_due") +
126
+ at("dividends_due") +
127
+ at("corporation_tax") +
128
+ at("cis_due") +
129
+ at("vat_due") +
130
+ at("paye_due");
131
+ const creditorsAfterOneYear = Math.max(0, at("directors_loan")) + at("long_term_creditors");
132
+ const calledUpShareCapital = at("share_capital");
133
+ const profitAndLossAccount = at("retained_earnings") + at("capital_reserves");
134
+ const capitalAndReserves = calledUpShareCapital + profitAndLossAccount;
135
+ const netAssets = fixedAssets + currentAssets - creditorsWithinOneYear - creditorsAfterOneYear;
136
+ if (Math.abs(netAssets - capitalAndReserves) > BALANCE_TOLERANCE) {
137
+ throw new Error(
138
+ `The opening balance sheet does not balance: net assets ${pence(netAssets)} against capital and reserves ${pence(capitalAndReserves)} ` +
139
+ `(a difference of ${pence(netAssets - capitalAndReserves)})`,
140
+ );
141
+ }
142
+ return {
143
+ fixedAssets,
144
+ currentAssets,
145
+ creditorsWithinOneYear,
146
+ creditorsAfterOneYear,
147
+ amountsOwedByDirectors,
148
+ calledUpShareCapital,
149
+ profitAndLossAccount,
150
+ capitalAndReserves,
151
+ };
152
+ }
153
+
154
+ /**
155
+ * Whole pounds with the filing's identity intact: the four asset and
156
+ * liability lines and share capital are rounded, capital and reserves is
157
+ * derived from the four, and the profit and loss account is the remainder.
158
+ */
159
+ export function roundForFiling(lines) {
160
+ const fixedAssets = Math.round(lines.fixedAssets);
161
+ const currentAssets = Math.round(lines.currentAssets);
162
+ const creditorsWithinOneYear = Math.round(lines.creditorsWithinOneYear);
163
+ const creditorsAfterOneYear = Math.round(lines.creditorsAfterOneYear);
164
+ const calledUpShareCapital = Math.round(lines.calledUpShareCapital);
165
+ const capitalAndReserves = fixedAssets + currentAssets - creditorsWithinOneYear - creditorsAfterOneYear;
166
+ return {
167
+ fixedAssets,
168
+ currentAssets,
169
+ creditorsWithinOneYear,
170
+ creditorsAfterOneYear,
171
+ calledUpShareCapital,
172
+ profitAndLossAccount: capitalAndReserves - calledUpShareCapital,
173
+ capitalAndReserves,
174
+ };
175
+ }
176
+
177
+ function rounded(lines) {
178
+ return Object.fromEntries(Object.entries(lines).map(([key, value]) => [key, pence(value)]));
179
+ }
180
+
181
+ /**
182
+ * The section 413 note rows for a director's loan account that is overdrawn at either balance
183
+ * sheet date, as { directorsAdvances }, or nothing. The book holds the two balances and no
184
+ * gross movements, so a year's net rise is the advance and a net fall is the repayment. The
185
+ * interest rate and the main conditions are the company's to state. A book with an overdrawn
186
+ * loan and no director throws when the note is required (a filed document must carry it) and
187
+ * gives no note otherwise (figures only).
188
+ */
189
+ export function directorsAdvancesFrom(currentYear, priorYear, directorName, { requireNote }) {
190
+ const balanceAtEnd = Math.round(currentYear.amountsOwedByDirectors ?? 0);
191
+ const balanceAtStart = Math.round(priorYear.amountsOwedByDirectors ?? 0);
192
+ if (balanceAtEnd === 0 && balanceAtStart === 0) return {};
193
+ if (!directorName) {
194
+ if (requireNote) throw new Error("The book names no director to carry the advances to directors note");
195
+ return {};
196
+ }
197
+ return {
198
+ directorsAdvances: [
199
+ {
200
+ name: directorName,
201
+ balanceAtStart,
202
+ advanced: Math.max(0, balanceAtEnd - balanceAtStart),
203
+ repaid: Math.max(0, balanceAtStart - balanceAtEnd),
204
+ balanceAtEnd,
205
+ },
206
+ ],
207
+ };
208
+ }
209
+
210
+ /**
211
+ * The figures the micro-entity accounts filing takes, from a loaded Company book and its
212
+ * calculated results. Pure, so the browser's books bundle runs it too.
213
+ * @param {Object} book
214
+ * @param {Object} results - calculatedResultsFor output
215
+ * @param {Object} scenario - diyaGlToScenario output
216
+ * @param {Object} [options]
217
+ * @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
218
+ */
219
+ export function microEntityAccountsFromResults(book, results, scenario, { requireDirectorsNote = true } = {}) {
220
+ const info = book.documentInfo ?? {};
221
+ const entity = book.entityInformation ?? {};
222
+ const periodStart = isoDate(info.periodCoveredStart);
223
+ const periodEnd = isoDate(info.periodCoveredEnd);
224
+ if (!periodStart || !periodEnd) throw new Error("The book's documentInfo carries no periodCoveredStart and periodCoveredEnd");
225
+
226
+ const current = linesFromPublishedBalanceSheet(results.PubBalSht);
227
+ const prior = linesFromOpeningBalance(scenario.opening_balance);
228
+ const currentYear = roundForFiling(current);
229
+ const priorYear = roundForFiling(prior);
230
+ const profitAndLoss = profitAndLossFromPublishedAccount(results["PubP&L"]);
231
+
232
+ const capitalReserve = scenario.opening_balance?.capital_reserves || 0;
233
+ const notes = [
234
+ "Whole pounds: capital and reserves is derived from the rounded assets and creditors, and the profit and loss account is the remainder after share capital.",
235
+ "The average number of employees is the count of the book's employees table; confirm it before filing.",
236
+ ];
237
+ if (current.amountsOwedByDirectors > 0 || prior.amountsOwedByDirectors > 0)
238
+ notes.push(
239
+ "The director's loan account is overdrawn, so it is a current asset. Add the interest rate and the main conditions of the advance to the advances to directors note; the book holds neither.",
240
+ );
241
+ if (capitalReserve)
242
+ notes.push(
243
+ `A capital reserve of ${pence(capitalReserve)} is folded into the profit and loss account; the seven-line set has no other reserve line.`,
244
+ );
245
+
246
+ return {
247
+ companyNumber: entity["diya-gl:companyNumber"] ?? null,
248
+ companyName: entity.organizationIdentifier ?? null,
249
+ periodStart,
250
+ periodEnd,
251
+ priorBalanceSheetDate: dayBefore(periodStart),
252
+ averageNumberOfEmployees: (book.employees ?? []).length,
253
+ directorName: book.directors?.[0]?.name ?? null,
254
+ ...directorsAdvancesFrom(current, prior, book.directors?.[0]?.name, { requireNote: requireDirectorsNote }),
255
+ dormant: false,
256
+ profitAndLoss,
257
+ balanceSheet: { currentYear, priorYear },
258
+ derivation: {
259
+ currentYear: { sheet: "PubBalSht", lines: rounded(current) },
260
+ priorYear: { sheet: "OpenAccounts", lines: rounded(prior) },
261
+ },
262
+ notes,
263
+ };
264
+ }