@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,426 +0,0 @@
1
- // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
- // Copyright (C) 2006-2026 DIY Accounting Limited
3
-
4
- // app/services/smallCompanyAccountsIxbrl.js
5
- // Builds a small company's FRS 102 section 1A annual accounts as one iXBRL document: the full
6
- // profit and loss account, the Format 1 balance sheet with its sub-lines, the directors' report,
7
- // the fixed asset note and the small-companies-regime statements. With `filleted` the document is
8
- // the Companies House copy under section 444: it carries the section 444(5A) statement and omits
9
- // the profit and loss account and the directors' report. Prior-year comparatives render when
10
- // supplied and are omitted when not.
11
-
12
- import { escapeXmlText } from "../lib/xmlDom.js";
13
- import {
14
- CONCEPTS,
15
- DIMENSIONS,
16
- MEMBERS,
17
- qname,
18
- buildContexts,
19
- formatMonetary,
20
- renderStatement,
21
- renderFixedFact,
22
- renderTextFact,
23
- renderMonetaryFact,
24
- dimensionMemberXml,
25
- buildDimensionedContext,
26
- assembleBalanceSheetFacts,
27
- renderAccountsDocument,
28
- } from "./accountsIxbrlCommon.js";
29
-
30
- export const SMALL_COMPANY_BALANCE_SHEET_LINES = [
31
- "fixedAssets",
32
- "stocks",
33
- "debtors",
34
- "cashAtBank",
35
- "tradeCreditors",
36
- "corporationTax",
37
- "otherCreditors",
38
- "creditorsAfterOneYear",
39
- "calledUpShareCapital",
40
- "profitAndLossAccount",
41
- "capitalAndReserves",
42
- ];
43
-
44
- export const SMALL_COMPANY_PROFIT_AND_LOSS_LINES = [
45
- "turnover",
46
- "costOfSales",
47
- "grossProfit",
48
- "administrativeExpenses",
49
- "operatingProfit",
50
- "interestReceivable",
51
- "profitBeforeTax",
52
- "tax",
53
- "profit",
54
- ];
55
-
56
- export const FIXED_ASSET_CLASSES = ["landBuildings", "plantMachinery", "furnitureFittings", "computerEquipment", "motorVehicles"];
57
-
58
- export const FIXED_ASSET_CLASS_LABEL = {
59
- landBuildings: "Land and buildings",
60
- plantMachinery: "Plant and machinery",
61
- furnitureFittings: "Fixtures and fittings",
62
- computerEquipment: "Computer equipment",
63
- motorVehicles: "Motor vehicles",
64
- };
65
-
66
- export const FIXED_ASSET_CLASS_FIELDS = [
67
- "costAtStart",
68
- "additions",
69
- "disposals",
70
- "depreciationAtStart",
71
- "depreciationCharge",
72
- "depreciationOnDisposals",
73
- ];
74
-
75
- export const SMALL_COMPANY_STATEMENT_KEYS = [
76
- "statementAuditExemptionSection477",
77
- "statementMembersNotRequiredAudit",
78
- "statementDirectorsResponsibilities",
79
- "statementSmallCompaniesRegimeAccounts",
80
- ];
81
-
82
- export const SMALL_COMPANY_MANDATORY_CONCEPT_KEYS = [
83
- "companiesHouseRegisteredNumber",
84
- "entityCurrentLegalOrRegisteredName",
85
- "balanceSheetDate",
86
- "dateAuthorisationFinancialStatementsForIssue",
87
- "directorSigningFinancialStatements",
88
- "entityDormantTruefalse",
89
- "startDateForPeriodCoveredByReport",
90
- "endDateForPeriodCoveredByReport",
91
- "entityTradingStatus",
92
- "accountsStatusAuditedOrUnaudited",
93
- "accountsType",
94
- "accountingStandardsApplied",
95
- "applicableLegislation",
96
- ];
97
-
98
- export const PROFIT_AND_LOSS_CONCEPT_KEY = {
99
- turnover: "turnoverRevenue",
100
- costOfSales: "costSales",
101
- grossProfit: "grossProfitLoss",
102
- administrativeExpenses: "administrativeExpenses",
103
- operatingProfit: "operatingProfitLoss",
104
- interestReceivable: "otherInterestReceivable",
105
- profitBeforeTax: "profitLossBeforeTax",
106
- tax: "taxOnProfitLoss",
107
- profit: "profitLoss",
108
- };
109
-
110
- const PROFIT_AND_LOSS_LABEL = {
111
- turnover: "Turnover",
112
- costOfSales: "Cost of sales",
113
- grossProfit: "Gross profit",
114
- administrativeExpenses: "Administrative expenses",
115
- operatingProfit: "Operating profit",
116
- interestReceivable: "Interest receivable and similar income",
117
- profitBeforeTax: "Profit on ordinary activities before taxation",
118
- tax: "Tax on profit on ordinary activities",
119
- profit: "Profit for the financial year",
120
- };
121
-
122
- /**
123
- * The current assets and creditors totals a balance sheet carries, derived from its sub-lines.
124
- * @param {object} figures - the sub-lines of SMALL_COMPANY_BALANCE_SHEET_LINES
125
- * @returns {object} the figures plus currentAssets and creditorsWithinOneYear
126
- */
127
- export function withBalanceSheetTotals(figures) {
128
- return {
129
- ...figures,
130
- currentAssets: figures.stocks + figures.debtors + figures.cashAtBank,
131
- creditorsWithinOneYear: figures.tradeCreditors + figures.corporationTax + figures.otherCreditors,
132
- };
133
- }
134
-
135
- /**
136
- * The profit and loss identities a set of figures must hold, as messages; empty when they hold.
137
- * @param {object} figures - the lines of SMALL_COMPANY_PROFIT_AND_LOSS_LINES
138
- * @returns {string[]}
139
- */
140
- export function profitAndLossProblems(figures) {
141
- const problems = [];
142
- if (figures.grossProfit !== figures.turnover - figures.costOfSales) problems.push("grossProfit must equal turnover less costOfSales");
143
- if (figures.operatingProfit !== figures.grossProfit - figures.administrativeExpenses)
144
- problems.push("operatingProfit must equal grossProfit less administrativeExpenses");
145
- if (figures.profitBeforeTax !== figures.operatingProfit + figures.interestReceivable)
146
- problems.push("profitBeforeTax must equal operatingProfit plus interestReceivable");
147
- if (figures.profit !== figures.profitBeforeTax - figures.tax) problems.push("profit must equal profitBeforeTax less tax");
148
- return problems;
149
- }
150
-
151
- /**
152
- * The fixed asset note's closing figures for each class, derived from its movements.
153
- * @param {object} classFigures - the FIXED_ASSET_CLASS_FIELDS of one class
154
- * @returns {{costAtEnd: number, depreciationAtEnd: number, netBookValue: number}}
155
- */
156
- export function fixedAssetClosingFigures(classFigures) {
157
- const costAtEnd = classFigures.costAtStart + classFigures.additions - classFigures.disposals;
158
- const depreciationAtEnd = classFigures.depreciationAtStart + classFigures.depreciationCharge - classFigures.depreciationOnDisposals;
159
- return { costAtEnd, depreciationAtEnd, netBookValue: costAtEnd - depreciationAtEnd };
160
- }
161
-
162
- /**
163
- * The total net book value of a fixed asset note, and whether it matches the balance sheet's fixed assets.
164
- * @param {Record<string, object>} fixedAssetNote - class name to FIXED_ASSET_CLASS_FIELDS
165
- * @returns {number}
166
- */
167
- export function fixedAssetNoteNetBookValue(fixedAssetNote) {
168
- return Object.values(fixedAssetNote).reduce((total, classFigures) => total + fixedAssetClosingFigures(classFigures).netBookValue, 0);
169
- }
170
-
171
- function money(conceptKey, contextRef, value) {
172
- return renderMonetaryFact(conceptKey, contextRef, "GBP", value);
173
- }
174
-
175
- function row(label, currentXml, priorXml) {
176
- return `<tr><td>${escapeXmlText(label)}</td><td>${currentXml}</td><td>${priorXml ?? ""}</td></tr>`;
177
- }
178
-
179
- function table(headingText, hasPrior, rows) {
180
- return `<h2>${escapeXmlText(headingText)}</h2>
181
- <table><thead><tr><th></th><th>Current year</th>${hasPrior ? "<th>Prior year</th>" : "<th></th>"}</tr></thead><tbody>
182
- ${rows.join("\n")}
183
- </tbody></table>`;
184
- }
185
-
186
- function profitAndLossHtml({ refs, current, prior }) {
187
- const rows = SMALL_COMPANY_PROFIT_AND_LOSS_LINES.map((line) =>
188
- row(
189
- PROFIT_AND_LOSS_LABEL[line],
190
- money(PROFIT_AND_LOSS_CONCEPT_KEY[line], refs.current, current[line]),
191
- prior ? money(PROFIT_AND_LOSS_CONCEPT_KEY[line], refs.prior, prior[line]) : undefined,
192
- ),
193
- );
194
- return table("Profit and loss account", Boolean(prior), rows);
195
- }
196
-
197
- function balanceSheetHtml({ refs, current, prior, additionalContexts, entityIdentifierXml, periodXml }) {
198
- const currentWithTotals = withBalanceSheetTotals(current);
199
- const priorWithTotals = prior ? withBalanceSheetTotals(prior) : undefined;
200
-
201
- const mainFacts = [
202
- assembleBalanceSheetFacts({
203
- contextRef: refs.currentInstant,
204
- entityIdentifierXml,
205
- periodXml: periodXml[refs.currentInstant],
206
- additionalContexts,
207
- unitRef: "GBP",
208
- figures: currentWithTotals,
209
- }),
210
- ];
211
- if (priorWithTotals) {
212
- mainFacts.push(
213
- assembleBalanceSheetFacts({
214
- contextRef: refs.priorInstant,
215
- entityIdentifierXml,
216
- periodXml: periodXml[refs.priorInstant],
217
- additionalContexts,
218
- unitRef: "GBP",
219
- figures: priorWithTotals,
220
- }),
221
- );
222
- }
223
-
224
- const lines = [
225
- ["Stocks", "totalInventories", "stocks", ""],
226
- ["Debtors", "debtors", "debtors", ""],
227
- ["Cash at bank and in hand", "cashBankOnHand", "cashAtBank", ""],
228
- ["Trade creditors", "tradeCreditors", "tradeCreditors", "-within-one-year"],
229
- ["Corporation tax", "corporationTaxPayable", "corporationTax", "-within-one-year"],
230
- ["Other creditors", "otherCreditors", "otherCreditors", "-within-one-year"],
231
- ];
232
- const rows = lines.map(([label, conceptKey, field, contextSuffix]) =>
233
- row(
234
- label,
235
- money(conceptKey, `${refs.currentInstant}${contextSuffix}`, current[field]),
236
- priorWithTotals ? money(conceptKey, `${refs.priorInstant}${contextSuffix}`, prior[field]) : undefined,
237
- ),
238
- );
239
- return { html: table("Balance sheet", Boolean(priorWithTotals), rows), mainFacts: mainFacts.join("") };
240
- }
241
-
242
- function fixedAssetNoteFacts({ refs, fixedAssetNote, entityIdentifierXml, periodXml, additionalContexts }) {
243
- const facts = [];
244
- const htmlRows = [];
245
- for (const className of FIXED_ASSET_CLASSES) {
246
- const classFigures = fixedAssetNote[className];
247
- if (!classFigures) continue;
248
- const member = MEMBERS[className];
249
- const dimensionXml = dimensionMemberXml(DIMENSIONS.propertyPlantEquipmentClasses, member);
250
- const instantRef = buildDimensionedContext({
251
- additionalContexts,
252
- entityIdentifierXml,
253
- periodXml: periodXml[refs.currentInstant],
254
- dimensionXml,
255
- id: `${refs.currentInstant}-ppe-${className}`,
256
- });
257
- const durationRef = buildDimensionedContext({
258
- additionalContexts,
259
- entityIdentifierXml,
260
- periodXml: periodXml[refs.current],
261
- dimensionXml,
262
- id: `${refs.current}-ppe-${className}`,
263
- });
264
- const closing = fixedAssetClosingFigures(classFigures);
265
- facts.push(
266
- money("propertyPlantEquipmentGrossCost", instantRef, closing.costAtEnd),
267
- money("additionsPropertyPlantEquipment", durationRef, classFigures.additions),
268
- money("disposalsPropertyPlantEquipment", durationRef, classFigures.disposals),
269
- money("accumulatedDepreciationPropertyPlantEquipment", instantRef, closing.depreciationAtEnd),
270
- money("depreciationChargePropertyPlantEquipment", durationRef, classFigures.depreciationCharge),
271
- money("depreciationDisposalsPropertyPlantEquipment", durationRef, classFigures.depreciationOnDisposals),
272
- money("propertyPlantEquipment", instantRef, closing.netBookValue),
273
- );
274
- htmlRows.push(
275
- `<tr><td>${FIXED_ASSET_CLASS_LABEL[className]}</td><td>${money("propertyPlantEquipmentGrossCost", instantRef, closing.costAtEnd)}</td><td>${money("accumulatedDepreciationPropertyPlantEquipment", instantRef, closing.depreciationAtEnd)}</td><td>${money("propertyPlantEquipment", instantRef, closing.netBookValue)}</td></tr>`,
276
- );
277
- }
278
- return { facts, htmlRows };
279
- }
280
-
281
- function directorsReportHtml({ input, refs, additionalContexts, entityIdentifierXml, periodXml }) {
282
- const directorFacts = input.directors.map((name, index) => {
283
- const contextRef = buildDimensionedContext({
284
- additionalContexts,
285
- entityIdentifierXml,
286
- periodXml: periodXml[refs.current],
287
- dimensionXml: dimensionMemberXml(DIMENSIONS.entityOfficers, { prefix: "bus", name: `Director${index + 1}` }),
288
- id: `${refs.current}-director-${index + 1}`,
289
- });
290
- return `<li>${renderTextFact("nameEntityOfficer", contextRef, name)}</li>`;
291
- });
292
- return `<h2>Directors' report</h2>
293
- <p>Principal activity: ${renderTextFact("descriptionPrincipalActivities", refs.current, input.principalActivity)}</p>
294
- <p>Directors who held office during the period:</p>
295
- <ul>${directorFacts.join("")}</ul>
296
- <p>${renderStatement("statementSmallCompaniesRegimeDirectorsReport", refs.current)}</p>
297
- <p>Approved by the board on ${input.dateOfApproval} and signed on its behalf by ${escapeXmlText(input.directorName)}${renderFixedFact("directorSigningDirectorsReport", refs.current)}</p>`;
298
- }
299
-
300
- /**
301
- * Build a small company's FRS 102 section 1A annual accounts as one iXBRL document.
302
- *
303
- * @param {object} input
304
- * @param {string} input.companyNumber
305
- * @param {string} input.companyName
306
- * @param {string} input.periodStart - ISO date
307
- * @param {string} input.periodEnd - ISO date
308
- * @param {string} [input.priorBalanceSheetDate] - ISO date; defaults to the day before periodStart
309
- * @param {string} [input.priorPeriodStart] - ISO date; defaults to a year before periodStart
310
- * @param {boolean} [input.filleted] - the Companies House copy: section 444(5A) statement, no profit and loss account, no directors' report
311
- * @param {number} input.averageNumberOfEmployees
312
- * @param {string} input.principalActivity
313
- * @param {string} input.accountingPolicies - plain text for the accounting policies note
314
- * @param {string[]} input.directors - the names of the directors who held office
315
- * @param {string} input.directorName - the director who signs
316
- * @param {string} input.dateOfApproval - ISO date
317
- * @param {{current: object, prior?: object}} input.balanceSheet - SMALL_COMPANY_BALANCE_SHEET_LINES
318
- * @param {{current: object, prior?: object}} input.profitAndLoss - SMALL_COMPANY_PROFIT_AND_LOSS_LINES
319
- * @param {Record<string, object>} [input.fixedAssetNote] - FIXED_ASSET_CLASSES to FIXED_ASSET_CLASS_FIELDS
320
- * @returns {string} the XHTML document
321
- */
322
- export function buildSmallCompanyAccounts(input) {
323
- const priorBalanceSheet = input.balanceSheet.prior;
324
- const priorProfitAndLoss = input.profitAndLoss.prior;
325
- const {
326
- xml: contextsXml,
327
- refs,
328
- entityIdentifierXml,
329
- periodXml,
330
- } = buildContexts(input, {
331
- includePriorInstant: Boolean(priorBalanceSheet),
332
- includePriorPeriod: Boolean(priorProfitAndLoss) && !input.filleted,
333
- });
334
- const additionalContexts = [];
335
- const unrenderedFacts = [];
336
-
337
- const problems = [
338
- ...profitAndLossProblems(input.profitAndLoss.current).map((message) => `profitAndLoss.current: ${message}`),
339
- ...(priorProfitAndLoss ? profitAndLossProblems(priorProfitAndLoss).map((message) => `profitAndLoss.prior: ${message}`) : []),
340
- ];
341
- if (problems.length > 0) throw new Error(problems.join("; "));
342
- if (input.fixedAssetNote && fixedAssetNoteNetBookValue(input.fixedAssetNote) !== input.balanceSheet.current.fixedAssets) {
343
- throw new Error(
344
- `The fixed asset note's net book value (${fixedAssetNoteNetBookValue(input.fixedAssetNote)}) does not equal fixed assets (${input.balanceSheet.current.fixedAssets})`,
345
- );
346
- }
347
-
348
- unrenderedFacts.push(
349
- `<ix:nonNumeric name="${qname(CONCEPTS.companiesHouseRegisteredNumber)}" contextRef="${refs.current}">${escapeXmlText(input.companyNumber)}</ix:nonNumeric>`,
350
- `<ix:nonNumeric name="${qname(CONCEPTS.entityCurrentLegalOrRegisteredName)}" contextRef="${refs.current}">${escapeXmlText(input.companyName)}</ix:nonNumeric>`,
351
- `<ix:nonNumeric name="${qname(CONCEPTS.balanceSheetDate)}" contextRef="${refs.currentInstant}">${input.periodEnd}</ix:nonNumeric>`,
352
- `<ix:nonNumeric name="${qname(CONCEPTS.dateAuthorisationFinancialStatementsForIssue)}" contextRef="${refs.currentInstant}">${input.dateOfApproval}</ix:nonNumeric>`,
353
- renderFixedFact("directorSigningFinancialStatements", refs.current),
354
- `<ix:nonNumeric name="${qname(CONCEPTS.entityDormantTruefalse)}" contextRef="${refs.current}">false</ix:nonNumeric>`,
355
- `<ix:nonNumeric name="${qname(CONCEPTS.startDateForPeriodCoveredByReport)}" contextRef="${refs.periodStartInstant}">${input.periodStart}</ix:nonNumeric>`,
356
- `<ix:nonNumeric name="${qname(CONCEPTS.endDateForPeriodCoveredByReport)}" contextRef="${refs.currentInstant}">${input.periodEnd}</ix:nonNumeric>`,
357
- renderFixedFact("entityTradingStatus", refs.current),
358
- );
359
-
360
- for (const [conceptKey, dimension, member, id] of [
361
- ["accountsStatusAuditedOrUnaudited", DIMENSIONS.accountsStatus, MEMBERS.auditExemptNoAccountantsReport, "accounts-status"],
362
- ["accountsType", DIMENSIONS.accountsType, MEMBERS.fullAccounts, "accounts-type"],
363
- ["accountingStandardsApplied", DIMENSIONS.accountingStandards, MEMBERS.frs102, "accounting-standards"],
364
- ["applicableLegislation", DIMENSIONS.applicableLegislation, MEMBERS.smallCompaniesRegimeForAccounts, "applicable-legislation"],
365
- ]) {
366
- const contextRef = buildDimensionedContext({
367
- additionalContexts,
368
- entityIdentifierXml,
369
- periodXml: periodXml[refs.current],
370
- dimensionXml: dimensionMemberXml(dimension, member),
371
- id: `${refs.current}-${id}`,
372
- });
373
- unrenderedFacts.push(renderFixedFact(conceptKey, contextRef));
374
- }
375
-
376
- const statementKeys = input.filleted
377
- ? [...SMALL_COMPANY_STATEMENT_KEYS, "statementProfitAndLossNotDelivered"]
378
- : SMALL_COMPANY_STATEMENT_KEYS;
379
- const statementsHtml = statementKeys.map((key) => `<p>${renderStatement(key, refs.current)}</p>`).join("\n");
380
-
381
- const employeesFact = `<ix:nonFraction name="${qname(CONCEPTS.averageNumberEmployeesDuringPeriod)}" contextRef="${refs.current}" unitRef="pure" decimals="0">${formatMonetary(input.averageNumberOfEmployees)}</ix:nonFraction>`;
382
-
383
- const balanceSheet = balanceSheetHtml({
384
- refs,
385
- current: input.balanceSheet.current,
386
- prior: priorBalanceSheet,
387
- additionalContexts,
388
- entityIdentifierXml,
389
- periodXml,
390
- });
391
-
392
- const sections = [];
393
- if (!input.filleted) {
394
- sections.push(profitAndLossHtml({ refs, current: input.profitAndLoss.current, prior: priorProfitAndLoss }));
395
- }
396
- sections.push(balanceSheet.html, `<div>${balanceSheet.mainFacts}</div>`);
397
-
398
- sections.push(`<h2>Statements</h2>\n${statementsHtml}`);
399
- sections.push(`<h2>Notes to the accounts</h2>
400
- <h3>Accounting policies</h3>
401
- <p>${escapeXmlText(input.accountingPolicies)}</p>
402
- <h3>Employees</h3>
403
- <p>The average number of employees during the period was ${employeesFact}</p>`);
404
-
405
- if (input.fixedAssetNote) {
406
- const note = fixedAssetNoteFacts({ refs, fixedAssetNote: input.fixedAssetNote, entityIdentifierXml, periodXml, additionalContexts });
407
- sections.push(`<h3>Tangible fixed assets</h3>
408
- <table><thead><tr><th></th><th>Cost</th><th>Depreciation</th><th>Net book value</th></tr></thead><tbody>
409
- ${note.htmlRows.join("\n")}
410
- </tbody></table>
411
- <div>${note.facts.join("")}</div>`);
412
- }
413
-
414
- if (!input.filleted) {
415
- sections.push(directorsReportHtml({ input, refs, additionalContexts, entityIdentifierXml, periodXml }));
416
- }
417
-
418
- const bodyHtml = `<h1>${escapeXmlText(input.companyName)}</h1>
419
- <p>Company number ${escapeXmlText(input.companyNumber)}</p>
420
- <p>Annual accounts for the period from ${input.periodStart} to ${input.periodEnd}</p>
421
- <p>Approved on behalf of the board on ${input.dateOfApproval} by ${escapeXmlText(input.directorName)}</p>
422
- <div>${unrenderedFacts.join("\n")}</div>
423
- ${sections.join("\n")}`;
424
-
425
- return renderAccountsDocument({ companyName: input.companyName, contextsXml: `${contextsXml}${additionalContexts.join("")}`, bodyHtml });
426
- }