@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.
- package/README.md +30 -9
- package/lib/accounts-tools.js +46 -2
- package/lib/auth.js +11 -1
- package/lib/batch-tools.js +19 -2
- package/lib/book-tools.js +47 -4
- package/lib/client-headers.js +263 -0
- package/lib/finance/bank-lines.js +10 -0
- package/lib/finance/book-from-workbook.js +10 -0
- package/lib/finance/mail-invoices.js +45 -7
- package/lib/finance/paypal-statement-lines.js +11 -1
- package/lib/finance/stripe-lines.js +20 -0
- package/lib/harness.js +58 -0
- package/lib/hosted-tools.js +82 -12
- package/lib/itsa-tools.js +173 -1
- package/lib/practice-tools.js +22 -12
- package/lib/server.js +348 -45
- package/lib/submit-tools.js +326 -71
- package/lib/vat-tools.js +10 -0
- package/lib/vendored/app/services/ct600Figures.js +1175 -0
- package/lib/vendored/app/services/microEntityAccounts.js +47 -197
- package/lib/vendored/app/services/microEntityAccountsFromResults.js +264 -0
- package/lib/vendored/app/services/smallCompanyAccounts.js +7 -240
- package/lib/vendored/app/services/smallCompanyAccountsFromResults.js +333 -0
- package/package.json +12 -7
- package/lib/vendored/app/lib/xmlDom.js +0 -73
- package/lib/vendored/app/services/accountsIxbrlCommon.js +0 -414
- package/lib/vendored/app/services/smallCompanyAccountsIxbrl.js +0 -426
|
@@ -0,0 +1,1175 @@
|
|
|
1
|
+
// SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
|
|
2
|
+
// Copyright (C) 2006-2026 DIY Accounting Limited
|
|
3
|
+
|
|
4
|
+
// app/services/ct600Figures.js
|
|
5
|
+
// The CT600 (2026) Version 3 boxes and the computation lines, worked from one object of figures.
|
|
6
|
+
// The module has no fs and no Buffer, so it runs in the browser (through the books bundle) for
|
|
7
|
+
// live checks and on the server for the preview and the submit, and both charge the same rates.
|
|
8
|
+
//
|
|
9
|
+
// Box 705 and the annual investment allowance. HMRC's Company Tax Return guide, section
|
|
10
|
+
// "Information about capital allowances and balancing charges or disposal values"
|
|
11
|
+
// (https://www.gov.uk/guidance/the-company-tax-return-guide), says:
|
|
12
|
+
// Box 690: "Enter the amount of Annual Investment Allowance included in the calculation of
|
|
13
|
+
// trading profits or losses."
|
|
14
|
+
// Box 705: "Enter the total allowances including any Annual Investment Allowance claimed, in
|
|
15
|
+
// respect of the main pool in box 705."
|
|
16
|
+
// So box 705 holds the main pool's writing down allowances plus the annual investment allowance
|
|
17
|
+
// claimed on the main pool, and box 690 repeats the annual investment allowance. The computation's
|
|
18
|
+
// total capital allowances is box 705 less the balancing charges in box 710. HMRC's validation
|
|
19
|
+
// rules put no limit on box 705 against box 690, so the transaction engine accepts either way and
|
|
20
|
+
// the guide decides.
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
apportionCorporationTax,
|
|
24
|
+
financialYearNumber,
|
|
25
|
+
financialYearRatesFor,
|
|
26
|
+
financialYearsInPeriod,
|
|
27
|
+
} from "@diy-accounting-uk/diya-gl/dist/app/lib/tax/corporation-tax.js";
|
|
28
|
+
|
|
29
|
+
export const EARLIEST_PERIOD_START = "2015-04-01";
|
|
30
|
+
export const WORKING_SHEET_TOLERANCE_POUNDS = 5;
|
|
31
|
+
|
|
32
|
+
const EXCEL_EPOCH_MS = Date.UTC(1899, 11, 30);
|
|
33
|
+
const DAY_MS = 86_400_000;
|
|
34
|
+
|
|
35
|
+
export class Ct600RefusedError extends Error {
|
|
36
|
+
constructor(message, field) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "Ct600RefusedError";
|
|
39
|
+
this.field = field;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isoFromSerial(serial) {
|
|
44
|
+
return new Date(EXCEL_EPOCH_MS + serial * DAY_MS).toISOString().slice(0, 10);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function utcDate(isoDate) {
|
|
48
|
+
return new Date(`${isoDate}T00:00:00Z`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function isIsoDate(value) {
|
|
52
|
+
return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && utcDate(value).toISOString().slice(0, 10) === value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function lastDayOfTwelveMonths(isoStart) {
|
|
56
|
+
const date = utcDate(isoStart);
|
|
57
|
+
date.setUTCFullYear(date.getUTCFullYear() + 1);
|
|
58
|
+
date.setUTCDate(date.getUTCDate() - 1);
|
|
59
|
+
return date.toISOString().slice(0, 10);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function toPence(pounds) {
|
|
63
|
+
return Math.round(pounds * 100);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function fromPence(pence) {
|
|
67
|
+
return pence / 100;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function wholePounds(value) {
|
|
71
|
+
return Math.round(value || 0);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// How each computation line moves the profit per accounts: -1 takes from it, 1 adds to it.
|
|
75
|
+
const COMPUTATION_ADJUSTMENTS = [
|
|
76
|
+
["nonTradingLoanRelationshipCredits", -1],
|
|
77
|
+
["depreciation", 1],
|
|
78
|
+
["amortisation", 1],
|
|
79
|
+
["entertaining", 1],
|
|
80
|
+
["donations", 1],
|
|
81
|
+
];
|
|
82
|
+
|
|
83
|
+
// The figures fields that hold whole pounds and no less than zero, with the label a message uses.
|
|
84
|
+
const WHOLE_POUND_FIELDS = [
|
|
85
|
+
["nonTradingLoanRelationshipCredits", "Non-trading loan relationship credits (bank interest)"],
|
|
86
|
+
["depreciation", "Depreciation added back"],
|
|
87
|
+
["amortisation", "Amortisation added back"],
|
|
88
|
+
["entertaining", "Entertaining added back"],
|
|
89
|
+
["donations", "Donations added back"],
|
|
90
|
+
["annualInvestmentAllowance", "Annual investment allowance (box 690)"],
|
|
91
|
+
["mainPoolAllowances", "Main pool writing down allowances, without the annual investment allowance"],
|
|
92
|
+
["mainPoolBalancingCharges", "Main pool balancing charges (box 710)"],
|
|
93
|
+
["fullExpensingAllowances", "Full expensing allowances (box 688)"],
|
|
94
|
+
["fullExpensingBalancingCharges", "Full expensing balancing charges (box 689)"],
|
|
95
|
+
["specialRateAllowances", "Special rate allowances (box 693)"],
|
|
96
|
+
["specialRateBalancingCharges", "Special rate allowance balancing charges (box 694)"],
|
|
97
|
+
["specialRatePoolAllowances", "Special rate pool writing down allowances, without the annual investment allowance (box 695)"],
|
|
98
|
+
["specialRatePoolAnnualInvestmentAllowance", "Annual investment allowance claimed on the special rate pool"],
|
|
99
|
+
["specialRatePoolBalancingCharges", "Special rate pool balancing charges (box 700)"],
|
|
100
|
+
["annualInvestmentAllowanceOutsideTrade", "Annual investment allowance outside the calculation of trading profits (box 735)"],
|
|
101
|
+
["firstYearAllowanceExpenditure", "Machinery and plant on which first year allowance is claimed (box 760)"],
|
|
102
|
+
["specialRateAllowanceExpenditure", "Machinery and plant - special rate allowance, qualifying expenditure (box 773)"],
|
|
103
|
+
["otherMachineryAndPlantExpenditure", "Other machinery and plant (box 775)"],
|
|
104
|
+
["lossesBroughtForward", "Trading losses brought forward (box 160)"],
|
|
105
|
+
["lossAgainstTotalProfits", "Trading loss of this period set against this period's total profits (box 275)"],
|
|
106
|
+
["lossesBroughtForwardAgainstTotalProfits", "Trading losses brought forward claimed against total profits (box 285)"],
|
|
107
|
+
["lossCarriedBack", "Trading loss carried back against the previous period's profits"],
|
|
108
|
+
["priorPeriodChargeableProfits", "The previous period's chargeable profits (box 315 of its return)"],
|
|
109
|
+
["frankedInvestmentIncome", "Franked investment income or exempt ABGH distributions (box 620)"],
|
|
110
|
+
];
|
|
111
|
+
|
|
112
|
+
const PENCE_FIELDS = [
|
|
113
|
+
["incomeTaxDeducted", "Income Tax deducted from gross income (box 515)"],
|
|
114
|
+
["taxAlreadyPaid", "Tax already paid and not repaid (box 595)"],
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
function numberOrZero(value) {
|
|
118
|
+
return value === undefined || value === null ? 0 : value;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function validText(value) {
|
|
122
|
+
return typeof value === "string" && value.trim().length >= 2;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The checks on the figures themselves, before any tax is worked.
|
|
127
|
+
*
|
|
128
|
+
* @param {object} figures
|
|
129
|
+
* @param {object} [options]
|
|
130
|
+
* @param {string} [options.today] - ISO date; when given, the period must end before it
|
|
131
|
+
* @returns {Array<{field: string, message: string, refusal: boolean}>}
|
|
132
|
+
*/
|
|
133
|
+
function figureProblems(figures, { today } = {}) {
|
|
134
|
+
const problems = [];
|
|
135
|
+
const problem = (field, message, refusal = false) => problems.push({ field, message, refusal });
|
|
136
|
+
|
|
137
|
+
if (!/^\d{10}$/.test(figures.utr || "")) problem("utr", "The UTR must be 10 digits");
|
|
138
|
+
if (!/^[A-Z0-9]{2,8}$/.test(figures.companyNumber || ""))
|
|
139
|
+
problem("companyNumber", "The company registration number must be 2 to 8 capital letters or digits");
|
|
140
|
+
if (!validText(figures.companyName)) problem("companyName", "The company name is required (at least 2 characters)");
|
|
141
|
+
const companyType = numberOrZero(figures.companyType);
|
|
142
|
+
if (companyType !== 0) {
|
|
143
|
+
problem("companyType", `Company type ${companyType} is not filed here; only type 0 (none of the listed types) is`, true);
|
|
144
|
+
}
|
|
145
|
+
const associated = numberOrZero(figures.associatedCompanies);
|
|
146
|
+
if (!Number.isInteger(associated) || associated < 0)
|
|
147
|
+
problem("associatedCompanies", "Associated companies must be a whole number, 0 or more");
|
|
148
|
+
|
|
149
|
+
if (!isIsoDate(figures.periodStart) || !isIsoDate(figures.periodEnd)) {
|
|
150
|
+
problem("period", "The period start and end must be dates (YYYY-MM-DD)");
|
|
151
|
+
} else if (figures.periodEnd < figures.periodStart) {
|
|
152
|
+
problem("period", "The period cannot end before it starts");
|
|
153
|
+
} else {
|
|
154
|
+
if (figures.periodStart < EARLIEST_PERIOD_START) {
|
|
155
|
+
problem(
|
|
156
|
+
"period",
|
|
157
|
+
`The return period starts ${figures.periodStart}; CT600 Version 3 covers periods starting on or after ${EARLIEST_PERIOD_START}`,
|
|
158
|
+
true,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (figures.periodEnd > lastDayOfTwelveMonths(figures.periodStart)) {
|
|
162
|
+
problem(
|
|
163
|
+
"period",
|
|
164
|
+
`The return period ${figures.periodStart} to ${figures.periodEnd} is longer than 12 months; a long period of account files two returns`,
|
|
165
|
+
true,
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
if (today && figures.periodEnd >= today) problem("period", "The period must end before today");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const current = figures.profitAndLoss?.current;
|
|
172
|
+
if (!current || !Number.isFinite(current.turnover) || !Number.isFinite(current.profitBeforeTax)) {
|
|
173
|
+
problem("profitAndLoss", "The profit and loss account needs turnover and profit before tax");
|
|
174
|
+
} else if (current.turnover < 0) {
|
|
175
|
+
problem("profitAndLoss", "The turnover is negative", true);
|
|
176
|
+
}
|
|
177
|
+
const prior = figures.profitAndLoss?.prior;
|
|
178
|
+
if (prior !== undefined && (!Number.isFinite(prior.turnover) || !Number.isFinite(prior.profitBeforeTax))) {
|
|
179
|
+
problem("profitAndLoss", "The prior year's profit and loss account needs turnover and profit before tax");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
for (const [field, label] of WHOLE_POUND_FIELDS) {
|
|
183
|
+
const value = numberOrZero(figures[field]);
|
|
184
|
+
if (!Number.isInteger(value) || value < 0) problem(field, `${label} must be whole pounds, 0 or more`);
|
|
185
|
+
}
|
|
186
|
+
if (
|
|
187
|
+
Number.isFinite(numberOrZero(figures.entertaining)) &&
|
|
188
|
+
current &&
|
|
189
|
+
Number.isFinite(current.costOfSales) &&
|
|
190
|
+
Number.isFinite(current.administrativeExpenses) &&
|
|
191
|
+
numberOrZero(figures.entertaining) > current.costOfSales + current.administrativeExpenses
|
|
192
|
+
) {
|
|
193
|
+
problem("entertaining", "Entertaining added back is more than the cost of sales and administrative expenses");
|
|
194
|
+
}
|
|
195
|
+
if (
|
|
196
|
+
Number.isFinite(numberOrZero(figures.donations)) &&
|
|
197
|
+
current &&
|
|
198
|
+
Number.isFinite(current.costOfSales) &&
|
|
199
|
+
Number.isFinite(current.administrativeExpenses) &&
|
|
200
|
+
numberOrZero(figures.donations) > current.costOfSales + current.administrativeExpenses
|
|
201
|
+
) {
|
|
202
|
+
problem("donations", "Donations added back are more than the cost of sales and administrative expenses");
|
|
203
|
+
}
|
|
204
|
+
if (numberOrZero(figures.specialRatePoolAnnualInvestmentAllowance) > numberOrZero(figures.annualInvestmentAllowance)) {
|
|
205
|
+
problem(
|
|
206
|
+
"specialRatePoolAnnualInvestmentAllowance",
|
|
207
|
+
"The annual investment allowance claimed on the special rate pool is more than the annual investment allowance in box 690",
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
if (numberOrZero(figures.specialRateAllowances) > 0 && numberOrZero(figures.specialRateAllowanceExpenditure) === 0) {
|
|
211
|
+
problem("specialRateAllowanceExpenditure", "Enter the qualifying expenditure in box 773: HMRC needs it when box 693 is completed");
|
|
212
|
+
}
|
|
213
|
+
if (figures.lossOutsideUk !== undefined && typeof figures.lossOutsideUk !== "boolean") {
|
|
214
|
+
problem("lossOutsideUk", "Whether the trade is carried on wholly outside the UK must be yes or no");
|
|
215
|
+
}
|
|
216
|
+
for (const [field, label] of PENCE_FIELDS) {
|
|
217
|
+
const value = numberOrZero(figures[field]);
|
|
218
|
+
if (!Number.isFinite(value) || value < 0 || Math.abs(value * 100 - Math.round(value * 100)) > 1e-6) {
|
|
219
|
+
problem(field, `${label} must be pounds and pence, 0 or more`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (!validText(figures.declarantName)) problem("declarantName", "The declarant's name is required (at least 2 characters)");
|
|
223
|
+
if (!validText(figures.declarantStatus)) problem("declarantStatus", "The declarant's status is required (at least 2 characters)");
|
|
224
|
+
problems.push(...loansProblems(figures, { today }));
|
|
225
|
+
return problems;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The full profit and loss account for the financial year, in whole pounds, from the engine's
|
|
230
|
+
* published account. Turnover, cost of sales, administrative expenses, profit before tax and tax
|
|
231
|
+
* are rounded; gross profit, operating profit and the interest line are derived from them so every
|
|
232
|
+
* subtotal holds exactly.
|
|
233
|
+
* @param {Object} sheet - results["PubP&L"]
|
|
234
|
+
*/
|
|
235
|
+
export function smallCompanyProfitAndLossFromPublishedAccount(sheet) {
|
|
236
|
+
if (!sheet)
|
|
237
|
+
throw new Error(
|
|
238
|
+
"The book's product carries no published profit and loss account; only a Company (ltd) book answers small company accounts",
|
|
239
|
+
);
|
|
240
|
+
const turnover = Math.round(sheet.F9 ?? 0);
|
|
241
|
+
const costOfSales = Math.round(sheet.F16 ?? 0);
|
|
242
|
+
const administrativeExpenses = Math.round(sheet.F44 ?? 0);
|
|
243
|
+
const profitBeforeTax = Math.round(sheet.F49 ?? 0);
|
|
244
|
+
const tax = Math.round(sheet.F50 ?? 0);
|
|
245
|
+
const grossProfit = turnover - costOfSales;
|
|
246
|
+
const operatingProfit = grossProfit - administrativeExpenses;
|
|
247
|
+
return {
|
|
248
|
+
turnover,
|
|
249
|
+
costOfSales,
|
|
250
|
+
grossProfit,
|
|
251
|
+
administrativeExpenses,
|
|
252
|
+
operatingProfit,
|
|
253
|
+
interestReceivable: profitBeforeTax - operatingProfit,
|
|
254
|
+
profitBeforeTax,
|
|
255
|
+
tax,
|
|
256
|
+
profit: profitBeforeTax - tax,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* The capital allowance classes the computation lists beside the annual investment allowance and
|
|
262
|
+
* the main pool: full expensing, the special rate allowance and the special rate pool. The annual
|
|
263
|
+
* investment allowance claimed on the special rate pool counts with that pool's allowances.
|
|
264
|
+
*/
|
|
265
|
+
function capitalAllowanceClassLines(figures) {
|
|
266
|
+
return {
|
|
267
|
+
fullExpensingAllowances: numberOrZero(figures.fullExpensingAllowances),
|
|
268
|
+
fullExpensingBalancingCharges: numberOrZero(figures.fullExpensingBalancingCharges),
|
|
269
|
+
specialRateAllowances: numberOrZero(figures.specialRateAllowances),
|
|
270
|
+
specialRateBalancingCharges: numberOrZero(figures.specialRateBalancingCharges),
|
|
271
|
+
specialRatePoolAllowances: numberOrZero(figures.specialRatePoolAllowances),
|
|
272
|
+
specialRatePoolBalancingCharges: numberOrZero(figures.specialRatePoolBalancingCharges),
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* The computation lines, in whole pounds, from the figures. Each total is summed from the lines
|
|
278
|
+
* above it, so the computation adds up.
|
|
279
|
+
*
|
|
280
|
+
* @param {object} figures
|
|
281
|
+
* @returns {{profitLossPerAccounts: number, nonTradingLoanRelationshipCredits: number, depreciation: number, amortisation: number, entertaining: number, donations: number, adjustedProfitBeforeCapitalAllowances: number, totalCapitalAllowances: number, adjustedProfit: number}} a loss is a negative adjustedProfit
|
|
282
|
+
*/
|
|
283
|
+
export function computationLinesFromFigures(figures) {
|
|
284
|
+
const lines = {
|
|
285
|
+
profitLossPerAccounts: figures.profitAndLoss.current.profitBeforeTax,
|
|
286
|
+
nonTradingLoanRelationshipCredits: numberOrZero(figures.nonTradingLoanRelationshipCredits),
|
|
287
|
+
depreciation: numberOrZero(figures.depreciation),
|
|
288
|
+
amortisation: numberOrZero(figures.amortisation),
|
|
289
|
+
entertaining: numberOrZero(figures.entertaining),
|
|
290
|
+
donations: numberOrZero(figures.donations),
|
|
291
|
+
};
|
|
292
|
+
lines.adjustedProfitBeforeCapitalAllowances =
|
|
293
|
+
lines.profitLossPerAccounts + COMPUTATION_ADJUSTMENTS.reduce((total, [key, effect]) => total + effect * lines[key], 0);
|
|
294
|
+
Object.assign(lines, capitalAllowanceClassLines(figures));
|
|
295
|
+
lines.totalCapitalAllowances =
|
|
296
|
+
numberOrZero(figures.annualInvestmentAllowance) +
|
|
297
|
+
numberOrZero(figures.mainPoolAllowances) -
|
|
298
|
+
numberOrZero(figures.mainPoolBalancingCharges) +
|
|
299
|
+
lines.fullExpensingAllowances -
|
|
300
|
+
lines.fullExpensingBalancingCharges +
|
|
301
|
+
lines.specialRateAllowances -
|
|
302
|
+
lines.specialRateBalancingCharges +
|
|
303
|
+
lines.specialRatePoolAllowances -
|
|
304
|
+
lines.specialRatePoolBalancingCharges;
|
|
305
|
+
lines.adjustedProfit = lines.adjustedProfitBeforeCapitalAllowances - lines.totalCapitalAllowances;
|
|
306
|
+
return lines;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The figures a Company book's calculated results give, in the model's shape. The typed company
|
|
311
|
+
* facts (name, number, UTR, company type, declarant, tax already paid) are not in a book; the
|
|
312
|
+
* caller adds them. The book carries no prior-year profit and loss account, so the prior year is
|
|
313
|
+
* the accounts' own when they supply one.
|
|
314
|
+
*
|
|
315
|
+
* @param {object} results - diya-gl calculatedResultsFor output for a Company book
|
|
316
|
+
* @param {{profitAndLoss: {currentYear: object, priorYear?: object}}} smallCompanyAccounts - deriveSmallCompanyAccounts output
|
|
317
|
+
* @returns {object} figures, with workingSheet for the £5 check
|
|
318
|
+
*/
|
|
319
|
+
export function ct600FiguresFromResults(results, smallCompanyAccounts) {
|
|
320
|
+
const ct600 = results.CT600;
|
|
321
|
+
const workingSheet = results.CorporationTax;
|
|
322
|
+
const admin = results.Admin;
|
|
323
|
+
if (!ct600 || !workingSheet || !admin) {
|
|
324
|
+
throw new Ct600RefusedError("The book carries no CT600 sheet; only a Company (ltd) book files a Company Tax Return");
|
|
325
|
+
}
|
|
326
|
+
if (workingSheet.K24 < 0) {
|
|
327
|
+
throw new Ct600RefusedError(
|
|
328
|
+
"The book has net non-trading loan relationship debits; those boxes have no diya-gl cell yet",
|
|
329
|
+
"nonTradingLoanRelationshipCredits",
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
const positive = (value) => (value > 0 ? Math.round(value) : 0);
|
|
333
|
+
const allowances = workingSheet;
|
|
334
|
+
const profitAndLoss = { current: smallCompanyAccounts.profitAndLoss.currentYear };
|
|
335
|
+
if (smallCompanyAccounts.profitAndLoss.priorYear) profitAndLoss.prior = smallCompanyAccounts.profitAndLoss.priorYear;
|
|
336
|
+
const figures = {
|
|
337
|
+
periodStart: isoFromSerial(ct600.B33),
|
|
338
|
+
periodEnd: isoFromSerial(ct600.M33),
|
|
339
|
+
associatedCompanies: admin.P14 ?? 0,
|
|
340
|
+
profitAndLoss,
|
|
341
|
+
nonTradingLoanRelationshipCredits: positive(workingSheet.K24),
|
|
342
|
+
depreciation: positive(workingSheet.I8),
|
|
343
|
+
amortisation: positive(workingSheet.I7),
|
|
344
|
+
entertaining: positive(workingSheet.I9),
|
|
345
|
+
donations: positive(results["MnthP&L"]?.B37),
|
|
346
|
+
directorsLoanOverdrawn: positive(-(results.PubBalSht?.E29 ?? 0)),
|
|
347
|
+
directorsLoanOpeningOverdrawn: positive(-(results.OpenAccounts?.E30 ?? 0)),
|
|
348
|
+
annualInvestmentAllowance: wholePounds(allowances.I15),
|
|
349
|
+
mainPoolAllowances: wholePounds((allowances.I16 ?? 0) + (allowances.I17 ?? 0) + Math.max(allowances.I18 ?? 0, 0)),
|
|
350
|
+
mainPoolBalancingCharges: wholePounds(Math.max(-(allowances.I18 ?? 0), 0)),
|
|
351
|
+
frankedInvestmentIncome: wholePounds(workingSheet.K29),
|
|
352
|
+
incomeTaxDeducted: workingSheet.K37 > 0 ? fromPence(toPence(workingSheet.K37)) : 0,
|
|
353
|
+
workingSheet: {
|
|
354
|
+
tradingProfit: workingSheet.K22 + positive(results["MnthP&L"]?.B37),
|
|
355
|
+
tradingLoss: Math.max((ct600.Q206 ?? 0) - positive(results["MnthP&L"]?.B37), 0),
|
|
356
|
+
corporationTax: workingSheet.K35 ?? 0,
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
const lossesBroughtForward = wholePounds(ct600.Z72);
|
|
360
|
+
if (lossesBroughtForward > 0) figures.lossesBroughtForward = lossesBroughtForward;
|
|
361
|
+
return figures;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Check the figures. Tax is worked only when taxDataByYear is given, so the refusals that depend
|
|
366
|
+
* on the charge (a trading loss, Income Tax deducted or tax paid beyond the charge) show too.
|
|
367
|
+
*
|
|
368
|
+
* @param {object} figures
|
|
369
|
+
* @param {object} [options]
|
|
370
|
+
* @param {string} [options.today] - ISO date; the period must end before it
|
|
371
|
+
* @param {Record<number, object>} [options.taxDataByYear] - parsed ltd-<FY>.toml files by financial year
|
|
372
|
+
* @returns {Array<{field: string, message: string, refusal: boolean}>} empty when the figures stand
|
|
373
|
+
*/
|
|
374
|
+
export function validateCt600Figures(figures, { today, taxDataByYear } = {}) {
|
|
375
|
+
const problems = figureProblems(figures, { today });
|
|
376
|
+
if (problems.length > 0 || !taxDataByYear) return problems;
|
|
377
|
+
try {
|
|
378
|
+
deriveCt600FromFigures(figures, taxDataByYear, { today });
|
|
379
|
+
} catch (error) {
|
|
380
|
+
if (!(error instanceof Ct600RefusedError)) throw error;
|
|
381
|
+
problems.push({ field: error.field ?? "figures", message: error.message, refusal: true });
|
|
382
|
+
}
|
|
383
|
+
return problems;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function workedEntry(sources, rule) {
|
|
387
|
+
return rule ? { sources, rule } : { sources };
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function refuseLoss(message, field) {
|
|
391
|
+
throw new Ct600RefusedError(message, field);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* The trading losses of the period and the pool brought forward, with each claim checked against
|
|
396
|
+
* what it draws on. A loss that no claim uses is carried forward.
|
|
397
|
+
*/
|
|
398
|
+
function workLosses({ figures, tradingLoss, profitsBeforeOtherDeductions, lossesBroughtForward, broughtForwardUsedAgainstTrading }) {
|
|
399
|
+
const usedAgainstTotalProfits = numberOrZero(figures.lossAgainstTotalProfits);
|
|
400
|
+
const broughtForwardAgainstTotalProfits = numberOrZero(figures.lossesBroughtForwardAgainstTotalProfits);
|
|
401
|
+
const carriedBack = numberOrZero(figures.lossCarriedBack);
|
|
402
|
+
const broughtForwardPool = lossesBroughtForward - broughtForwardUsedAgainstTrading;
|
|
403
|
+
if (usedAgainstTotalProfits > tradingLoss) {
|
|
404
|
+
refuseLoss(
|
|
405
|
+
`The loss set against this period's total profits ${usedAgainstTotalProfits} is more than the trading loss of the period ${tradingLoss}`,
|
|
406
|
+
"lossAgainstTotalProfits",
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
if (broughtForwardAgainstTotalProfits > broughtForwardPool) {
|
|
410
|
+
refuseLoss(
|
|
411
|
+
`Losses brought forward claimed against total profits ${broughtForwardAgainstTotalProfits} are more than the ${broughtForwardPool} the trading profit leaves unused`,
|
|
412
|
+
"lossesBroughtForwardAgainstTotalProfits",
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
if (usedAgainstTotalProfits + broughtForwardAgainstTotalProfits > profitsBeforeOtherDeductions) {
|
|
416
|
+
refuseLoss(
|
|
417
|
+
`Losses claimed against total profits ${usedAgainstTotalProfits + broughtForwardAgainstTotalProfits} are more than the profits of the period ${profitsBeforeOtherDeductions}`,
|
|
418
|
+
usedAgainstTotalProfits > 0 ? "lossAgainstTotalProfits" : "lossesBroughtForwardAgainstTotalProfits",
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
if (carriedBack > tradingLoss - usedAgainstTotalProfits) {
|
|
422
|
+
refuseLoss(
|
|
423
|
+
`The loss carried back ${carriedBack} is more than the trading loss left after the claim against total profits, ${tradingLoss - usedAgainstTotalProfits}`,
|
|
424
|
+
"lossCarriedBack",
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
const carriedForwardFromPeriod = tradingLoss - usedAgainstTotalProfits - carriedBack;
|
|
428
|
+
const broughtForwardCarriedForward = broughtForwardPool - broughtForwardAgainstTotalProfits;
|
|
429
|
+
return {
|
|
430
|
+
arising: tradingLoss,
|
|
431
|
+
usedAgainstTotalProfits,
|
|
432
|
+
carriedBack,
|
|
433
|
+
carriedForwardFromPeriod,
|
|
434
|
+
broughtForward: lossesBroughtForward,
|
|
435
|
+
broughtForwardUsedAgainstTrading,
|
|
436
|
+
broughtForwardAgainstTotalProfits,
|
|
437
|
+
broughtForwardCarriedForward,
|
|
438
|
+
totalCarriedForward: carriedForwardFromPeriod + broughtForwardCarriedForward,
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function corporationTaxPenceOn(profits, years, totalDays, { taxData, fileFinancialYear, associatedCompanies }) {
|
|
443
|
+
const perYear = years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days));
|
|
444
|
+
const charge = apportionCorporationTax(profits, years, totalDays, { perYear, associatedCompanies });
|
|
445
|
+
const firstShare = years[1].days > 0 ? Math.round((profits * years[0].days) / totalDays) : profits;
|
|
446
|
+
const shares = [firstShare, profits - firstShare];
|
|
447
|
+
const pence = charge.rows.reduce((total, row, index) => total + (row.days > 0 ? shares[index] * row.ratePercent : 0), 0);
|
|
448
|
+
return pence - toPence(charge.marginalRelief);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* The carry-back claim against the twelve months before the period: the Corporation Tax the
|
|
453
|
+
* previous period paid on its chargeable profits less what it would have paid with the claim
|
|
454
|
+
* deducted, which is the repayment, and the boxes the previous period's return then carries.
|
|
455
|
+
*/
|
|
456
|
+
function workCarryBack(figures, losses, taxDataByYear) {
|
|
457
|
+
if (losses.carriedBack === 0) return undefined;
|
|
458
|
+
const priorProfits = numberOrZero(figures.priorPeriodChargeableProfits);
|
|
459
|
+
if (losses.carriedBack > priorProfits) {
|
|
460
|
+
refuseLoss(
|
|
461
|
+
`The loss carried back ${losses.carriedBack} is more than the previous period's chargeable profits ${priorProfits}`,
|
|
462
|
+
priorProfits === 0 ? "priorPeriodChargeableProfits" : "lossCarriedBack",
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
const priorStart = utcDate(figures.periodStart);
|
|
466
|
+
priorStart.setUTCFullYear(priorStart.getUTCFullYear() - 1);
|
|
467
|
+
const priorEnd = new Date(utcDate(figures.periodStart).getTime() - DAY_MS);
|
|
468
|
+
const fileFinancialYear = financialYearNumber(utcDate(figures.periodEnd));
|
|
469
|
+
const taxData = taxDataByYear?.[fileFinancialYear];
|
|
470
|
+
if (!taxData) refuseLoss(`No tax data is held for the financial year ${fileFinancialYear}`, "period");
|
|
471
|
+
const { years, totalDays } = financialYearsInPeriod(priorStart, priorEnd);
|
|
472
|
+
const options = { taxData, fileFinancialYear, associatedCompanies: numberOrZero(figures.associatedCompanies) };
|
|
473
|
+
let before;
|
|
474
|
+
let after;
|
|
475
|
+
try {
|
|
476
|
+
before = corporationTaxPenceOn(priorProfits, years, totalDays, options);
|
|
477
|
+
after = corporationTaxPenceOn(priorProfits - losses.carriedBack, years, totalDays, options);
|
|
478
|
+
} catch (error) {
|
|
479
|
+
refuseLoss(`The previous period's tax cannot be worked for the claim: ${error.message}`, "lossCarriedBack");
|
|
480
|
+
}
|
|
481
|
+
return {
|
|
482
|
+
amount: losses.carriedBack,
|
|
483
|
+
priorPeriodStart: priorStart.toISOString().slice(0, 10),
|
|
484
|
+
priorPeriodEnd: priorEnd.toISOString().slice(0, 10),
|
|
485
|
+
boxes: { 275: losses.carriedBack, 280: "yes" },
|
|
486
|
+
taxRepayable: fromPence(before - after),
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// The section 455 rates HMRC's online rules accept (RIM artefacts V1.994): the dividend upper rate
|
|
491
|
+
// from each date, until S455_RATES_IN_RIM_UNTIL.
|
|
492
|
+
export const S455_RATES_IN_RIM = [
|
|
493
|
+
{ from: "2016-04-06", rate: 0.325 },
|
|
494
|
+
{ from: "2022-04-06", rate: 0.3375 },
|
|
495
|
+
];
|
|
496
|
+
export const S455_RATES_IN_RIM_UNTIL = "2026-04-05";
|
|
497
|
+
|
|
498
|
+
export const S455_LATER_RATE_WARNING =
|
|
499
|
+
"Loans made on or after 6 April 2026 owe section 455 tax at 35.75%. HMRC's online rules accept only 33.75% until they move to RIM V1.995, so this return files at 33.75% and shows less tax than is due. Amend the return when HMRC accepts 35.75%.";
|
|
500
|
+
|
|
501
|
+
const LOAN_NAME_PATTERN = /^[^<>|"\\]{2,56}$/;
|
|
502
|
+
|
|
503
|
+
function validLoanName(name) {
|
|
504
|
+
return LOAN_NAME_PATTERN.test(name) && ![...name].some((character) => character < " ");
|
|
505
|
+
}
|
|
506
|
+
const MAX_LOAN_ROWS = 999;
|
|
507
|
+
const MAX_RATE_DECIMALS = 4;
|
|
508
|
+
|
|
509
|
+
function rimRateOn(isoDate) {
|
|
510
|
+
let rate;
|
|
511
|
+
for (const entry of S455_RATES_IN_RIM) if (entry.from <= isoDate) rate = entry.rate;
|
|
512
|
+
return rate;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function addDays(isoDate, days) {
|
|
516
|
+
const date = utcDate(isoDate);
|
|
517
|
+
date.setUTCDate(date.getUTCDate() + days);
|
|
518
|
+
return date.toISOString().slice(0, 10);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function isMonthEnd(isoDate) {
|
|
522
|
+
return addDays(isoDate, 1).endsWith("-01");
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// The same day of the month `months` later, or its last day when that month is shorter.
|
|
526
|
+
function addMonths(isoDate, months) {
|
|
527
|
+
const date = utcDate(isoDate);
|
|
528
|
+
const day = date.getUTCDate();
|
|
529
|
+
date.setUTCDate(1);
|
|
530
|
+
date.setUTCMonth(date.getUTCMonth() + months);
|
|
531
|
+
const lastDay = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate();
|
|
532
|
+
date.setUTCDate(Math.min(day, lastDay));
|
|
533
|
+
return date.toISOString().slice(0, 10);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function lastDayOfMonthsAfter(isoDate, months) {
|
|
537
|
+
const date = utcDate(isoDate);
|
|
538
|
+
date.setUTCDate(1);
|
|
539
|
+
date.setUTCMonth(date.getUTCMonth() + months + 1);
|
|
540
|
+
date.setUTCDate(0);
|
|
541
|
+
return date.toISOString().slice(0, 10);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// The latest date a repayment can come and still belong to part 2: nine months after the period
|
|
545
|
+
// end (rule 9406: before the first day of the tenth month when the period ends on a month end).
|
|
546
|
+
function part2LastDate(periodEnd) {
|
|
547
|
+
return isMonthEnd(periodEnd) ? lastDayOfMonthsAfter(periodEnd, 9) : addMonths(periodEnd, 9);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// The tax year (6 April to 5 April) a date falls in, named by the year it starts.
|
|
551
|
+
function taxYearStartOf(isoDate) {
|
|
552
|
+
const year = Number(isoDate.slice(0, 4));
|
|
553
|
+
return isoDate >= `${year}-04-06` ? year : year - 1;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// The day relief is due for a repayment on `repaymentDate`: nine months and a day after the end of
|
|
557
|
+
// the accounting period it falls in, taking the periods after the return's own as 12 months each.
|
|
558
|
+
function reliefDueDate(periodEnd, repaymentDate) {
|
|
559
|
+
let end = periodEnd;
|
|
560
|
+
while (end < repaymentDate) end = addMonths(end, 12);
|
|
561
|
+
return addDays(isMonthEnd(end) ? lastDayOfMonthsAfter(end, 9) : addMonths(end, 9), 1);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// Tax at a rate in pence, half up. The rate is a whole number of ten-thousandths.
|
|
565
|
+
function taxPence(pounds, rate) {
|
|
566
|
+
return Math.floor((pounds * Math.round(rate * 10_000) + 50) / 100);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function rateProblem(rate) {
|
|
570
|
+
if (!Number.isFinite(rate) || rate <= 0 || rate >= 1) return "must be between 0 and 1, for example 0.3375 for 33.75%";
|
|
571
|
+
if (Math.abs(rate * 10 ** MAX_RATE_DECIMALS - Math.round(rate * 10 ** MAX_RATE_DECIMALS)) > 1e-6) {
|
|
572
|
+
return `must have no more than ${MAX_RATE_DECIMALS} decimal places`;
|
|
573
|
+
}
|
|
574
|
+
return undefined;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function wholePoundProblem(value) {
|
|
578
|
+
return Number.isInteger(value) && value >= 0;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* The checks on the loans to participators answers, as messages. A problem is something the
|
|
583
|
+
* customer corrects; a refusal ends the return.
|
|
584
|
+
* @returns {Array<{field: string, message: string, refusal: boolean}>}
|
|
585
|
+
*/
|
|
586
|
+
function loansProblems(figures, { today } = {}) {
|
|
587
|
+
const problems = [];
|
|
588
|
+
const problem = (field, message, refusal = false) => problems.push({ field, message, refusal });
|
|
589
|
+
const loans = figures.loansToParticipators;
|
|
590
|
+
const overdrawn = numberOrZero(figures.directorsLoanOverdrawn);
|
|
591
|
+
const openingOverdrawn = numberOrZero(figures.directorsLoanOpeningOverdrawn);
|
|
592
|
+
if (!loans) {
|
|
593
|
+
if (figures.directorsLoanOverdrawn !== undefined && overdrawn > openingOverdrawn) {
|
|
594
|
+
problem(
|
|
595
|
+
"loansToParticipators",
|
|
596
|
+
`The account is ${overdrawn - openingOverdrawn} more overdrawn at the end than at the start, so the company lent in the period`,
|
|
597
|
+
);
|
|
598
|
+
}
|
|
599
|
+
return problems;
|
|
600
|
+
}
|
|
601
|
+
if (typeof loans !== "object" || Array.isArray(loans)) {
|
|
602
|
+
problem("loansToParticipators", "The loans to participators answer must be an object");
|
|
603
|
+
return problems;
|
|
604
|
+
}
|
|
605
|
+
const rows = Array.isArray(loans.loans) ? loans.loans : [];
|
|
606
|
+
const repayments = Array.isArray(loans.repayments) ? loans.repayments : [];
|
|
607
|
+
if (typeof loans.releasedBeforeEnd !== "boolean")
|
|
608
|
+
problem("loansToParticipators", "Say whether any loans made in the period were repaid, released or written off before its end");
|
|
609
|
+
if (rows.length === 0) problem("loansToParticipators", "Enter at least one loan to a participator, or answer that the company made none");
|
|
610
|
+
if (rows.length > MAX_LOAN_ROWS) problem("loansToParticipators", `At most ${MAX_LOAN_ROWS} loans can be entered`);
|
|
611
|
+
if (repayments.length > MAX_LOAN_ROWS) problem("loansToParticipators", `At most ${MAX_LOAN_ROWS} repayments can be entered`);
|
|
612
|
+
const names = new Set();
|
|
613
|
+
rows.forEach((row, index) => {
|
|
614
|
+
const label = `Loan ${index + 1}`;
|
|
615
|
+
if (typeof row?.name !== "string" || !validLoanName(row.name.trim())) {
|
|
616
|
+
problem("loansToParticipators", `${label}: the participator's name must be 2 to 56 characters without < > | " or \\`);
|
|
617
|
+
} else if (names.has(row.name.trim())) {
|
|
618
|
+
problem("loansToParticipators", `${label}: ${row.name.trim()} appears twice; enter one loan for each participator`);
|
|
619
|
+
} else {
|
|
620
|
+
names.add(row.name.trim());
|
|
621
|
+
}
|
|
622
|
+
if (!wholePoundProblem(row?.amount) || row.amount === 0)
|
|
623
|
+
problem("loansToParticipators", `${label}: the amount still owed must be whole pounds above 0`);
|
|
624
|
+
if (row?.lentFromRateChange !== undefined && (!wholePoundProblem(row.lentFromRateChange) || row.lentFromRateChange > row.amount)) {
|
|
625
|
+
problem(
|
|
626
|
+
"loansToParticipators",
|
|
627
|
+
`${label}: the amount lent on or after the rate change must be whole pounds and no more than the amount owed`,
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
if (row?.rate !== undefined) {
|
|
631
|
+
const rateMessage = rateProblem(row.rate);
|
|
632
|
+
if (rateMessage) problem("loansToParticipators", `${label}: the section 455 rate ${rateMessage}`);
|
|
633
|
+
}
|
|
634
|
+
});
|
|
635
|
+
const bookTotal = rows.reduce((total, row) => total + (Number.isInteger(row?.amount) ? row.amount : 0), 0);
|
|
636
|
+
if (figures.directorsLoanOverdrawn !== undefined && bookTotal > overdrawn) {
|
|
637
|
+
problem(
|
|
638
|
+
"loansToParticipators",
|
|
639
|
+
`The loans total ${bookTotal}, which is more than the ${overdrawn} the director's loan account is overdrawn at the end of the period`,
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
repayments.forEach((row, index) => {
|
|
643
|
+
const label = `Repayment ${index + 1}`;
|
|
644
|
+
if (!names.has(typeof row?.name === "string" ? row.name.trim() : ""))
|
|
645
|
+
problem("loansToParticipators", `${label}: name a participator from the loans`);
|
|
646
|
+
if (!isIsoDate(row?.date)) problem("loansToParticipators", `${label}: enter the date as YYYY-MM-DD`);
|
|
647
|
+
if (!wholePoundProblem(row?.repaid) || !wholePoundProblem(row?.releasedOrWrittenOff)) {
|
|
648
|
+
problem("loansToParticipators", `${label}: the amounts must be whole pounds, 0 or more`);
|
|
649
|
+
} else if (row.repaid + row.releasedOrWrittenOff === 0) {
|
|
650
|
+
problem("loansToParticipators", `${label}: enter an amount repaid, or released or written off`);
|
|
651
|
+
}
|
|
652
|
+
});
|
|
653
|
+
const perName = new Map();
|
|
654
|
+
for (const row of repayments) {
|
|
655
|
+
const total =
|
|
656
|
+
(Number.isInteger(row?.repaid) ? row.repaid : 0) + (Number.isInteger(row?.releasedOrWrittenOff) ? row.releasedOrWrittenOff : 0);
|
|
657
|
+
perName.set(row?.name?.trim(), (perName.get(row?.name?.trim()) ?? 0) + total);
|
|
658
|
+
}
|
|
659
|
+
for (const row of rows) {
|
|
660
|
+
if ((perName.get(row?.name?.trim()) ?? 0) > (row?.amount ?? 0)) {
|
|
661
|
+
problem("loansToParticipators", `The repayments for ${row.name.trim()} are more than the loan of ${row.amount}`);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
for (const row of repayments) {
|
|
665
|
+
if (!isIsoDate(row?.date)) continue;
|
|
666
|
+
if (row.date <= figures.periodEnd) {
|
|
667
|
+
problem(
|
|
668
|
+
"loansToParticipators",
|
|
669
|
+
`The repayment on ${row.date} is on or before the end of the period; the period's own book records it`,
|
|
670
|
+
true,
|
|
671
|
+
);
|
|
672
|
+
} else if (today && row.date > today) {
|
|
673
|
+
problem("loansToParticipators", `The repayment on ${row.date} is after today`, true);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
return problems;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* The section 455 rate parts of a period: one part, or two when 6 April falls inside the period and
|
|
681
|
+
* the rate changes there (or HMRC's online rules stop knowing the rate there). Each part carries
|
|
682
|
+
* the rate the return files at, the rate the tax data holds, and any warning.
|
|
683
|
+
*/
|
|
684
|
+
function section455RateOf(taxDataByYear, year) {
|
|
685
|
+
const rate = taxDataByYear?.[year]?.dividend_tax?.higher_rate;
|
|
686
|
+
if (!Number.isFinite(rate)) {
|
|
687
|
+
throw new Ct600RefusedError(`No section 455 rate is held for the tax year starting 6 April ${year}`, "loansToParticipators");
|
|
688
|
+
}
|
|
689
|
+
return rate;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* The 6 April inside a period at which the section 455 rate changes, or at which HMRC's online
|
|
694
|
+
* rules stop knowing it; undefined when the period has no such date.
|
|
695
|
+
* @param {string} periodStart - ISO date
|
|
696
|
+
* @param {string} periodEnd - ISO date
|
|
697
|
+
* @param {Record<number, object>} taxDataByYear
|
|
698
|
+
* @returns {string|undefined}
|
|
699
|
+
*/
|
|
700
|
+
export function section455RateChangeDate(periodStart, periodEnd, taxDataByYear) {
|
|
701
|
+
const startYear = taxYearStartOf(periodStart);
|
|
702
|
+
const endYear = taxYearStartOf(periodEnd);
|
|
703
|
+
const changeDate = `${endYear}-04-06`;
|
|
704
|
+
const crosses =
|
|
705
|
+
endYear > startYear &&
|
|
706
|
+
changeDate > periodStart &&
|
|
707
|
+
(section455RateOf(taxDataByYear, startYear) !== section455RateOf(taxDataByYear, endYear) ||
|
|
708
|
+
changeDate === addDays(S455_RATES_IN_RIM_UNTIL, 1));
|
|
709
|
+
return crosses ? changeDate : undefined;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function section455Parts(periodStart, periodEnd, taxDataByYear) {
|
|
713
|
+
const changeDate = section455RateChangeDate(periodStart, periodEnd, taxDataByYear);
|
|
714
|
+
const starts = changeDate ? [periodStart, changeDate] : [periodStart];
|
|
715
|
+
return {
|
|
716
|
+
changeDate,
|
|
717
|
+
parts: starts.map((from) => {
|
|
718
|
+
const derived = section455RateOf(taxDataByYear, taxYearStartOf(from));
|
|
719
|
+
const rim = rimRateOn(from);
|
|
720
|
+
if (from > S455_RATES_IN_RIM_UNTIL) {
|
|
721
|
+
return { from, derived, rate: rimRate(), warning: S455_LATER_RATE_WARNING, source: "online-rules" };
|
|
722
|
+
}
|
|
723
|
+
if (derived !== rim) {
|
|
724
|
+
return {
|
|
725
|
+
from,
|
|
726
|
+
derived,
|
|
727
|
+
rate: rim,
|
|
728
|
+
warning: `The tax data and HMRC's rules disagree on the section 455 rate for ${from}`,
|
|
729
|
+
source: "online-rules",
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
return { from, derived, rate: derived, source: "tax-data" };
|
|
733
|
+
}),
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
function rimRate() {
|
|
738
|
+
return S455_RATES_IN_RIM[S455_RATES_IN_RIM.length - 1].rate;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* Part 1 to part 3 of supplementary page CT600A, loans to participators of a close company, and the
|
|
743
|
+
* boxes that follow from it: 95 (the page is attached), 480 (the section 455 tax, A80) and 485
|
|
744
|
+
* (relief claimed in part 3). Sets box 95, 480 and 485 on `boxes` and returns the page's boxes, or
|
|
745
|
+
* undefined when the company made no loans.
|
|
746
|
+
*
|
|
747
|
+
* @param {object} figures - loansToParticipators: { releasedBeforeEnd, loans: [{name, amount, lentFromRateChange?, rate?}], repayments: [{name, date, repaid, releasedOrWrittenOff}] }
|
|
748
|
+
* @param {Record<number, string|number>} boxes
|
|
749
|
+
* @param {Record<number, {sources: string[], rule?: string}>} worked
|
|
750
|
+
* @param {Record<number, object>} taxDataByYear - ltd-<year>.toml files by year; the dividend upper rate of the tax year of each loan
|
|
751
|
+
* @param {{today?: string}} [options] - ISO date; a repayment cannot come after it
|
|
752
|
+
* @returns {{ct600a: object|undefined, a80Pence: number}}
|
|
753
|
+
*/
|
|
754
|
+
export function workLoansToParticipators(figures, boxes, worked, taxDataByYear, { today } = {}) {
|
|
755
|
+
const loans = figures.loansToParticipators;
|
|
756
|
+
if (!loans) return { ct600a: undefined, a80Pence: 0 };
|
|
757
|
+
const problems = loansProblems(figures, { today });
|
|
758
|
+
const refusal = problems.find((entry) => entry.refusal);
|
|
759
|
+
if (refusal) throw new Ct600RefusedError(refusal.message, refusal.field);
|
|
760
|
+
if (problems.length > 0) throw new Error(problems[0].message);
|
|
761
|
+
|
|
762
|
+
const { periodStart, periodEnd } = figures;
|
|
763
|
+
const rows = loans.loans.map((row) => ({ ...row, name: row.name.trim() }));
|
|
764
|
+
const needsDerivedRate = rows.some((row) => row.rate === undefined);
|
|
765
|
+
const { changeDate, parts: derivedParts } = needsDerivedRate
|
|
766
|
+
? section455Parts(periodStart, periodEnd, taxDataByYear)
|
|
767
|
+
: { changeDate: undefined, parts: [] };
|
|
768
|
+
if (!changeDate && rows.some((row) => row.lentFromRateChange > 0 && row.rate === undefined)) {
|
|
769
|
+
throw new Error("A loan lent on or after a rate change needs a period that crosses one");
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// Each participator's loan as parts in the order they were lent, each at the rate the return files at.
|
|
773
|
+
const warnings = [];
|
|
774
|
+
const rateRows = rows.map((row) => {
|
|
775
|
+
if (row.rate !== undefined) {
|
|
776
|
+
return { name: row.name, parts: [{ amount: row.amount, rate: row.rate, source: "customer-entered" }] };
|
|
777
|
+
}
|
|
778
|
+
const lateAmount = changeDate ? (row.lentFromRateChange ?? 0) : 0;
|
|
779
|
+
const parts = [
|
|
780
|
+
{ amount: row.amount - lateAmount, from: derivedParts[0].from, part: derivedParts[0] },
|
|
781
|
+
...(changeDate ? [{ amount: lateAmount, from: derivedParts[1].from, part: derivedParts[1] }] : []),
|
|
782
|
+
].filter((entry) => entry.amount > 0 || derivedParts.length === 1);
|
|
783
|
+
for (const entry of parts) {
|
|
784
|
+
if (entry.part.warning && !warnings.includes(entry.part.warning)) warnings.push(entry.part.warning);
|
|
785
|
+
}
|
|
786
|
+
return {
|
|
787
|
+
name: row.name,
|
|
788
|
+
parts: parts.map((entry) => ({
|
|
789
|
+
amount: entry.amount,
|
|
790
|
+
rate: entry.part.rate,
|
|
791
|
+
source: entry.part.source,
|
|
792
|
+
from: entry.from,
|
|
793
|
+
...(entry.part.derived !== entry.part.rate ? { taxDataRate: entry.part.derived } : {}),
|
|
794
|
+
})),
|
|
795
|
+
};
|
|
796
|
+
});
|
|
797
|
+
|
|
798
|
+
const bucketTotals = new Map();
|
|
799
|
+
const addToBucket = (buckets, rate, amount) => buckets.set(rate, (buckets.get(rate) ?? 0) + amount);
|
|
800
|
+
for (const row of rateRows) for (const part of row.parts) addToBucket(bucketTotals, part.rate, part.amount);
|
|
801
|
+
const chargePence = (buckets) => [...buckets].reduce((total, [rate, amount]) => total + taxPence(amount, rate), 0);
|
|
802
|
+
|
|
803
|
+
const totalLoans = rows.reduce((total, row) => total + row.amount, 0);
|
|
804
|
+
const a20Pence = chargePence(bucketTotals);
|
|
805
|
+
|
|
806
|
+
// Repayments in date order, against each participator's parts in the order lent.
|
|
807
|
+
const remaining = new Map(rateRows.map((row) => [row.name, row.parts.map((part) => ({ ...part }))]));
|
|
808
|
+
const part2Last = part2LastDate(periodEnd);
|
|
809
|
+
const sortedRepayments = [...loans.repayments].sort((a, b) => a.date.localeCompare(b.date));
|
|
810
|
+
const partTwo = [];
|
|
811
|
+
const partThree = [];
|
|
812
|
+
for (const repayment of sortedRepayments) {
|
|
813
|
+
const row = { ...repayment, name: repayment.name.trim() };
|
|
814
|
+
if (row.date <= part2Last) {
|
|
815
|
+
partTwo.push(row);
|
|
816
|
+
} else {
|
|
817
|
+
const due = reliefDueDate(periodEnd, row.date);
|
|
818
|
+
if (today && due > today) {
|
|
819
|
+
throw new Ct600RefusedError(
|
|
820
|
+
`Relief on the repayment of ${row.date} is due on ${due}. Claim it from HMRC after that date.`,
|
|
821
|
+
"loansToParticipators",
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
partThree.push(row);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
const relieve = (list) => {
|
|
828
|
+
const allocated = new Map();
|
|
829
|
+
for (const row of list) {
|
|
830
|
+
let left = row.repaid + row.releasedOrWrittenOff;
|
|
831
|
+
for (const part of remaining.get(row.name)) {
|
|
832
|
+
const used = Math.min(left, part.amount);
|
|
833
|
+
if (used > 0) {
|
|
834
|
+
part.amount -= used;
|
|
835
|
+
left -= used;
|
|
836
|
+
addToBucket(allocated, part.rate, used);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return allocated;
|
|
841
|
+
};
|
|
842
|
+
const partTwoAllocated = relieve(partTwo);
|
|
843
|
+
const partThreeAllocated = relieve(partThree);
|
|
844
|
+
const a45Pence = Math.min(chargePence(partTwoAllocated), a20Pence);
|
|
845
|
+
const a70Pence = Math.min(chargePence(partThreeAllocated), a20Pence);
|
|
846
|
+
const a80Pence = Math.max(a20Pence - a45Pence - a70Pence, 0);
|
|
847
|
+
|
|
848
|
+
const grouped = (list) => {
|
|
849
|
+
const byName = new Map();
|
|
850
|
+
for (const row of list) {
|
|
851
|
+
const entry = byName.get(row.name) ?? { name: row.name, repaid: 0, releasedOrWrittenOff: 0, date: row.date };
|
|
852
|
+
entry.repaid += row.repaid;
|
|
853
|
+
entry.releasedOrWrittenOff += row.releasedOrWrittenOff;
|
|
854
|
+
if (row.date > entry.date) entry.date = row.date;
|
|
855
|
+
byName.set(row.name, entry);
|
|
856
|
+
}
|
|
857
|
+
return [...byName.values()];
|
|
858
|
+
};
|
|
859
|
+
const sum = (list, field) => list.reduce((total, row) => total + row[field], 0);
|
|
860
|
+
const reliefPart = (list, reliefPence) => {
|
|
861
|
+
if (list.length === 0) return undefined;
|
|
862
|
+
const repaid = sum(list, "repaid");
|
|
863
|
+
const released = sum(list, "releasedOrWrittenOff");
|
|
864
|
+
return { rows: grouped(list), repaid, releasedOrWrittenOff: released, total: repaid + released, relief: fromPence(reliefPence) };
|
|
865
|
+
};
|
|
866
|
+
const partTwoBoxes = reliefPart(partTwo, a45Pence);
|
|
867
|
+
const partThreeBoxes = reliefPart(partThree, a70Pence);
|
|
868
|
+
const outstanding = totalLoans - (partTwoBoxes?.total ?? 0) - (partThreeBoxes?.total ?? 0);
|
|
869
|
+
|
|
870
|
+
const ct600a = {
|
|
871
|
+
releasedBeforeEnd: loans.releasedBeforeEnd,
|
|
872
|
+
loans: rows.map((row) => ({ name: row.name, amount: row.amount })),
|
|
873
|
+
totalLoans,
|
|
874
|
+
taxChargeable: fromPence(a20Pence),
|
|
875
|
+
partTwo: partTwoBoxes,
|
|
876
|
+
partThree: partThreeBoxes,
|
|
877
|
+
...(outstanding > 0 ? { totalLoansOutstanding: outstanding } : {}),
|
|
878
|
+
taxPayable: fromPence(a80Pence),
|
|
879
|
+
rates: rateRows,
|
|
880
|
+
warnings,
|
|
881
|
+
};
|
|
882
|
+
|
|
883
|
+
boxes[95] = "yes";
|
|
884
|
+
boxes[480] = ct600a.taxPayable;
|
|
885
|
+
worked[480] = workedEntry(["A20", "A45", "A70"], "Box 480 is the tax in box A80 of supplementary page CT600A");
|
|
886
|
+
if (partThreeBoxes) {
|
|
887
|
+
boxes[485] = "yes";
|
|
888
|
+
worked[485] = workedEntry(["A70"], "Box 485 is ticked when box A70 is completed");
|
|
889
|
+
}
|
|
890
|
+
return { ct600a, a80Pence };
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* The capital allowance boxes: the annual investment allowance (690), the pools (688/689, 693/694,
|
|
895
|
+
* 695/700, 705/710) and the information boxes that carry no tax (735, 760, 775). Box 705 and box
|
|
896
|
+
* 695 each include the annual investment allowance claimed on that pool.
|
|
897
|
+
*/
|
|
898
|
+
function workCapitalAllowanceBoxes(figures, boxes, worked) {
|
|
899
|
+
const annualInvestmentAllowance = numberOrZero(figures.annualInvestmentAllowance);
|
|
900
|
+
const onSpecialRatePool = numberOrZero(figures.specialRatePoolAnnualInvestmentAllowance);
|
|
901
|
+
const classes = capitalAllowanceClassLines(figures);
|
|
902
|
+
const amounts = {
|
|
903
|
+
688: classes.fullExpensingAllowances,
|
|
904
|
+
689: classes.fullExpensingBalancingCharges,
|
|
905
|
+
690: annualInvestmentAllowance,
|
|
906
|
+
693: classes.specialRateAllowances,
|
|
907
|
+
694: classes.specialRateBalancingCharges,
|
|
908
|
+
695: classes.specialRatePoolAllowances + onSpecialRatePool,
|
|
909
|
+
700: classes.specialRatePoolBalancingCharges,
|
|
910
|
+
705: annualInvestmentAllowance - onSpecialRatePool + numberOrZero(figures.mainPoolAllowances),
|
|
911
|
+
710: numberOrZero(figures.mainPoolBalancingCharges),
|
|
912
|
+
735: numberOrZero(figures.annualInvestmentAllowanceOutsideTrade),
|
|
913
|
+
760: numberOrZero(figures.firstYearAllowanceExpenditure),
|
|
914
|
+
773: numberOrZero(figures.specialRateAllowanceExpenditure),
|
|
915
|
+
775: numberOrZero(figures.otherMachineryAndPlantExpenditure),
|
|
916
|
+
};
|
|
917
|
+
for (const [box, amount] of Object.entries(amounts)) if (amount > 0) boxes[box] = amount;
|
|
918
|
+
worked[705] = workedEntry(
|
|
919
|
+
["annualInvestmentAllowance", "mainPoolAllowances", "specialRatePoolAnnualInvestmentAllowance"],
|
|
920
|
+
"Box 705 includes the annual investment allowance in box 690, less the part claimed on the special rate pool",
|
|
921
|
+
);
|
|
922
|
+
worked[695] = workedEntry(
|
|
923
|
+
["specialRatePoolAllowances", "specialRatePoolAnnualInvestmentAllowance"],
|
|
924
|
+
"Box 695 includes the annual investment allowance claimed on the special rate pool",
|
|
925
|
+
);
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* The boxes from the trading profit down to the chargeable profits (155 to 315): the trading
|
|
930
|
+
* profit or loss, the losses brought forward, the claims against total profits and the donations.
|
|
931
|
+
* Fills boxes and worked, and returns the losses and the chargeable profits.
|
|
932
|
+
*/
|
|
933
|
+
function workProfitsAndReliefs(figures, computationLines, boxes, worked) {
|
|
934
|
+
const tradingProfit = Math.max(computationLines.adjustedProfit, 0);
|
|
935
|
+
const tradingLoss = Math.max(-computationLines.adjustedProfit, 0);
|
|
936
|
+
// Losses brought forward set against the trading profit by right (box 160); what the profit
|
|
937
|
+
// does not take stays in the pool, and a claim against total profits (box 285) can use it.
|
|
938
|
+
const lossesBroughtForward = numberOrZero(figures.lossesBroughtForward);
|
|
939
|
+
const broughtForwardUsedAgainstTrading = Math.min(lossesBroughtForward, tradingProfit);
|
|
940
|
+
if (tradingProfit > 0) {
|
|
941
|
+
boxes[155] = tradingProfit;
|
|
942
|
+
worked[155] = workedEntry(
|
|
943
|
+
[
|
|
944
|
+
"profitAndLoss",
|
|
945
|
+
"nonTradingLoanRelationshipCredits",
|
|
946
|
+
"depreciation",
|
|
947
|
+
"amortisation",
|
|
948
|
+
"entertaining",
|
|
949
|
+
"donations",
|
|
950
|
+
"annualInvestmentAllowance",
|
|
951
|
+
"mainPoolAllowances",
|
|
952
|
+
"mainPoolBalancingCharges",
|
|
953
|
+
"fullExpensingAllowances",
|
|
954
|
+
"fullExpensingBalancingCharges",
|
|
955
|
+
"specialRateAllowances",
|
|
956
|
+
"specialRateBalancingCharges",
|
|
957
|
+
"specialRatePoolAllowances",
|
|
958
|
+
"specialRatePoolBalancingCharges",
|
|
959
|
+
],
|
|
960
|
+
"Box 155 equals the computation's adjusted profit",
|
|
961
|
+
);
|
|
962
|
+
if (broughtForwardUsedAgainstTrading > 0) boxes[160] = broughtForwardUsedAgainstTrading;
|
|
963
|
+
boxes[165] = tradingProfit - broughtForwardUsedAgainstTrading;
|
|
964
|
+
worked[165] = workedEntry(["155", "160"]);
|
|
965
|
+
}
|
|
966
|
+
const bankInterest = computationLines.nonTradingLoanRelationshipCredits;
|
|
967
|
+
if (bankInterest > 0) boxes[170] = bankInterest;
|
|
968
|
+
const profitsBeforeOtherDeductions = (boxes[165] ?? 0) + (boxes[170] ?? 0);
|
|
969
|
+
if (profitsBeforeOtherDeductions > 0) {
|
|
970
|
+
boxes[235] = profitsBeforeOtherDeductions;
|
|
971
|
+
worked[235] = workedEntry(["165", "170"]);
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
const losses = workLosses({ figures, tradingLoss, profitsBeforeOtherDeductions, lossesBroughtForward, broughtForwardUsedAgainstTrading });
|
|
975
|
+
if (tradingLoss > 0) {
|
|
976
|
+
boxes[figures.lossOutsideUk === true ? 790 : 780] = tradingLoss;
|
|
977
|
+
worked[figures.lossOutsideUk === true ? 790 : 780] = workedEntry(
|
|
978
|
+
["profitAndLoss"],
|
|
979
|
+
"The loss arising is the computation's adjusted loss",
|
|
980
|
+
);
|
|
981
|
+
}
|
|
982
|
+
if (losses.usedAgainstTotalProfits > 0) boxes[275] = losses.usedAgainstTotalProfits;
|
|
983
|
+
if (losses.broughtForwardAgainstTotalProfits > 0) boxes[285] = losses.broughtForwardAgainstTotalProfits;
|
|
984
|
+
const deductionsAndReliefs = losses.usedAgainstTotalProfits + losses.broughtForwardAgainstTotalProfits;
|
|
985
|
+
if (deductionsAndReliefs > 0) {
|
|
986
|
+
boxes[295] = deductionsAndReliefs;
|
|
987
|
+
worked[295] = workedEntry(["lossAgainstTotalProfits", "lossesBroughtForwardAgainstTotalProfits"], "Box 295 is boxes 275 and 285");
|
|
988
|
+
}
|
|
989
|
+
const profitsBeforeDonations = profitsBeforeOtherDeductions - deductionsAndReliefs;
|
|
990
|
+
if (profitsBeforeOtherDeductions > 0) {
|
|
991
|
+
boxes[300] = profitsBeforeDonations;
|
|
992
|
+
worked[300] = workedEntry(["235", "295"], "Box 300 is box 235 less box 295");
|
|
993
|
+
}
|
|
994
|
+
const qualifyingDonations = Math.min(computationLines.donations, Math.max(profitsBeforeDonations, 0));
|
|
995
|
+
if (qualifyingDonations > 0) {
|
|
996
|
+
boxes[305] = qualifyingDonations;
|
|
997
|
+
worked[305] = workedEntry(["donations", "300"], "Donations are claimed up to the profits in box 300");
|
|
998
|
+
}
|
|
999
|
+
const chargeableProfits = profitsBeforeDonations - qualifyingDonations;
|
|
1000
|
+
boxes[315] = chargeableProfits;
|
|
1001
|
+
worked[315] = workedEntry(["300", "305"], "Box 315 is box 300 less box 305");
|
|
1002
|
+
return { losses, chargeableProfits };
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
/**
|
|
1006
|
+
* Work the CT600 boxes and the computation lines for a small trading company. The tax rows follow
|
|
1007
|
+
* HMRC's rules from box 315: 9198 splits the profit between financial years by days, 9204 and
|
|
1008
|
+
* 9213 charge each share at its rate to the penny, and the marginal relief is diya-gl's own
|
|
1009
|
+
* calculation on the boxed profit. The working sheet's own trading profit and tax, or the figure
|
|
1010
|
+
* the customer worked out, must agree with the result to within £5.
|
|
1011
|
+
*
|
|
1012
|
+
* @param {object} figures
|
|
1013
|
+
* @param {Record<number, object>} taxDataByYear - parsed ltd-<FY>.toml files by financial year; the one named for the period end's financial year is required
|
|
1014
|
+
* @param {object} [options]
|
|
1015
|
+
* @param {string} [options.today] - ISO date; a repayment of a loan to a participator cannot come after it
|
|
1016
|
+
* @returns {{boxes: Record<number, string|number>, ct600a: object|undefined, computationLines: object, losses: object, carryBack: object|undefined, worked: Record<number, {sources: string[], rule?: string}>, periodStart: string, periodEnd: string}}
|
|
1017
|
+
*/
|
|
1018
|
+
export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
|
|
1019
|
+
const problems = figureProblems(figures);
|
|
1020
|
+
const refusal = problems.find((entry) => entry.refusal);
|
|
1021
|
+
if (refusal) throw new Ct600RefusedError(refusal.message, refusal.field);
|
|
1022
|
+
if (problems.length > 0) throw new Error(problems[0].message);
|
|
1023
|
+
|
|
1024
|
+
const { periodStart, periodEnd } = figures;
|
|
1025
|
+
const computationLines = computationLinesFromFigures(figures);
|
|
1026
|
+
|
|
1027
|
+
const worked = {};
|
|
1028
|
+
const boxes = {
|
|
1029
|
+
1: figures.companyName.trim(),
|
|
1030
|
+
2: figures.companyNumber,
|
|
1031
|
+
3: figures.utr,
|
|
1032
|
+
4: numberOrZero(figures.companyType),
|
|
1033
|
+
30: periodStart,
|
|
1034
|
+
35: periodEnd,
|
|
1035
|
+
145: figures.profitAndLoss.current.turnover,
|
|
1036
|
+
975: figures.declarantName.trim(),
|
|
1037
|
+
985: figures.declarantStatus.trim(),
|
|
1038
|
+
};
|
|
1039
|
+
|
|
1040
|
+
const workingSheet = figures.workingSheet;
|
|
1041
|
+
if (workingSheet && Math.abs(computationLines.adjustedProfit - workingSheet.tradingProfit) > WORKING_SHEET_TOLERANCE_POUNDS) {
|
|
1042
|
+
throw new Ct600RefusedError(
|
|
1043
|
+
`The computation's adjusted trading profit ${computationLines.adjustedProfit} disagrees with the working sheet's ${Math.round(workingSheet.tradingProfit)}`,
|
|
1044
|
+
"profitAndLoss",
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
const computedLoss = Math.max(-computationLines.adjustedProfit, 0);
|
|
1049
|
+
if (workingSheet?.tradingLoss !== undefined && Math.abs(computedLoss - workingSheet.tradingLoss) > WORKING_SHEET_TOLERANCE_POUNDS) {
|
|
1050
|
+
throw new Ct600RefusedError(
|
|
1051
|
+
`The computation's trading loss ${computedLoss} disagrees with the book's trading loss arising ${Math.round(workingSheet.tradingLoss)}`,
|
|
1052
|
+
"profitAndLoss",
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
workCapitalAllowanceBoxes(figures, boxes, worked);
|
|
1057
|
+
|
|
1058
|
+
const { losses, chargeableProfits } = workProfitsAndReliefs(figures, computationLines, boxes, worked);
|
|
1059
|
+
|
|
1060
|
+
const { years, totalDays } = financialYearsInPeriod(utcDate(periodStart), utcDate(periodEnd));
|
|
1061
|
+
const straddles = years[1].days > 0;
|
|
1062
|
+
const associatedCompanies = numberOrZero(figures.associatedCompanies);
|
|
1063
|
+
const frankedInvestmentIncome = numberOrZero(figures.frankedInvestmentIncome);
|
|
1064
|
+
if (frankedInvestmentIncome > 0) boxes[620] = frankedInvestmentIncome;
|
|
1065
|
+
|
|
1066
|
+
let corporationTaxPence = 0;
|
|
1067
|
+
let marginalReliefPence = 0;
|
|
1068
|
+
if (chargeableProfits > 0) {
|
|
1069
|
+
const fileFinancialYear = financialYearNumber(utcDate(periodEnd));
|
|
1070
|
+
const taxData = taxDataByYear?.[fileFinancialYear];
|
|
1071
|
+
if (!taxData) throw new Ct600RefusedError(`No tax data is held for the financial year ${fileFinancialYear}`, "period");
|
|
1072
|
+
const perYear = years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days));
|
|
1073
|
+
const charge = apportionCorporationTax(chargeableProfits, years, totalDays, { perYear, associatedCompanies, frankedInvestmentIncome });
|
|
1074
|
+
const firstShare = straddles ? Math.round((chargeableProfits * years[0].days) / totalDays) : chargeableProfits;
|
|
1075
|
+
const shares = [firstShare, chargeableProfits - firstShare];
|
|
1076
|
+
const yearBoxes = [
|
|
1077
|
+
[330, 335, 340, 345],
|
|
1078
|
+
[380, 385, 390, 395],
|
|
1079
|
+
];
|
|
1080
|
+
years.forEach((year, index) => {
|
|
1081
|
+
if (index === 1 && !straddles) return;
|
|
1082
|
+
const [yearBox, profitBox, rateBox, taxBox] = yearBoxes[index];
|
|
1083
|
+
const ratePercent = charge.rows[index].ratePercent;
|
|
1084
|
+
boxes[yearBox] = year.year;
|
|
1085
|
+
boxes[profitBox] = shares[index];
|
|
1086
|
+
boxes[rateBox] = ratePercent;
|
|
1087
|
+
const taxPence = shares[index] * ratePercent;
|
|
1088
|
+
boxes[taxBox] = fromPence(taxPence);
|
|
1089
|
+
corporationTaxPence += taxPence;
|
|
1090
|
+
worked[profitBox] = workedEntry(["315"], "9198: the profit is split between financial years by days");
|
|
1091
|
+
worked[taxBox] = workedEntry(
|
|
1092
|
+
[String(profitBox), String(rateBox)],
|
|
1093
|
+
"9204 and 9213: each share is charged at its year's rate, to the penny",
|
|
1094
|
+
);
|
|
1095
|
+
});
|
|
1096
|
+
marginalReliefPence = toPence(charge.marginalRelief);
|
|
1097
|
+
const claimsSmallProfitsRateOrRelief =
|
|
1098
|
+
marginalReliefPence > 0 ||
|
|
1099
|
+
charge.rows.some(
|
|
1100
|
+
(row, index) =>
|
|
1101
|
+
row.days > 0 &&
|
|
1102
|
+
perYear[index].smallProfitsRatePercent < perYear[index].mainRatePercent &&
|
|
1103
|
+
row.ratePercent === perYear[index].smallProfitsRatePercent,
|
|
1104
|
+
);
|
|
1105
|
+
if (straddles) {
|
|
1106
|
+
boxes[327] = associatedCompanies;
|
|
1107
|
+
boxes[328] = associatedCompanies;
|
|
1108
|
+
} else {
|
|
1109
|
+
boxes[326] = associatedCompanies;
|
|
1110
|
+
}
|
|
1111
|
+
if (claimsSmallProfitsRateOrRelief) {
|
|
1112
|
+
boxes[329] = "yes";
|
|
1113
|
+
worked[329] = workedEntry(["315"]);
|
|
1114
|
+
}
|
|
1115
|
+
boxes[430] = fromPence(corporationTaxPence);
|
|
1116
|
+
worked[430] = workedEntry(["345", "395"]);
|
|
1117
|
+
if (marginalReliefPence > 0) {
|
|
1118
|
+
boxes[435] = fromPence(marginalReliefPence);
|
|
1119
|
+
worked[435] = workedEntry(["315", "associatedCompanies", "frankedInvestmentIncome"]);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
const netCorporationTaxPence = corporationTaxPence - marginalReliefPence;
|
|
1123
|
+
const netCorporationTax = fromPence(netCorporationTaxPence);
|
|
1124
|
+
if (workingSheet && Math.abs(netCorporationTax - workingSheet.corporationTax) > WORKING_SHEET_TOLERANCE_POUNDS) {
|
|
1125
|
+
throw new Ct600RefusedError(
|
|
1126
|
+
`The return's Corporation Tax ${netCorporationTax.toFixed(2)} disagrees with the working sheet's ${workingSheet.corporationTax.toFixed(2)}`,
|
|
1127
|
+
"corporationTax",
|
|
1128
|
+
);
|
|
1129
|
+
}
|
|
1130
|
+
const ownCorporationTax = figures.ownCorporationTax;
|
|
1131
|
+
if (
|
|
1132
|
+
ownCorporationTax !== undefined &&
|
|
1133
|
+
ownCorporationTax !== null &&
|
|
1134
|
+
Math.abs(netCorporationTax - ownCorporationTax) > WORKING_SHEET_TOLERANCE_POUNDS
|
|
1135
|
+
) {
|
|
1136
|
+
throw new Ct600RefusedError(
|
|
1137
|
+
`The return's Corporation Tax ${netCorporationTax.toFixed(2)} disagrees with your own working's ${Number(ownCorporationTax).toFixed(2)}`,
|
|
1138
|
+
"ownCorporationTax",
|
|
1139
|
+
);
|
|
1140
|
+
}
|
|
1141
|
+
boxes[440] = netCorporationTax;
|
|
1142
|
+
boxes[475] = boxes[440];
|
|
1143
|
+
for (const box of [440, 475]) worked[box] = workedEntry(["430", "435"]);
|
|
1144
|
+
const { ct600a, a80Pence } = workLoansToParticipators(figures, boxes, worked, taxDataByYear, { today });
|
|
1145
|
+
const totalChargePence = netCorporationTaxPence + a80Pence;
|
|
1146
|
+
boxes[510] = fromPence(totalChargePence);
|
|
1147
|
+
worked[510] = workedEntry(["475", "480"], "Box 510 is box 475 plus box 480");
|
|
1148
|
+
|
|
1149
|
+
const incomeTaxDeductedPence = toPence(numberOrZero(figures.incomeTaxDeducted));
|
|
1150
|
+
if (incomeTaxDeductedPence > netCorporationTaxPence) {
|
|
1151
|
+
throw new Ct600RefusedError(
|
|
1152
|
+
`Income Tax deducted ${fromPence(incomeTaxDeductedPence).toFixed(2)} is more than the Corporation Tax charged ${netCorporationTax.toFixed(2)}; the repayment boxes (bank details, 920 onward) are not filed here`,
|
|
1153
|
+
"incomeTaxDeducted",
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
if (incomeTaxDeductedPence > 0) boxes[515] = fromPence(incomeTaxDeductedPence);
|
|
1157
|
+
const taxPayablePence = totalChargePence - incomeTaxDeductedPence;
|
|
1158
|
+
boxes[525] = fromPence(taxPayablePence);
|
|
1159
|
+
boxes[528] = boxes[525];
|
|
1160
|
+
for (const box of [525, 528]) worked[box] = workedEntry(["440", "515"]);
|
|
1161
|
+
|
|
1162
|
+
const alreadyPaidPence = toPence(numberOrZero(figures.taxAlreadyPaid));
|
|
1163
|
+
if (alreadyPaidPence > taxPayablePence) {
|
|
1164
|
+
throw new Ct600RefusedError(
|
|
1165
|
+
"More tax was paid than the return charges; the repayment boxes (bank details, 920 onward) are not filed here",
|
|
1166
|
+
"taxAlreadyPaid",
|
|
1167
|
+
);
|
|
1168
|
+
}
|
|
1169
|
+
if (alreadyPaidPence > 0) boxes[595] = fromPence(alreadyPaidPence);
|
|
1170
|
+
boxes[600] = fromPence(taxPayablePence - alreadyPaidPence);
|
|
1171
|
+
worked[600] = workedEntry(["525", "595"]);
|
|
1172
|
+
|
|
1173
|
+
const carryBack = workCarryBack(figures, losses, taxDataByYear);
|
|
1174
|
+
return { boxes, ct600a, computationLines, losses, carryBack, worked, periodStart, periodEnd };
|
|
1175
|
+
}
|