@diy-accounting-uk/diya-submit 0.1.3 → 0.1.8
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 +10 -7
- package/lib/accounts-tools.js +1 -1
- package/lib/book-read-tools.js +134 -0
- package/lib/book-tools.js +155 -43
- package/lib/client-kind.js +44 -0
- package/lib/finance/bank-lines.js +4 -2
- package/lib/finance/paypal-statement-lines.js +117 -37
- package/lib/handoff-tools.js +135 -23
- package/lib/help-index.json +2959 -0
- package/lib/help-tools.js +111 -0
- package/lib/hosted-register-book.js +128 -0
- package/lib/hosted-tools.js +116 -16
- package/lib/hosted-write-tools.js +313 -0
- package/lib/http.js +3 -3
- package/lib/rules-data.json +1821 -0
- package/lib/rules-tools.js +165 -0
- package/lib/server.js +316 -63
- package/lib/submit-tools.js +200 -13
- package/lib/tool-annotations.js +4 -1
- package/lib/vat-tools.js +16 -2
- package/lib/vendored/app/services/ct600Figures.js +15 -19
- package/lib/vendored/app/services/microEntityAccounts.js +8 -6
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -40,10 +40,12 @@ Cowork), or in Claude Code:
|
|
|
40
40
|
claude mcp add --transport http diya-submit https://submit.diyaccounting.co.uk/mcp
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
-
The
|
|
43
|
+
The endpoint answers `initialize`, `ping` and `tools/list` without a token, so a client or a catalogue
|
|
44
|
+
can read the tools first. The first tool call without a token gets 401 with a `WWW-Authenticate`
|
|
45
|
+
challenge. The client finds the sign-in through `/.well-known/oauth-protected-resource/mcp`, registers itself, and
|
|
44
46
|
the user signs in with their Submit account. The ci form of the URL is
|
|
45
47
|
`https://ci-submit.diyaccounting.co.uk/mcp`. The hosted tool set is `HOSTED_TOOL_NAMES` in
|
|
46
|
-
`lib/hosted-tools.js`: `open_book` reads the
|
|
48
|
+
`lib/hosted-tools.js`: `open_book` reads the DIY Accounting Submit account only. The sign-in pair, the filesystem tools,
|
|
47
49
|
the practice tools that still take an HMRC token, and `run_for_clients` are not registered.
|
|
48
50
|
|
|
49
51
|
## HMRC fraud prevention data
|
|
@@ -64,12 +66,13 @@ HMRC requires data about the device behind each request. The two surfaces send d
|
|
|
64
66
|
| `request_hmrc_authorisation` | HMRC's sign-in link for this session. `services` is `vat` (the default) and `itsa`; `hmrcAccount` is `live` (the default) or `synthetic`. Answers `url`, `expiresAt`, `scope`, `hmrcAccount`. The user grants access on HMRC's pages; Submit keeps HMRC's tokens and renews the access token for the rest of the session. No token reaches the chat. |
|
|
65
67
|
| `list_vat_obligations` | VAT obligations for `vrn` (or `clientId`), filtered by `from`, `to`, `status`. Uses the session's HMRC authorisation; optional `hmrcAccount` (the authorisation's own by default), `govTestScenario`. |
|
|
66
68
|
| `submit_vat_return` | Files the seven confirmed boxes (`vatDueSales`, `vatDueAcquisitions`, `vatReclaimedCurrPeriod`, `totalValueSalesExVAT`, `totalValuePurchasesExVAT`, `totalValueGoodsSuppliedExVAT`, `totalAcquisitionsExVAT`) for `periodStart` to `periodEnd`, for `vatNumber` or `clientId`. Uses the session's HMRC authorisation. Answers `receipt`, `periodKey`, `receiptId`. |
|
|
67
|
-
| `get_vat_receipt` | A stored receipt by `name` (`<receiptId>.json`); optional `clientId`. |
|
|
68
|
-
| `
|
|
69
|
-
| `
|
|
69
|
+
| `get_vat_receipt` | A stored VAT return receipt by `name` (`<receiptId>.json`); optional `clientId`. Answers HMRC's `processingDate`, `formBundleNumber`, `paymentIndicator` and `chargeRefNumber`. |
|
|
70
|
+
| `list_accounts_receipts` | The signed-in account's newest 25 accounts filings, newest first, with `more: true` when there are older ones it does not list; optional `clientId`. Each accepted filing answers `name` (the receipt name `revision.revisesReceipt` takes), `companyNumber`, `periodStart`, `periodEnd`, `accountsType`, `status`, `revisedAccounts`, `filedWithCompanyTaxReturn`, `revisable` and `filedOn`, and `problem` with the reason when the receipt cannot be read or its filed document does not read as accounts; each rejected filing answers its `submissionNumber` and Companies House's `rejections`. Call it before revising accounts already filed. Hosted outside prod and on the local server. |
|
|
71
|
+
| `render_micro_entity_accounts_sandbox` | The rendered micro-entity iXBRL for confirmed figures, without reaching the Companies House gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `balanceSheet`, `averageEmployees`, `director`, `statementsAccepted`; optional `revision` (`originalDateOfApproval`, `nonCompliance`, `amendments`, and optionally `revisesReceipt`, the name of the accepted accounts receipt it revises, which the filing route checks) renders revised accounts that replace accounts already filed; optional `documentLanguage` (`cy` files the accounts in Welsh, for a company registered in Wales), `directorsAdvances` (one row per director: `name`, `terms`, `balanceAtStart`, `advanced`, `repaid`, `balanceAtEnd`, printed in the note on advances and credits to directors), and for a dormant company `dormant`, `dormantTradingStatus` (`neverTraded` or `noLongerTrading`), `shareClass` and `nominalValue`. |
|
|
72
|
+
| `render_small_company_accounts_sandbox` | The rendered small-company (FRS 102 section 1A) iXBRL for confirmed figures, without reaching the gateway. Inputs: `companyNumber`, `companyName`, `periodStart`, `periodEnd`, `averageEmployees`, `director`, `statementsAccepted` (four small-company statements) and `smallCompany` (`filleted`, `principalActivity`, `accountingPolicies`, `directors`, `balanceSheet`, `profitAndLoss`, `fixedAssetNote`); optional `revision` and `documentLanguage` as for the micro-entity render, and `smallCompany.directorsAdvances` (inside `smallCompany`, each row naming one of `smallCompany.directors`, closing at `balanceSheet.currentYear.amountsOwedByDirectors`). A dormant company files micro-entity accounts. |
|
|
70
73
|
| `request_companies_house_codes` | A link where the user types the Companies House codes instead of the chat. `kind` is `accounts`, `confirmation-statement` (with `directors` in filing order) or `confirmation-statement-data`; answers `entryId`, `url`, `expiresAt`. The entry lasts ten minutes and one filing call uses it up. With `clientIds` (no `companyNumber`) the page asks for one code per practice client and each client's filing call, including through `run_for_clients`, takes only its own. |
|
|
71
|
-
| `submit_micro_entity_accounts_sandbox` | Files the same figures with the codes the user typed on that link, named by `codesEntryId`; answers `submissionNumber`. |
|
|
72
|
-
| `submit_small_company_accounts_sandbox` | Files the small-company figures with the codes named by `codesEntryId`, for `companyNumber` or `clientId`; answers `submissionNumber`. Poll it with `poll_submission` kind `accounts`. |
|
|
74
|
+
| `submit_micro_entity_accounts_sandbox` | Files the same figures with the codes the user typed on that link, named by `codesEntryId`; answers `submissionNumber`. With `revision`, files revised accounts that replace accounts already filed for the same period. Takes the render tool's optional fields. |
|
|
75
|
+
| `submit_small_company_accounts_sandbox` | Files the small-company figures with the codes named by `codesEntryId`, for `companyNumber` or `clientId`; answers `submissionNumber`. Poll it with `poll_submission` kind `accounts`. With `revision`, files revised accounts that replace accounts already filed for the same period. Takes the render tool's optional fields. |
|
|
73
76
|
| `poll_submission` | The outcome of a Companies House filing, `kind` `accounts` or `confirmation-statement`, for a `submissionNumber`: `PENDING`, `ACCEPT` (with `receiptId`) or `REJECT` (with `rejections`). |
|
|
74
77
|
|
|
75
78
|
The filing tools call the deployed REST API at `DIYA_SUBMIT_BASE_URL` with the MCP's own sign-in bearer (`sign_in`), and poll a 202 answer to its terminal status. They validate required inputs before any request.
|
package/lib/accounts-tools.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// app/services/microEntityAccounts.js, shared with the nightly company
|
|
7
7
|
// book pull; this file re-exports it for the MCP tool registration.
|
|
8
8
|
// derive_company_tax_return: the Company Tax Return figures from the loaded
|
|
9
|
-
// Company book, the file the web "Fill from your
|
|
9
|
+
// Company book, the file the web "Fill from your records" card reads.
|
|
10
10
|
|
|
11
11
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
12
12
|
import { basename, dirname, resolve as resolvePath } from "node:path";
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
|
|
2
|
+
// Copyright (C) 2006-2026 DIY Accounting Limited
|
|
3
|
+
|
|
4
|
+
// book-read-tools.js -- diya-gl's read tools over the session's open DIYA-GL book: the report, the
|
|
5
|
+
// trial balance, the book checks, the ledger lines, the chart of accounts and the book's profile.
|
|
6
|
+
// Each calls the published @diy-accounting-uk/diya-gl tool's own handler with the session's book and
|
|
7
|
+
// lines; no engine code lives here. The titles and descriptions use Submit's customer wording.
|
|
8
|
+
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
|
|
11
|
+
import { LINE_GROUPINGS } from "@diy-accounting-uk/diya-gl/dist/app/lib/book-queries.js";
|
|
12
|
+
import { TOOLS as DIYA_GL_TOOLS } from "@diy-accounting-uk/diya-gl/dist/app/lib/mcp/diya-gl-tools.js";
|
|
13
|
+
|
|
14
|
+
import { READS } from "./tool-annotations.js";
|
|
15
|
+
|
|
16
|
+
// The open book alone, never a book or lines passed in a call: diya-gl's handlers take either.
|
|
17
|
+
function openBookOnly(session) {
|
|
18
|
+
if (!session.book || !session.lines) throw new Error("No book is loaded. Call open_book first.");
|
|
19
|
+
return { book: session.book, lines: session.lines };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function diyaGlRead(name) {
|
|
23
|
+
return (session, params = {}) => DIYA_GL_TOOLS[name].handler(openBookOnly(session), params);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const oneOrMany = (description) =>
|
|
27
|
+
z
|
|
28
|
+
.union([z.string(), z.array(z.string())])
|
|
29
|
+
.optional()
|
|
30
|
+
.describe(description);
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The read tools keyed by MCP name, in the shape server.js's TOOLS table uses; createServer
|
|
34
|
+
* registers them beside it.
|
|
35
|
+
*/
|
|
36
|
+
export const BOOK_READ_TOOLS = {
|
|
37
|
+
report: {
|
|
38
|
+
title: "Report a DIYA-GL book's figures",
|
|
39
|
+
annotations: READS,
|
|
40
|
+
description:
|
|
41
|
+
"Works out the figures of the open DIYA-GL book (one business's sales, purchases and bank lines for a year): " +
|
|
42
|
+
"the profit and loss account, the balance sheet, the tax and VAT figures and the compliance checks, each figure " +
|
|
43
|
+
"with the label the spreadsheet prints for it, and the book checks. Use this when the person asks what their " +
|
|
44
|
+
"profit, turnover, tax bill or VAT due is, or which lines make up a figure (entryNumbers). It does not change the " +
|
|
45
|
+
"book, file anything or contact HMRC.",
|
|
46
|
+
inputSchema: {
|
|
47
|
+
entryNumbers: z
|
|
48
|
+
.union([z.boolean(), z.array(z.string())])
|
|
49
|
+
.optional()
|
|
50
|
+
.describe(
|
|
51
|
+
"true gives every figure the entryNumbers of the lines behind it; a list of figure keys (for example " +
|
|
52
|
+
"section/profit-loss-account/sales-turnover) gives them to those figures only",
|
|
53
|
+
),
|
|
54
|
+
},
|
|
55
|
+
handler: diyaGlRead("report"),
|
|
56
|
+
},
|
|
57
|
+
trial_balance: {
|
|
58
|
+
title: "Trial balance of a DIYA-GL book",
|
|
59
|
+
annotations: READS,
|
|
60
|
+
description:
|
|
61
|
+
"Answers the trial balance of the open DIYA-GL book of a company: every account's balance in the debit or the credit " +
|
|
62
|
+
"column and the two totals, over the year, one month, one VAT quarter or a date range, with the year-end postings " +
|
|
63
|
+
"of the registers. Name an account to also get the lines and postings behind its balance. Use this when the " +
|
|
64
|
+
"person asks whether their trial balance balances, what an account's balance is, or what moved in a month. " +
|
|
65
|
+
"Company DIYA-GL books only. It does not change the book or contact HMRC.",
|
|
66
|
+
inputSchema: {
|
|
67
|
+
period: z
|
|
68
|
+
.enum(["year", "month", "vatQuarter", "custom"])
|
|
69
|
+
.optional()
|
|
70
|
+
.describe("year (the default), month, vatQuarter, or custom with from and to"),
|
|
71
|
+
month: z.string().optional().describe("YYYY-MM of the month, or of the VAT quarter's last month; needed for month and vatQuarter"),
|
|
72
|
+
from: z.string().optional().describe("First day, YYYY-MM-DD inclusive, for a custom range"),
|
|
73
|
+
to: z.string().optional().describe("Last day, YYYY-MM-DD inclusive, for a custom range"),
|
|
74
|
+
account: z.string().optional().describe("An account id (for example 1300); adds that account's postings"),
|
|
75
|
+
},
|
|
76
|
+
handler: diyaGlRead("trial_balance"),
|
|
77
|
+
},
|
|
78
|
+
checks: {
|
|
79
|
+
title: "Check a DIYA-GL book",
|
|
80
|
+
annotations: READS,
|
|
81
|
+
description:
|
|
82
|
+
"Answers every book check and warning over the open DIYA-GL book, each with its verdict (pass, warn or fail), what it " +
|
|
83
|
+
"means and the entryNumbers of the lines that fail it, with the pass, warn and fail counts. Use this when the " +
|
|
84
|
+
"person asks whether anything is wrong with their records, which entries fall outside the year, which sales " +
|
|
85
|
+
"have no invoice number, whether there are duplicates, or how near they are to the VAT threshold. It does not " +
|
|
86
|
+
"change the book or contact HMRC.",
|
|
87
|
+
inputSchema: {},
|
|
88
|
+
handler: diyaGlRead("checks"),
|
|
89
|
+
},
|
|
90
|
+
lines: {
|
|
91
|
+
title: "Read a DIYA-GL book's lines",
|
|
92
|
+
annotations: READS,
|
|
93
|
+
description:
|
|
94
|
+
"Reads the lines of the open DIYA-GL book (every sale, purchase, bank movement, payslip and journal entry, with " +
|
|
95
|
+
"its entryNumber, journal, account, date, amount, customer, supplier or payee, description, reference and VAT " +
|
|
96
|
+
"fields), filtered and optionally grouped with a count and a total in pence. Filters combine: journal, account, " +
|
|
97
|
+
"dates, text and reference. Use this when the person asks who their best customer is, which suppliers cost most, " +
|
|
98
|
+
"what they spent on something in a month, or for their largest sales or purchases. It does not change the book.",
|
|
99
|
+
inputSchema: {
|
|
100
|
+
journal: oneOrMany("The journals to keep: sales, purchases, bank, payroll or journal"),
|
|
101
|
+
accountMainID: oneOrMany("The account ids to keep, for example 4000 (the chart tool lists them)"),
|
|
102
|
+
from: z.string().optional().describe("The earliest date kept, YYYY-MM-DD inclusive"),
|
|
103
|
+
to: z.string().optional().describe("The latest date kept, YYYY-MM-DD inclusive"),
|
|
104
|
+
text: z.string().optional().describe("Text found in the customer, supplier or payee, or the description, ignoring case"),
|
|
105
|
+
documentReference: z.string().optional().describe("Text found in the reference, ignoring case"),
|
|
106
|
+
groupBy: z.enum(LINE_GROUPINGS).optional().describe("detailComment (customer or supplier), accountMainID or month (YYYY-MM)"),
|
|
107
|
+
top: z.number().int().min(1).optional().describe("Keep at most this many groups, or without groupBy the largest lines"),
|
|
108
|
+
},
|
|
109
|
+
handler: diyaGlRead("lines"),
|
|
110
|
+
},
|
|
111
|
+
chart: {
|
|
112
|
+
title: "Chart of accounts of a DIYA-GL book",
|
|
113
|
+
annotations: READS,
|
|
114
|
+
description:
|
|
115
|
+
"Answers the chart of accounts of the open DIYA-GL book: each account's id, name, group, class and normal side, for a " +
|
|
116
|
+
"company the accounts line it feeds, the spreadsheet column it lands in, how many lines post to it with their " +
|
|
117
|
+
"total in pence, and the report rows it reaches. Use this when the person asks which account to use for " +
|
|
118
|
+
"something, where a cost shows in their accounts, or which accounts have no activity. It does not change the book.",
|
|
119
|
+
inputSchema: {},
|
|
120
|
+
handler: diyaGlRead("chart"),
|
|
121
|
+
},
|
|
122
|
+
book: {
|
|
123
|
+
title: "Profile of a DIYA-GL book",
|
|
124
|
+
annotations: READS,
|
|
125
|
+
description:
|
|
126
|
+
"Answers the profile of the open DIYA-GL book: the product, the accounting period, the business (name, trade, address, " +
|
|
127
|
+
"VAT registration, cash or accruals basis), the tax settings, the bank accounts, the journals with their line " +
|
|
128
|
+
"counts and dates, and the registers it carries (directors, employees, debtors, creditors, fixed assets, " +
|
|
129
|
+
"dividends, members, opening balances, stock). Use this when the person asks what period their records cover, " +
|
|
130
|
+
"whether they are VAT registered, or who their directors or employees are. It does not change the book.",
|
|
131
|
+
inputSchema: {},
|
|
132
|
+
handler: diyaGlRead("book"),
|
|
133
|
+
},
|
|
134
|
+
};
|
package/lib/book-tools.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
// State: one loaded book per session, a plain object this module owns the
|
|
22
22
|
// shape of. open_book replaces it outright; save_book reads it.
|
|
23
23
|
|
|
24
|
+
import { randomUUID } from "node:crypto";
|
|
24
25
|
import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
|
|
25
26
|
import { basename, extname, resolve as resolvePath } from "node:path";
|
|
26
27
|
|
|
@@ -36,10 +37,11 @@ import { stampBook } from "@diy-accounting-uk/diya-gl/dist/app/lib/provenance.js
|
|
|
36
37
|
|
|
37
38
|
import { storedCredentials } from "./auth.js";
|
|
38
39
|
import { desktopClientHeaders } from "./client-headers.js";
|
|
40
|
+
import { UNKNOWN_CLIENT } from "./client-kind.js";
|
|
39
41
|
|
|
40
42
|
export const SAVE_FORMATS = ["diya-gl-dir", "diya-gl-zip", "json", "xlsx", "zip"];
|
|
41
43
|
|
|
42
|
-
// The
|
|
44
|
+
// The DIY Accounting Submit account forms of open_book/save_book reach DIY Accounting Submit's own storage routes
|
|
43
45
|
// (diyaGlListGet.js, diyaGlVersionGet.js, diyaGlPut.js), the same routes the spreadsheets site's
|
|
44
46
|
// DIYA-GL pages use, over the session's credentials. Configuration comes from the
|
|
45
47
|
// environment: DIYA_SUBMIT_BASE_URL, the same variable practice-tools.js and submit-tools.js read.
|
|
@@ -58,14 +60,21 @@ function baseUrl() {
|
|
|
58
60
|
* clientHeaders answers the headers a call to an HMRC route carries for HMRC's fraud prevention
|
|
59
61
|
* data (the stdio server reads its own machine; the hosted Lambda passes what the caller gives).
|
|
60
62
|
* @param {{credentials?: {accessToken: () => Promise<string>, idToken: () => Promise<string|null>},
|
|
61
|
-
* pollBudgetMs?: number|null, clientHeaders?: () => Promise<Object
|
|
62
|
-
*
|
|
63
|
+
* pollBudgetMs?: number|null, clientHeaders?: () => Promise<Object>, client?: string}} [options] - client is the
|
|
64
|
+
* assistant's kind from client-kind.js
|
|
65
|
+
* @returns {{client: string, book: Object|null, lines: Array|null, product: string|null, sourcePath: string|null,
|
|
63
66
|
* cloud: {bookId: string, clientId: string|null, etag: string}|null,
|
|
64
67
|
* credentials: {accessToken: () => Promise<string>, idToken: () => Promise<string|null>},
|
|
65
68
|
* pollBudgetMs: number|null, clientHeaders: () => Promise<Object>}}
|
|
66
69
|
*/
|
|
67
|
-
export function createSession({
|
|
70
|
+
export function createSession({
|
|
71
|
+
credentials = storedCredentials,
|
|
72
|
+
pollBudgetMs = null,
|
|
73
|
+
clientHeaders = desktopClientHeaders,
|
|
74
|
+
client = UNKNOWN_CLIENT,
|
|
75
|
+
} = {}) {
|
|
68
76
|
return {
|
|
77
|
+
client,
|
|
69
78
|
book: null,
|
|
70
79
|
lines: null,
|
|
71
80
|
product: null,
|
|
@@ -107,13 +116,11 @@ async function bookChecksFor(book, lines) {
|
|
|
107
116
|
* The summary open_book answers: what the book is, whose it is, which period
|
|
108
117
|
* it covers, how many lines it holds, and the check and warning counts.
|
|
109
118
|
*/
|
|
110
|
-
function summarise(session,
|
|
111
|
-
const { book, lines, product
|
|
119
|
+
function summarise(session, bookChecks) {
|
|
120
|
+
const { book, lines, product } = session;
|
|
112
121
|
const info = book.documentInfo ?? {};
|
|
113
122
|
const entity = book.entityInformation ?? {};
|
|
114
123
|
return {
|
|
115
|
-
kind,
|
|
116
|
-
sourcePath,
|
|
117
124
|
product,
|
|
118
125
|
entity: entity.organizationIdentifier ?? null,
|
|
119
126
|
period: { start: isoDate(info.periodCoveredStart), end: isoDate(info.periodCoveredEnd) },
|
|
@@ -124,14 +131,24 @@ function summarise(session, kind, bookChecks) {
|
|
|
124
131
|
}
|
|
125
132
|
|
|
126
133
|
/**
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
|
|
134
|
+
* The summary open_book answers, for the session's loaded book.
|
|
135
|
+
* @param {Object} session
|
|
136
|
+
*/
|
|
137
|
+
export async function loadedBookSummary(session) {
|
|
138
|
+
requireLoaded(session);
|
|
139
|
+
return summarise(session, await bookChecksFor(session.book, session.lines));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The metadata of each book saved in the DIY Accounting Submit account, most recently updated first, over the route
|
|
144
|
+
* the spreadsheets site's DIYA-GL pages list (GET /api/v1/books): every field the route stores,
|
|
145
|
+
* the etag a replacing save sends among them. clientId lists a practice client's book set instead
|
|
146
|
+
* of the practice's own.
|
|
130
147
|
* @param {Object} session
|
|
131
148
|
* @param {{clientId?: string}} params
|
|
132
|
-
* @returns {Promise<
|
|
149
|
+
* @returns {Promise<Object[]>}
|
|
133
150
|
*/
|
|
134
|
-
export async function
|
|
151
|
+
export async function listBookMetadata(session, { clientId } = {}) {
|
|
135
152
|
const query = clientId ? `?clientId=${encodeURIComponent(clientId)}` : "";
|
|
136
153
|
const response = await fetch(`${baseUrl()}/api/v1/books${query}`, {
|
|
137
154
|
headers: { Authorization: `Bearer ${await session.credentials.accessToken()}` },
|
|
@@ -140,11 +157,33 @@ export async function listBooks(session, { clientId } = {}) {
|
|
|
140
157
|
if (!response.ok) {
|
|
141
158
|
throw new Error(body?.message || `list_books failed with HTTP ${response.status}`);
|
|
142
159
|
}
|
|
143
|
-
return
|
|
160
|
+
return body.books ?? [];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* list_books: the saved books, most recently updated first, each as the bookId open_book takes,
|
|
165
|
+
* the title, the product and the period the book covers. The route's other fields (its versions,
|
|
166
|
+
* etags, sizes, times, retention and the account's entitlement) answer no question a person asks
|
|
167
|
+
* about their books, so the tool leaves them out.
|
|
168
|
+
* @param {Object} session
|
|
169
|
+
* @param {{clientId?: string}} params
|
|
170
|
+
* @returns {Promise<{books: Array<{bookId: string, title: string|null, product: string|null,
|
|
171
|
+
* period: {start: string|null, end: string|null}}>}>}
|
|
172
|
+
*/
|
|
173
|
+
export async function listBooks(session, { clientId } = {}) {
|
|
174
|
+
const books = await listBookMetadata(session, { clientId });
|
|
175
|
+
return {
|
|
176
|
+
books: books.map((book) => ({
|
|
177
|
+
bookId: book.bookId,
|
|
178
|
+
title: book.title ?? null,
|
|
179
|
+
product: book.product ?? null,
|
|
180
|
+
period: { start: isoDate(book.periodCoveredStart), end: isoDate(book.periodCoveredEnd) },
|
|
181
|
+
})),
|
|
182
|
+
};
|
|
144
183
|
}
|
|
145
184
|
|
|
146
185
|
/**
|
|
147
|
-
* The session's loaded book from the
|
|
186
|
+
* The session's loaded book from the DIY Accounting Submit account by book id, over the same route the spreadsheets
|
|
148
187
|
* site's DIYA-GL pages read (GET /api/v1/books/{bookId}/versions/latest). Replaces the session's
|
|
149
188
|
* loaded book and records the etag save_book's cloud form needs for its next if-match.
|
|
150
189
|
*/
|
|
@@ -169,7 +208,7 @@ async function openCloudBook(session, { bookId, clientId } = {}) {
|
|
|
169
208
|
session.sourcePath = null;
|
|
170
209
|
session.cloud = { bookId, clientId: clientId ?? null, etag: body.metadata.latestETag };
|
|
171
210
|
|
|
172
|
-
return summarise(session,
|
|
211
|
+
return summarise(session, await bookChecksFor(book, lines));
|
|
173
212
|
}
|
|
174
213
|
|
|
175
214
|
/**
|
|
@@ -220,7 +259,7 @@ export async function openBook(session, { path, cloud, bookId, clientId } = {})
|
|
|
220
259
|
session.product = product;
|
|
221
260
|
session.sourcePath = resolved;
|
|
222
261
|
|
|
223
|
-
return summarise(session,
|
|
262
|
+
return { kind, sourcePath: resolved, ...summarise(session, await bookChecksFor(book, lines)) };
|
|
224
263
|
}
|
|
225
264
|
|
|
226
265
|
function refuseUnlessValid(book, lines) {
|
|
@@ -258,24 +297,50 @@ function isoDateOrNull(value) {
|
|
|
258
297
|
return new Date(value).toISOString().slice(0, 10);
|
|
259
298
|
}
|
|
260
299
|
|
|
300
|
+
// An error from a cloud book route, carrying the HTTP status and the route's code so a caller can
|
|
301
|
+
// answer a stale version, a full account or an oversized book in its own words.
|
|
302
|
+
function cloudRouteError(response, body, fallback) {
|
|
303
|
+
const error = new Error(body?.message || fallback);
|
|
304
|
+
error.status = response.status;
|
|
305
|
+
error.code = body?.error?.code ?? body?.message ?? null;
|
|
306
|
+
return error;
|
|
307
|
+
}
|
|
308
|
+
|
|
261
309
|
/**
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
* session's last cloud open or save of this same bookId; a book saved here for the first time (no
|
|
265
|
-
* prior cloud open) sends none, matching a brand-new book on that route.
|
|
310
|
+
* A new cloud book's id: the version 4 UUID the storage route's book id pattern takes.
|
|
311
|
+
* @returns {string}
|
|
266
312
|
*/
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
const { book, lines } = session;
|
|
271
|
-
const info = book.documentInfo ?? {};
|
|
272
|
-
const entity = book.entityInformation ?? {};
|
|
313
|
+
export function newCloudBookId() {
|
|
314
|
+
return randomUUID();
|
|
315
|
+
}
|
|
273
316
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
317
|
+
/**
|
|
318
|
+
* The stored DIYA-GL zip of one version of a cloud book, and the book's metadata, over the route
|
|
319
|
+
* open_book's cloud form reads (GET /api/v1/books/{bookId}/versions/{version}).
|
|
320
|
+
* @param {Object} session
|
|
321
|
+
* @param {{bookId: string, clientId?: string|null, version: number|"latest"}} params
|
|
322
|
+
* @returns {Promise<{bytes: Buffer, metadata: Object}>}
|
|
323
|
+
*/
|
|
324
|
+
export async function readCloudVersion(session, { bookId, clientId, version }) {
|
|
325
|
+
const query = clientId ? `?clientId=${encodeURIComponent(clientId)}` : "";
|
|
326
|
+
const response = await fetch(`${baseUrl()}/api/v1/books/${encodeURIComponent(bookId)}/versions/${encodeURIComponent(version)}${query}`, {
|
|
327
|
+
headers: { Authorization: `Bearer ${await session.credentials.accessToken()}` },
|
|
328
|
+
});
|
|
329
|
+
const body = await response.json().catch(() => ({}));
|
|
330
|
+
if (!response.ok) throw cloudRouteError(response, body, `Reading version ${version} failed with HTTP ${response.status}`);
|
|
331
|
+
return { bytes: Buffer.from(body.zipBase64, "base64"), metadata: body.metadata };
|
|
332
|
+
}
|
|
277
333
|
|
|
278
|
-
|
|
334
|
+
/**
|
|
335
|
+
* Stores a DIYA-GL zip as the next version of a cloud book (PUT /api/v1/books/{bookId}). ifMatch is
|
|
336
|
+
* the etag of the version the zip replaces, or null for a new book. change says what made this
|
|
337
|
+
* version, for the version list and the activity record.
|
|
338
|
+
* @returns {Promise<Object>} the book's metadata after the write
|
|
339
|
+
*/
|
|
340
|
+
export async function putCloudZip(
|
|
341
|
+
session,
|
|
342
|
+
{ bookId, clientId, zipBytes, title, product, periodCoveredStart, periodCoveredEnd, ifMatch, change },
|
|
343
|
+
) {
|
|
279
344
|
const response = await fetch(`${baseUrl()}/api/v1/books/${encodeURIComponent(bookId)}`, {
|
|
280
345
|
method: "PUT",
|
|
281
346
|
headers: {
|
|
@@ -284,21 +349,68 @@ async function saveCloudBook(session, { bookId, clientId } = {}) {
|
|
|
284
349
|
...(ifMatch ? { "if-match": ifMatch } : {}),
|
|
285
350
|
},
|
|
286
351
|
body: JSON.stringify({
|
|
287
|
-
title
|
|
288
|
-
product
|
|
289
|
-
periodCoveredStart
|
|
290
|
-
periodCoveredEnd
|
|
352
|
+
title,
|
|
353
|
+
product,
|
|
354
|
+
periodCoveredStart,
|
|
355
|
+
periodCoveredEnd,
|
|
291
356
|
zipBase64: zipBytes.toString("base64"),
|
|
292
357
|
...(clientId ? { clientId } : {}),
|
|
358
|
+
...(change ? { change } : {}),
|
|
293
359
|
}),
|
|
294
360
|
});
|
|
295
361
|
const body = await response.json().catch(() => ({}));
|
|
296
|
-
if (!response.ok) {
|
|
297
|
-
|
|
298
|
-
|
|
362
|
+
if (!response.ok) throw cloudRouteError(response, body, `save_book (cloud) failed with HTTP ${response.status}`);
|
|
363
|
+
return body.metadata;
|
|
364
|
+
}
|
|
299
365
|
|
|
300
|
-
|
|
301
|
-
|
|
366
|
+
/**
|
|
367
|
+
* The DIYA-GL zip of a book and lines, with the report and the book checks computed from them: the
|
|
368
|
+
* bytes the cloud stores.
|
|
369
|
+
* @returns {Promise<Buffer>}
|
|
370
|
+
*/
|
|
371
|
+
export async function diyaGlZipOf(book, lines) {
|
|
372
|
+
const { results } = await bookChecksFor(book, lines);
|
|
373
|
+
const bookchecks = JSON.parse(bookChecksJson(results));
|
|
374
|
+
return Buffer.from(await writeDiyaGlZip({ book, lines, report: reportFor(book, lines), bookchecks }));
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* The session's loaded book to the DIY Accounting Submit account by book id, over the same route the spreadsheets
|
|
379
|
+
* site's DIYA-GL pages write (PUT /api/v1/books/{bookId}). Carries the if-match etag from the
|
|
380
|
+
* session's last cloud open or save of this same bookId; a book saved here for the first time (no
|
|
381
|
+
* prior cloud open), or one saved with newBook, sends none, matching a brand-new book on that route.
|
|
382
|
+
*/
|
|
383
|
+
async function saveCloudBook(session, { bookId, clientId, change, newBook = false } = {}) {
|
|
384
|
+
requireLoaded(session);
|
|
385
|
+
if (!bookId) throw new Error("save_book with cloud: true requires bookId");
|
|
386
|
+
const { book, lines } = session;
|
|
387
|
+
const info = book.documentInfo ?? {};
|
|
388
|
+
const entity = book.entityInformation ?? {};
|
|
389
|
+
|
|
390
|
+
const zipBytes = await diyaGlZipOf(book, lines);
|
|
391
|
+
const ifMatch = !newBook && session.cloud?.bookId === bookId ? session.cloud.etag : undefined;
|
|
392
|
+
const metadata = await putCloudZip(session, {
|
|
393
|
+
bookId,
|
|
394
|
+
clientId,
|
|
395
|
+
zipBytes,
|
|
396
|
+
title: entity.organizationIdentifier || bookId,
|
|
397
|
+
product: session.product,
|
|
398
|
+
periodCoveredStart: isoDateOrNull(info.periodCoveredStart),
|
|
399
|
+
periodCoveredEnd: isoDateOrNull(info.periodCoveredEnd),
|
|
400
|
+
ifMatch,
|
|
401
|
+
change,
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
session.cloud = { bookId, clientId: clientId ?? null, etag: metadata.latestETag };
|
|
405
|
+
return {
|
|
406
|
+
path: null,
|
|
407
|
+
format: "cloud",
|
|
408
|
+
bookId,
|
|
409
|
+
etag: metadata.latestETag,
|
|
410
|
+
version: metadata.latestVersion,
|
|
411
|
+
lineCount: lines.length,
|
|
412
|
+
bytes: zipBytes.length,
|
|
413
|
+
};
|
|
302
414
|
}
|
|
303
415
|
|
|
304
416
|
/**
|
|
@@ -308,13 +420,13 @@ async function saveCloudBook(session, { bookId, clientId } = {}) {
|
|
|
308
420
|
* engine's own interchange formats; xlsx and zip compose the product's
|
|
309
421
|
* workbook or package, which fetches the template from
|
|
310
422
|
* spreadsheets.diyaccounting.co.uk the first time it runs. With cloud: true,
|
|
311
|
-
* writes to the
|
|
423
|
+
* writes to the DIY Accounting Submit account by bookId instead (a practice client's book set
|
|
312
424
|
* with clientId).
|
|
313
425
|
* @param {Object} session
|
|
314
426
|
* @param {{path: string, format?: string} | {cloud: true, bookId: string, clientId?: string}} params
|
|
315
427
|
*/
|
|
316
|
-
export async function saveBook(session, { path, format, cloud, bookId, clientId } = {}) {
|
|
317
|
-
if (cloud) return saveCloudBook(session, { bookId, clientId });
|
|
428
|
+
export async function saveBook(session, { path, format, cloud, bookId, clientId, change, newBook } = {}) {
|
|
429
|
+
if (cloud) return saveCloudBook(session, { bookId, clientId, change, newBook });
|
|
318
430
|
if (!path) throw new Error("save_book requires a path, or cloud: true and bookId");
|
|
319
431
|
requireLoaded(session);
|
|
320
432
|
const { book, lines } = session;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
|
|
2
|
+
// Copyright (C) 2006-2026 DIY Accounting Limited
|
|
3
|
+
|
|
4
|
+
// client-kind.js -- the kind of assistant an MCP client is, from the name it gives in
|
|
5
|
+
// initialize's params.clientInfo.name. The kind is a product name, not personal data.
|
|
6
|
+
|
|
7
|
+
export const UNKNOWN_CLIENT = "unknown";
|
|
8
|
+
|
|
9
|
+
// Checked in order: the first kind with a word in the name wins.
|
|
10
|
+
const KIND_WORDS = [
|
|
11
|
+
["chatgpt", ["openai", "chatgpt"]],
|
|
12
|
+
["claude", ["claude", "anthropic"]],
|
|
13
|
+
["gemini", ["gemini", "google"]],
|
|
14
|
+
["copilot", ["copilot", "microsoft"]],
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The client kind for a clientInfo.name: chatgpt, claude, gemini, copilot, other for any other
|
|
19
|
+
* name, or unknown when the client gave no name.
|
|
20
|
+
* @param {unknown} name
|
|
21
|
+
* @returns {"chatgpt"|"claude"|"gemini"|"copilot"|"other"|"unknown"}
|
|
22
|
+
*/
|
|
23
|
+
export function clientKindOf(name) {
|
|
24
|
+
if (typeof name !== "string" || name.trim() === "") return UNKNOWN_CLIENT;
|
|
25
|
+
const lower = name.toLowerCase();
|
|
26
|
+
for (const [kind, words] of KIND_WORDS) {
|
|
27
|
+
if (words.some((word) => lower.includes(word))) return kind;
|
|
28
|
+
}
|
|
29
|
+
return "other";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const CLIENT_NAME_LOG_LENGTH = 64;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The client's own name as the session log records it: printable ASCII only, each other character
|
|
36
|
+
* shown as "?", cut to CLIENT_NAME_LOG_LENGTH characters, or null when the client gave no name. A
|
|
37
|
+
* client chooses its name, so the log never takes it whole.
|
|
38
|
+
* @param {unknown} name
|
|
39
|
+
* @returns {string|null}
|
|
40
|
+
*/
|
|
41
|
+
export function clientNameForLog(name) {
|
|
42
|
+
if (typeof name !== "string" || name.trim() === "") return null;
|
|
43
|
+
return name.slice(0, CLIENT_NAME_LOG_LENGTH).replace(/[^\x20-\x7e]/g, "?");
|
|
44
|
+
}
|
|
@@ -75,12 +75,14 @@ function parseCsvLine(line) {
|
|
|
75
75
|
return fields;
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
// NatWest writes "31 Jul 2025"; the same CSV saved again by Excel holds "31-Jul-25".
|
|
78
79
|
function parseStatementDate(text) {
|
|
79
|
-
const match = /^(\d{2}) (\w{3}) (\d{4})$/.exec(text.trim());
|
|
80
|
+
const match = /^(\d{2}) (\w{3}) (\d{4})$/.exec(text.trim()) || /^(\d{2})-(\w{3})-(\d{2})$/.exec(text.trim());
|
|
80
81
|
if (!match) {
|
|
81
82
|
throw new Error(`Unrecognised statement date "${text}"`);
|
|
82
83
|
}
|
|
83
|
-
const [, day, monthName,
|
|
84
|
+
const [, day, monthName, yearDigits] = match;
|
|
85
|
+
const year = yearDigits.length === 2 ? `20${yearDigits}` : yearDigits;
|
|
84
86
|
const month = MONTHS[monthName];
|
|
85
87
|
if (!month) {
|
|
86
88
|
throw new Error(`Unrecognised statement month "${monthName}"`);
|