@deliverd/sdk 0.39.1 → 0.41.0
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/dist/adapters/index.d.ts +2 -0
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +1 -0
- package/dist/gates.d.ts +18 -1
- package/dist/gates.d.ts.map +1 -1
- package/dist/gates.js +29 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +19 -3
- package/dist/ledgers.d.ts +192 -0
- package/dist/ledgers.d.ts.map +1 -0
- package/dist/ledgers.js +672 -0
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +3132 -0
- package/dist/types.d.ts +24 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/adapters/index.ts +11 -0
- package/src/gates.ts +38 -0
- package/src/index.ts +17 -3
- package/src/ledgers.ts +733 -0
- package/src/released.ts +3133 -0
- package/src/types.ts +25 -0
package/src/ledgers.ts
ADDED
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Accounting ledgers: what an agent's call to Xero or QuickBooks Online is,
|
|
3
|
+
* in the words a finance approver and a policy rule use.
|
|
4
|
+
*
|
|
5
|
+
* Agents now write to the books. Xero's remote MCP server and its open-source
|
|
6
|
+
* one (`@xeroapi/xero-mcp-server`), Intuit's open-source QuickBooks server
|
|
7
|
+
* (`intuit/quickbooks-online-mcp-server`), and plain calls to both REST APIs
|
|
8
|
+
* can create payments, post journals and change a supplier's bank details.
|
|
9
|
+
* None of them asks anybody first. This module turns any of those calls into
|
|
10
|
+
* one of a handful of finance actions (approve a bill, record a payment,
|
|
11
|
+
* change a supplier's bank details...) with the amount, currency and
|
|
12
|
+
* counterparty pulled out, so a rule can say "over 5,000 needs two people"
|
|
13
|
+
* and mean it, whichever door the agent came through.
|
|
14
|
+
*
|
|
15
|
+
* It also reads what the ledgers' webhooks say, and turns a record the ledger
|
|
16
|
+
* sends back into a change worth watching, so a bill authorised or a bank
|
|
17
|
+
* account swapped with no yes behind it shows on the Enforcement panel.
|
|
18
|
+
*
|
|
19
|
+
* Three lines are held throughout:
|
|
20
|
+
*
|
|
21
|
+
* - **Pure, no imports.** This file is copied verbatim into
|
|
22
|
+
* `packages/sdk/src/ledgers.ts`, and a test fails when they differ, so an
|
|
23
|
+
* agent classifies its own calls the same way the hosted gateway does. The
|
|
24
|
+
* local MCP hook carries a JavaScript copy of the tool map
|
|
25
|
+
* (`integrations/agent-hooks/deliverd/ledgers.mjs`), held to the same cases.
|
|
26
|
+
* - **Unknown writes are still asked about.** A tool or route this file does
|
|
27
|
+
* not recognise but that changes something is `finance.ledger_write`, never
|
|
28
|
+
* waved through. Reads are never asked about.
|
|
29
|
+
* - **Bank details never travel whole.** Only masked forms (`•••• 1234`) are
|
|
30
|
+
* put in front of an approver or stored.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
export const LEDGERS = ["xero", "quickbooks"] as const;
|
|
34
|
+
export type Ledger = (typeof LEDGERS)[number];
|
|
35
|
+
|
|
36
|
+
export const LEDGER_LABEL: Record<Ledger, string> = { xero: "Xero", quickbooks: "QuickBooks Online" };
|
|
37
|
+
|
|
38
|
+
/** The finance actions, by the id policy keys on. `finance.*` in a rule catches every one. */
|
|
39
|
+
export const FINANCE_ACTIONS = {
|
|
40
|
+
approveBill: "finance.approve_bill",
|
|
41
|
+
recordPayment: "finance.record_payment",
|
|
42
|
+
postJournal: "finance.post_journal",
|
|
43
|
+
bankTransaction: "finance.bank_transaction",
|
|
44
|
+
supplierBankDetails: "finance.change_supplier_bank_details",
|
|
45
|
+
sendInvoice: "finance.send_invoice",
|
|
46
|
+
creditNote: "finance.issue_credit_note",
|
|
47
|
+
payroll: "finance.approve_payroll",
|
|
48
|
+
voidRecord: "finance.void_record",
|
|
49
|
+
ledgerWrite: "finance.ledger_write",
|
|
50
|
+
} as const;
|
|
51
|
+
export type FinanceActionId = (typeof FINANCE_ACTIONS)[keyof typeof FINANCE_ACTIONS];
|
|
52
|
+
|
|
53
|
+
export const FINANCE_ACTION_IDS: readonly FinanceActionId[] = Object.values(FINANCE_ACTIONS);
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* What every finance gate carries. One shape for all of them, so a rule
|
|
57
|
+
* written for one (`amount gte 5000`, `newCounterparty eq true`) reads the
|
|
58
|
+
* same on the others. Flat and primitive, because the action schema subset is.
|
|
59
|
+
*/
|
|
60
|
+
export interface LedgerInput {
|
|
61
|
+
ledger: Ledger;
|
|
62
|
+
/** What was called: `create-payment`, `POST /Payments`. */
|
|
63
|
+
tool: string;
|
|
64
|
+
recordType?: string;
|
|
65
|
+
amount?: number;
|
|
66
|
+
currency?: string;
|
|
67
|
+
counterparty?: string;
|
|
68
|
+
reference?: string;
|
|
69
|
+
recordId?: string;
|
|
70
|
+
status?: string;
|
|
71
|
+
/** The ledger has no earlier bill or payment for this counterparty. Set only when Deliverd could look. */
|
|
72
|
+
newCounterparty?: boolean;
|
|
73
|
+
/** The record is dated inside a period the ledger has locked. Set only when Deliverd could look. */
|
|
74
|
+
closedPeriod?: boolean;
|
|
75
|
+
/** The call changes where a supplier is paid. */
|
|
76
|
+
bankDetailsChanged?: boolean;
|
|
77
|
+
previousBankDetails?: string;
|
|
78
|
+
newBankDetails?: string;
|
|
79
|
+
/** What the approver should know, one finding a line: duplicates, recent bills. */
|
|
80
|
+
checks?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface LedgerCall {
|
|
84
|
+
actionId: FinanceActionId;
|
|
85
|
+
input: LedgerInput;
|
|
86
|
+
/** One line for the approval card and the agent: "Record a payment of 1,200.00 GBP to Acme". */
|
|
87
|
+
summary: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/* ─── reading values out of whatever shape the call came in ─────────────── */
|
|
91
|
+
|
|
92
|
+
type Rec = Record<string, unknown>;
|
|
93
|
+
const isRec = (v: unknown): v is Rec => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
94
|
+
const str = (v: unknown, max = 200): string | undefined => {
|
|
95
|
+
if (typeof v === "string" && v.trim()) return v.trim().slice(0, max);
|
|
96
|
+
if (typeof v === "number" && Number.isFinite(v)) return String(v);
|
|
97
|
+
return undefined;
|
|
98
|
+
};
|
|
99
|
+
const num = (v: unknown): number | undefined => {
|
|
100
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
101
|
+
if (typeof v === "string" && /^-?\d+(\.\d+)?$/.test(v.trim())) return Number(v.trim());
|
|
102
|
+
return undefined;
|
|
103
|
+
};
|
|
104
|
+
const round2 = (n: number): number => Math.round(n * 100) / 100;
|
|
105
|
+
|
|
106
|
+
/** Keys compared without case, underscores or dashes: `TotalAmt`, `total_amt`, `totalAmt` are one key. */
|
|
107
|
+
const norm = (k: string): string => k.toLowerCase().replace(/[_\-\s]/g, "");
|
|
108
|
+
|
|
109
|
+
function field(o: Rec, ...names: string[]): unknown {
|
|
110
|
+
const want = new Set(names.map(norm));
|
|
111
|
+
for (const [k, v] of Object.entries(o)) if (want.has(norm(k))) return v;
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The record a call is about. Xero wraps writes as `{ Invoices: [ … ] }`, the
|
|
117
|
+
* QuickBooks MCP server takes `{ bill: { … } }`, others pass the fields flat.
|
|
118
|
+
*/
|
|
119
|
+
const LINE_KEYS = new Set(["lineitems", "line", "lines", "journallines", "manualjournallines"]);
|
|
120
|
+
|
|
121
|
+
export function primaryRecord(args: unknown): Rec {
|
|
122
|
+
if (!isRec(args)) return {};
|
|
123
|
+
const keys = Object.keys(args);
|
|
124
|
+
if (keys.length <= 2) {
|
|
125
|
+
for (const k of keys) {
|
|
126
|
+
const v = args[k];
|
|
127
|
+
if (Array.isArray(v) && v.length && isRec(v[0]) && !LINE_KEYS.has(norm(k))) return v[0];
|
|
128
|
+
if (isRec(v) && keys.length === 1 && !/^(contact|vendor|customer|invoice|account)ref?$/i.test(k)) return v;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return args;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function nameOf(v: unknown): string | undefined {
|
|
135
|
+
if (isRec(v)) return str(field(v, "name", "displayName", "contactName")) ?? str(field(v, "value", "contactId", "id"));
|
|
136
|
+
return str(v);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function lineTotal(lines: unknown): number | undefined {
|
|
140
|
+
if (!Array.isArray(lines) || !lines.length) return undefined;
|
|
141
|
+
let total = 0;
|
|
142
|
+
let any = false;
|
|
143
|
+
for (const l of lines) {
|
|
144
|
+
if (!isRec(l)) continue;
|
|
145
|
+
const amount = num(field(l, "lineAmount", "amount"));
|
|
146
|
+
if (amount !== undefined) {
|
|
147
|
+
total += amount;
|
|
148
|
+
any = true;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
const qty = num(field(l, "quantity", "qty")) ?? 1;
|
|
152
|
+
const unit = num(field(l, "unitAmount", "unitPrice"));
|
|
153
|
+
if (unit !== undefined) {
|
|
154
|
+
total += qty * unit;
|
|
155
|
+
any = true;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return any ? round2(total) : undefined;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A journal's size: the sum of its debits (its positive lines, or lines marked Debit). */
|
|
162
|
+
function journalTotal(lines: unknown): number | undefined {
|
|
163
|
+
if (!Array.isArray(lines) || !lines.length) return undefined;
|
|
164
|
+
let debit = 0;
|
|
165
|
+
let any = false;
|
|
166
|
+
for (const l of lines) {
|
|
167
|
+
if (!isRec(l)) continue;
|
|
168
|
+
const detail = field(l, "journalEntryLineDetail");
|
|
169
|
+
const posting = isRec(detail) ? str(field(detail, "postingType")) : undefined;
|
|
170
|
+
const amount = num(field(l, "lineAmount", "amount"));
|
|
171
|
+
if (amount === undefined) continue;
|
|
172
|
+
any = true;
|
|
173
|
+
if (posting ? posting.toLowerCase() === "debit" : amount > 0) debit += Math.abs(amount);
|
|
174
|
+
}
|
|
175
|
+
return any ? round2(debit) : undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function amountOf(record: Rec): number | undefined {
|
|
179
|
+
const direct = num(field(record, "total", "totalAmt", "amount", "totalAmount"));
|
|
180
|
+
if (direct !== undefined) return round2(Math.abs(direct));
|
|
181
|
+
const journal = journalTotal(field(record, "journalLines", "manualJournalLines"));
|
|
182
|
+
if (journal !== undefined) return journal;
|
|
183
|
+
const lines = field(record, "lineItems", "line", "lines");
|
|
184
|
+
if (Array.isArray(lines) && lines.some((l) => isRec(l) && isRec(field(l, "journalEntryLineDetail")))) return journalTotal(lines);
|
|
185
|
+
return lineTotal(lines);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function currencyOf(record: Rec): string | undefined {
|
|
189
|
+
const c = field(record, "currencyCode", "currency", "currencyRef");
|
|
190
|
+
const code = isRec(c) ? str(field(c, "value")) : str(c);
|
|
191
|
+
return code && /^[A-Za-z]{3}$/.test(code) ? code.toUpperCase() : undefined;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Who a record is with: a name wherever one is given, and an id only when no
|
|
196
|
+
* name is. `self` is for a contact or vendor record, which names itself.
|
|
197
|
+
*/
|
|
198
|
+
export function counterpartyOf(record: Rec, self = false): string | undefined {
|
|
199
|
+
const refs = ["contact", "vendorRef", "customerRef", "entityRef", "payeeRef", "employeeRef"];
|
|
200
|
+
for (const key of refs) {
|
|
201
|
+
const v = field(record, key);
|
|
202
|
+
if (isRec(v)) {
|
|
203
|
+
const n = str(field(v, "name", "displayName", "contactName"));
|
|
204
|
+
if (n) return n;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const named = str(field(record, "contactName", "vendorName", "customerName", "payeeName", "employeeName"));
|
|
208
|
+
if (named) return named;
|
|
209
|
+
const invoice = field(record, "invoice");
|
|
210
|
+
if (isRec(invoice)) {
|
|
211
|
+
const n = counterpartyOf(invoice);
|
|
212
|
+
if (n) return n;
|
|
213
|
+
}
|
|
214
|
+
if (self) {
|
|
215
|
+
const n = selfName(record);
|
|
216
|
+
if (n) return n;
|
|
217
|
+
}
|
|
218
|
+
for (const key of refs) {
|
|
219
|
+
const v = field(record, key);
|
|
220
|
+
const id = isRec(v) ? str(field(v, "value", "contactId", "id")) : str(v);
|
|
221
|
+
if (id) return id;
|
|
222
|
+
}
|
|
223
|
+
return str(field(record, "contactId", "vendorId", "customerId", "employeeId"));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** A contact, vendor or employee record names itself. */
|
|
227
|
+
function selfName(record: Rec): string | undefined {
|
|
228
|
+
return str(field(record, "name", "displayName", "companyName", "fullName"));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** `YYYY-MM-DD` from an ISO date, a QuickBooks `TxnDate`, or Xero's `/Date(1731628800000+0000)/`. */
|
|
232
|
+
export function isoDay(v: unknown): string | undefined {
|
|
233
|
+
const s = str(v, 60);
|
|
234
|
+
if (!s) return undefined;
|
|
235
|
+
const ms = /^\/Date\((-?\d+)([+-]\d{4})?\)\/$/.exec(s);
|
|
236
|
+
if (ms) return new Date(Number(ms[1])).toISOString().slice(0, 10);
|
|
237
|
+
return /^\d{4}-\d{2}-\d{2}/.test(s) ? s.slice(0, 10) : undefined;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function dateOf(record: Rec): string | undefined {
|
|
241
|
+
return isoDay(field(record, "dateString", "txnDate", "date"));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function referenceOf(record: Rec): string | undefined {
|
|
245
|
+
return str(field(record, "reference", "invoiceNumber", "docNumber", "billNumber", "narration", "privateNote"), 120);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function recordIdOf(record: Rec): string | undefined {
|
|
249
|
+
return str(field(record, "invoiceId", "billId", "paymentId", "bankTransactionId", "manualJournalId", "contactId", "creditNoteId", "timesheetId", "id"), 100);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const BANK_KEYS = [
|
|
253
|
+
"bankAccountDetails",
|
|
254
|
+
"batchPayments",
|
|
255
|
+
"bankAccountNumber",
|
|
256
|
+
"bankAccountName",
|
|
257
|
+
"sortCode",
|
|
258
|
+
"iban",
|
|
259
|
+
"bsb",
|
|
260
|
+
"routingNumber",
|
|
261
|
+
"vendorPaymentBankDetail",
|
|
262
|
+
"acctNum",
|
|
263
|
+
"bankBranchIdentifier",
|
|
264
|
+
];
|
|
265
|
+
|
|
266
|
+
/** The bank details a call sets, flattened to one string, or undefined when it sets none. */
|
|
267
|
+
export function bankDetailsIn(record: Rec): string | undefined {
|
|
268
|
+
const parts: string[] = [];
|
|
269
|
+
const walk = (o: Rec, depth: number) => {
|
|
270
|
+
for (const [k, v] of Object.entries(o)) {
|
|
271
|
+
const n = norm(k);
|
|
272
|
+
if (BANK_KEYS.some((b) => norm(b) === n)) {
|
|
273
|
+
if (isRec(v)) walk(v, depth + 1);
|
|
274
|
+
else {
|
|
275
|
+
const s = str(v, 120);
|
|
276
|
+
if (s) parts.push(s);
|
|
277
|
+
}
|
|
278
|
+
} else if (depth > 0 && isRec(v)) walk(v, depth + 1);
|
|
279
|
+
else if (depth > 0) {
|
|
280
|
+
const s = str(v, 120);
|
|
281
|
+
if (s && /number|account|sort|bsb|iban|routing|branch/i.test(k)) parts.push(s);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
walk(record, 0);
|
|
286
|
+
return parts.length ? parts.join(" ") : undefined;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** `•••• 1234`: enough for a person to recognise an account, not enough to pay into it. */
|
|
290
|
+
export function maskAccount(value: string | undefined | null): string {
|
|
291
|
+
const digits = (value ?? "").replace(/[^0-9A-Za-z]/g, "");
|
|
292
|
+
if (!digits) return "none on file";
|
|
293
|
+
return `•••• ${digits.slice(-4)}`;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/* ─── tools: MCP servers and SDK tool calls ─────────────────────────────── */
|
|
297
|
+
|
|
298
|
+
/** `xero__create-payment`, `mcp__qbo__create_bill`, `create-payment` → `create_payment`. */
|
|
299
|
+
export function toolKey(tool: string): string {
|
|
300
|
+
const bare = tool.includes("__") ? tool.slice(tool.lastIndexOf("__") + 2) : tool;
|
|
301
|
+
return bare.toLowerCase().replace(/[-\s.]/g, "_");
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const READ_VERBS = /^(list|get|search|read|find|query|fetch|report|retrieve|download|show|describe|count|whoami|lookup)(_|$)/;
|
|
305
|
+
const WRITE_VERBS = /^(create|update|delete|remove|void|approve|revert|add|send|email|post|pay|authori[sz]e|submit|apply|allocate|reconcile|write|set|upsert|import|batch|archive|refund|transfer)(_|$)/;
|
|
306
|
+
|
|
307
|
+
const label = (actionId: FinanceActionId): string =>
|
|
308
|
+
({
|
|
309
|
+
"finance.approve_bill": "Approve a bill for payment",
|
|
310
|
+
"finance.record_payment": "Record a payment",
|
|
311
|
+
"finance.post_journal": "Post a journal",
|
|
312
|
+
"finance.bank_transaction": "Post a bank transaction",
|
|
313
|
+
"finance.change_supplier_bank_details": "Change a supplier's bank details",
|
|
314
|
+
"finance.send_invoice": "Issue or send an invoice",
|
|
315
|
+
"finance.issue_credit_note": "Issue a credit note or refund",
|
|
316
|
+
"finance.approve_payroll": "Approve payroll",
|
|
317
|
+
"finance.void_record": "Void or delete a ledger record",
|
|
318
|
+
"finance.ledger_write": "Change the ledger",
|
|
319
|
+
})[actionId];
|
|
320
|
+
|
|
321
|
+
export function financeActionLabel(actionId: string): string {
|
|
322
|
+
return (FINANCE_ACTION_IDS as readonly string[]).includes(actionId) ? label(actionId as FinanceActionId) : actionId;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function money(amount: number | undefined, currency: string | undefined): string {
|
|
326
|
+
if (amount === undefined) return "";
|
|
327
|
+
const n = amount.toLocaleString("en-GB", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
328
|
+
return currency ? `${n} ${currency}` : n;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export function summarise(call: { actionId: FinanceActionId; input: LedgerInput }): string {
|
|
332
|
+
const { input } = call;
|
|
333
|
+
const m = money(input.amount, input.currency);
|
|
334
|
+
const who = input.counterparty;
|
|
335
|
+
const base = label(call.actionId);
|
|
336
|
+
const parts = [base];
|
|
337
|
+
if (m) parts.push(`of ${m}`);
|
|
338
|
+
if (who) parts.push(call.actionId === FINANCE_ACTIONS.supplierBankDetails ? `for ${who}` : `${call.actionId === FINANCE_ACTIONS.sendInvoice || call.actionId === FINANCE_ACTIONS.creditNote ? "to" : "for"} ${who}`);
|
|
339
|
+
parts.push(`in ${LEDGER_LABEL[input.ledger]}`);
|
|
340
|
+
return parts.join(" ");
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function build(ledger: Ledger, tool: string, actionId: FinanceActionId, record: Rec, extra: Partial<LedgerInput> = {}): LedgerCall {
|
|
344
|
+
const input: LedgerInput = { ledger, tool: tool.slice(0, 200) };
|
|
345
|
+
const amount = amountOf(record);
|
|
346
|
+
if (amount !== undefined) input.amount = amount;
|
|
347
|
+
const currency = currencyOf(record);
|
|
348
|
+
if (currency) input.currency = currency;
|
|
349
|
+
const counterparty = counterpartyOf(record, /contact|vendor|supplier|employee/.test(extra.recordType ?? ""));
|
|
350
|
+
if (counterparty) input.counterparty = counterparty;
|
|
351
|
+
const reference = referenceOf(record);
|
|
352
|
+
if (reference) input.reference = reference;
|
|
353
|
+
const id = recordIdOf(record);
|
|
354
|
+
if (id) input.recordId = id;
|
|
355
|
+
const status = str(field(record, "status"), 40);
|
|
356
|
+
if (status) input.status = status.toUpperCase();
|
|
357
|
+
Object.assign(input, extra);
|
|
358
|
+
if (actionId === FINANCE_ACTIONS.supplierBankDetails) {
|
|
359
|
+
input.bankDetailsChanged = true;
|
|
360
|
+
const next = bankDetailsIn(record);
|
|
361
|
+
if (next) input.newBankDetails = maskAccount(next);
|
|
362
|
+
}
|
|
363
|
+
return { actionId, input, summary: summarise({ actionId, input }) };
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Which family a tool's noun belongs to, after the verb. */
|
|
367
|
+
function nounOf(key: string): string {
|
|
368
|
+
return key.replace(WRITE_VERBS, "").replace(/^_/, "");
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* One MCP tool call (or an SDK tool call with the same name), as a finance
|
|
373
|
+
* action. Null for a read: listing invoices or running a report asks nobody.
|
|
374
|
+
*/
|
|
375
|
+
export function classifyLedgerTool(ledger: Ledger, tool: string, args: unknown): LedgerCall | null {
|
|
376
|
+
const key = toolKey(tool);
|
|
377
|
+
if (READ_VERBS.test(key)) return null;
|
|
378
|
+
const record = primaryRecord(args);
|
|
379
|
+
const verb = key.split("_")[0] ?? "";
|
|
380
|
+
const noun = nounOf(key);
|
|
381
|
+
const status = (str(field(record, "status")) ?? "").toUpperCase();
|
|
382
|
+
const type = (str(field(record, "type")) ?? "").toUpperCase();
|
|
383
|
+
|
|
384
|
+
if (/^(delete|remove|void|archive)$/.test(verb) || status === "VOIDED" || status === "DELETED") {
|
|
385
|
+
if (noun.includes("timesheet") && verb === "delete") return build(ledger, tool, FINANCE_ACTIONS.ledgerWrite, record);
|
|
386
|
+
return build(ledger, tool, FINANCE_ACTIONS.voidRecord, record, { recordType: noun || undefined });
|
|
387
|
+
}
|
|
388
|
+
if (/payroll|payrun|pay_run|timesheet/.test(noun)) {
|
|
389
|
+
if (/^(approve|revert|post|submit)$/.test(verb) || /payrun|pay_run/.test(noun)) return build(ledger, tool, FINANCE_ACTIONS.payroll, record, { recordType: "payroll" });
|
|
390
|
+
return build(ledger, tool, FINANCE_ACTIONS.ledgerWrite, record, { recordType: "payroll" });
|
|
391
|
+
}
|
|
392
|
+
if (/(^|_)(contact|vendor|supplier|employee)s?$/.test(noun)) {
|
|
393
|
+
if (bankDetailsIn(record)) return build(ledger, tool, FINANCE_ACTIONS.supplierBankDetails, record, { recordType: noun.includes("vendor") || noun.includes("supplier") ? "vendor" : "contact" });
|
|
394
|
+
return build(ledger, tool, FINANCE_ACTIONS.ledgerWrite, record, { recordType: noun });
|
|
395
|
+
}
|
|
396
|
+
if (/payment/.test(noun) || verb === "pay") return build(ledger, tool, FINANCE_ACTIONS.recordPayment, record, { recordType: noun || "payment" });
|
|
397
|
+
if (/journal/.test(noun)) {
|
|
398
|
+
// A Xero manual journal can be saved as a draft; QuickBooks journals post when saved.
|
|
399
|
+
const posted = ledger === "quickbooks" || status === "POSTED" || verb === "post";
|
|
400
|
+
return build(ledger, tool, posted ? FINANCE_ACTIONS.postJournal : FINANCE_ACTIONS.ledgerWrite, record, { recordType: "journal" });
|
|
401
|
+
}
|
|
402
|
+
if (/bank_?transaction|bank_?transfer|purchase|expense|deposit|transfer|spend|receive_money/.test(noun)) return build(ledger, tool, FINANCE_ACTIONS.bankTransaction, record, { recordType: noun });
|
|
403
|
+
if (/credit_?note|credit_?memo|refund|vendor_?credit/.test(noun)) return build(ledger, tool, FINANCE_ACTIONS.creditNote, record, { recordType: noun });
|
|
404
|
+
if (/^(send|email)$/.test(verb) || /(^|_)send$|email$/.test(noun)) return build(ledger, tool, FINANCE_ACTIONS.sendInvoice, record, { recordType: "invoice" });
|
|
405
|
+
if (/bill/.test(noun)) {
|
|
406
|
+
// A QuickBooks bill is payable as soon as it is saved: entering one is approving it.
|
|
407
|
+
return build(ledger, tool, FINANCE_ACTIONS.approveBill, record, { recordType: "bill" });
|
|
408
|
+
}
|
|
409
|
+
if (/invoice/.test(noun)) {
|
|
410
|
+
if (type === "ACCPAY") return build(ledger, tool, status === "AUTHORISED" || verb === "approve" || verb === "authorise" ? FINANCE_ACTIONS.approveBill : FINANCE_ACTIONS.ledgerWrite, record, { recordType: "bill" });
|
|
411
|
+
if (status === "AUTHORISED" || verb === "approve" || verb === "authorise") return build(ledger, tool, FINANCE_ACTIONS.sendInvoice, record, { recordType: "invoice" });
|
|
412
|
+
return build(ledger, tool, FINANCE_ACTIONS.ledgerWrite, record, { recordType: "invoice" });
|
|
413
|
+
}
|
|
414
|
+
if (WRITE_VERBS.test(key)) return build(ledger, tool, FINANCE_ACTIONS.ledgerWrite, record, { recordType: noun || undefined });
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/* ─── REST: the ledger HTTP gateway ─────────────────────────────────────── */
|
|
419
|
+
|
|
420
|
+
/** The JSON body as a record, or {} when it is not JSON. */
|
|
421
|
+
function parseBody(body: string | null | undefined): unknown {
|
|
422
|
+
if (!body) return {};
|
|
423
|
+
try {
|
|
424
|
+
return JSON.parse(body);
|
|
425
|
+
} catch {
|
|
426
|
+
return {};
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* One REST request to a ledger, as a finance action. `path` is relative to
|
|
432
|
+
* the ledger's API root: `/api.xro/2.0/Invoices/…` for Xero, `/bill?…` for
|
|
433
|
+
* QuickBooks (whose root already names the company). Null for a read.
|
|
434
|
+
*/
|
|
435
|
+
export function classifyLedgerRequest(ledger: Ledger, method: string, path: string, body?: string | null): LedgerCall | null {
|
|
436
|
+
const m = method.toUpperCase();
|
|
437
|
+
const [rawPath = "", query = ""] = path.split("?");
|
|
438
|
+
const segments = rawPath.split("/").filter(Boolean).map((s) => s.toLowerCase());
|
|
439
|
+
const tool = `${m} ${rawPath}`.slice(0, 200);
|
|
440
|
+
if (["GET", "HEAD", "OPTIONS"].includes(m)) return null;
|
|
441
|
+
const parsed = parseBody(body);
|
|
442
|
+
const record = primaryRecord(parsed);
|
|
443
|
+
|
|
444
|
+
if (ledger === "quickbooks") {
|
|
445
|
+
const entity = segments[0] ?? "";
|
|
446
|
+
if (entity === "query" || entity === "reports" || entity === "cdc" || entity === "batch") {
|
|
447
|
+
if (entity === "batch") return build(ledger, tool, FINANCE_ACTIONS.ledgerWrite, record, { recordType: "batch" });
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
const operation = /(?:^|&)operation=([a-z]+)/i.exec(query)?.[1]?.toLowerCase();
|
|
451
|
+
if (m === "DELETE" || operation === "delete" || operation === "void") return build(ledger, tool, FINANCE_ACTIONS.voidRecord, record, { recordType: entity });
|
|
452
|
+
if (segments.includes("send")) return build(ledger, tool, FINANCE_ACTIONS.sendInvoice, record, { recordType: entity });
|
|
453
|
+
const verb = field(record, "id") !== undefined ? "update" : "create";
|
|
454
|
+
const call = classifyLedgerTool(ledger, `${verb}_${entity}`, record);
|
|
455
|
+
return call && { ...call, input: { ...call.input, tool } };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Xero: /api.xro/2.0/<Collection>[/<id>[/<sub>]], /payroll.xro/2.0/…
|
|
459
|
+
const at = segments.findIndex((s) => /\.xro$/.test(s));
|
|
460
|
+
const rest = at === -1 ? segments : segments.slice(at + 2);
|
|
461
|
+
const collection = rest[0] ?? "";
|
|
462
|
+
const sub = rest[2] ?? rest[1] ?? "";
|
|
463
|
+
const payroll = segments.some((s) => s.startsWith("payroll"));
|
|
464
|
+
const idIn = rest[1] && !/^(email|history|attachments|approve|revert|allocations)$/.test(rest[1]) ? rest[1] : undefined;
|
|
465
|
+
const withId = (call: LedgerCall | null): LedgerCall | null => {
|
|
466
|
+
if (!call) return call;
|
|
467
|
+
const input = { ...call.input, tool };
|
|
468
|
+
if (idIn && !input.recordId) input.recordId = idIn;
|
|
469
|
+
return { ...call, input, summary: summarise({ actionId: call.actionId, input }) };
|
|
470
|
+
};
|
|
471
|
+
if (/history|attachments/.test(sub)) return null;
|
|
472
|
+
if (m === "DELETE") return withId(build(ledger, tool, FINANCE_ACTIONS.voidRecord, record, { recordType: collection }));
|
|
473
|
+
if (payroll) return withId(classifyLedgerTool(ledger, `${/approve|revert/.test(sub) ? sub : "update"}_payroll_${collection}`, record));
|
|
474
|
+
if (sub === "email") return withId(build(ledger, tool, FINANCE_ACTIONS.sendInvoice, record, { recordType: "invoice" }));
|
|
475
|
+
const singular: Record<string, string> = {
|
|
476
|
+
invoices: "invoice",
|
|
477
|
+
payments: "payment",
|
|
478
|
+
batchpayments: "batch_payment",
|
|
479
|
+
overpayments: "payment",
|
|
480
|
+
prepayments: "payment",
|
|
481
|
+
banktransactions: "bank_transaction",
|
|
482
|
+
banktransfers: "bank_transfer",
|
|
483
|
+
manualjournals: "manual_journal",
|
|
484
|
+
contacts: "contact",
|
|
485
|
+
creditnotes: "credit_note",
|
|
486
|
+
purchaseorders: "purchase_order",
|
|
487
|
+
quotes: "quote",
|
|
488
|
+
items: "item",
|
|
489
|
+
accounts: "account",
|
|
490
|
+
};
|
|
491
|
+
const noun = singular[collection] ?? collection;
|
|
492
|
+
if (!noun) return null;
|
|
493
|
+
if (/^(allocations)$/.test(rest[2] ?? rest[1] ?? "")) return withId(build(ledger, tool, FINANCE_ACTIONS.recordPayment, record, { recordType: "allocation" }));
|
|
494
|
+
return withId(classifyLedgerTool(ledger, `${idIn ? "update" : "create"}_${noun}`, record));
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/* ─── webhooks ───────────────────────────────────────────────────────────── */
|
|
498
|
+
|
|
499
|
+
export interface LedgerEvent {
|
|
500
|
+
ledger: Ledger;
|
|
501
|
+
/** Xero's tenant id, or the QuickBooks company's realm id. */
|
|
502
|
+
tenantId: string;
|
|
503
|
+
/** `invoice`, `contact`, `bill`, `vendor`, `billpayment`, `journalentry`… lower case. */
|
|
504
|
+
entity: string;
|
|
505
|
+
entityId: string;
|
|
506
|
+
/** `create`, `update`, `delete`, `void`, `emailed`, `merge`. */
|
|
507
|
+
operation: string;
|
|
508
|
+
at: string;
|
|
509
|
+
/** Unique per event, for recording each once. */
|
|
510
|
+
eventId: string;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** Xero's batch: `{ events: [ { resourceId, tenantId, eventCategory, eventType, eventDateUtc } ] }`. */
|
|
514
|
+
export function parseXeroWebhook(body: unknown): LedgerEvent[] {
|
|
515
|
+
const events = isRec(body) && Array.isArray(body.events) ? body.events : [];
|
|
516
|
+
const out: LedgerEvent[] = [];
|
|
517
|
+
for (const e of events) {
|
|
518
|
+
if (!isRec(e)) continue;
|
|
519
|
+
const tenantId = str(e.tenantId, 100);
|
|
520
|
+
const entityId = str(e.resourceId, 100);
|
|
521
|
+
const entity = str(e.eventCategory, 40)?.toLowerCase();
|
|
522
|
+
const operation = str(e.eventType, 40)?.toLowerCase();
|
|
523
|
+
if (!tenantId || !entityId || !entity || !operation || str(e.tenantType)?.toUpperCase() === "APPLICATION") continue;
|
|
524
|
+
const at = str(e.eventDateUtc, 40) ?? new Date(0).toISOString();
|
|
525
|
+
out.push({ ledger: "xero", tenantId, entity, entityId, operation, at, eventId: `${entity}:${entityId}:${operation}:${at}` });
|
|
526
|
+
}
|
|
527
|
+
return out;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Intuit sends either format during its move to CloudEvents: a JSON array of
|
|
532
|
+
* CloudEvents (`type: "qbo.bill.created.v1"`, `intuitaccountid`,
|
|
533
|
+
* `intuitentityid`), or the older `{ eventNotifications: [ { realmId,
|
|
534
|
+
* dataChangeEvent: { entities: [ { name, id, operation, lastUpdated } ] } } ] }`.
|
|
535
|
+
*/
|
|
536
|
+
export function parseQuickbooksWebhook(body: unknown): LedgerEvent[] {
|
|
537
|
+
const out: LedgerEvent[] = [];
|
|
538
|
+
const op = (s: string): string => {
|
|
539
|
+
const o = s.toLowerCase();
|
|
540
|
+
return o === "created" ? "create" : o === "updated" ? "update" : o === "deleted" ? "delete" : o === "voided" ? "void" : o === "merged" ? "merge" : o;
|
|
541
|
+
};
|
|
542
|
+
if (Array.isArray(body)) {
|
|
543
|
+
for (const e of body) {
|
|
544
|
+
if (!isRec(e)) continue;
|
|
545
|
+
const type = str(e.type, 120) ?? "";
|
|
546
|
+
const t = /^qbo\.([a-z]+)\.([a-z]+)\b/i.exec(type);
|
|
547
|
+
const data = isRec(e.data) ? e.data : {};
|
|
548
|
+
const tenantId = str(e.intuitaccountid, 60) ?? str(field(data, "realmId", "accountId"), 60);
|
|
549
|
+
const entityId = str(e.intuitentityid, 60) ?? str(field(data, "id", "entityId"), 60);
|
|
550
|
+
if (!t || !tenantId || !entityId) continue;
|
|
551
|
+
const at = str(e.time, 40) ?? new Date(0).toISOString();
|
|
552
|
+
out.push({ ledger: "quickbooks", tenantId, entity: t[1]!.toLowerCase(), entityId, operation: op(t[2]!), at, eventId: str(e.id, 120) ?? `${t[1]}:${entityId}:${t[2]}:${at}` });
|
|
553
|
+
}
|
|
554
|
+
return out;
|
|
555
|
+
}
|
|
556
|
+
const notes = isRec(body) && Array.isArray(body.eventNotifications) ? body.eventNotifications : [];
|
|
557
|
+
for (const n of notes) {
|
|
558
|
+
if (!isRec(n)) continue;
|
|
559
|
+
const tenantId = str(n.realmId, 60);
|
|
560
|
+
const change = isRec(n.dataChangeEvent) ? n.dataChangeEvent : {};
|
|
561
|
+
const entities = Array.isArray(change.entities) ? change.entities : [];
|
|
562
|
+
for (const e of entities) {
|
|
563
|
+
if (!isRec(e) || !tenantId) continue;
|
|
564
|
+
const entity = str(e.name, 40)?.toLowerCase();
|
|
565
|
+
const entityId = str(e.id, 60);
|
|
566
|
+
const operation = str(e.operation, 20);
|
|
567
|
+
if (!entity || !entityId || !operation) continue;
|
|
568
|
+
const at = str(e.lastUpdated, 40) ?? new Date(0).toISOString();
|
|
569
|
+
out.push({ ledger: "quickbooks", tenantId, entity, entityId, operation: op(operation), at, eventId: `${entity}:${entityId}:${operation.toLowerCase()}:${at}` });
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return out;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** The record a ledger event names, as the ledger's API answers for it. Xero: `/Invoices/{id}`; QuickBooks: `/{entity}/{id}`. */
|
|
576
|
+
export function recordPath(event: Pick<LedgerEvent, "ledger" | "entity" | "entityId">): string | null {
|
|
577
|
+
const id = encodeURIComponent(event.entityId);
|
|
578
|
+
if (event.ledger === "xero") {
|
|
579
|
+
const map: Record<string, string> = { invoice: "Invoices", contact: "Contacts", creditnote: "CreditNotes" };
|
|
580
|
+
const c = map[event.entity];
|
|
581
|
+
return c ? `/api.xro/2.0/${c}/${id}` : null;
|
|
582
|
+
}
|
|
583
|
+
const watched = ["bill", "billpayment", "vendor", "journalentry", "purchase", "invoice", "creditmemo", "payment", "deposit", "transfer", "vendorcredit", "refundreceipt"];
|
|
584
|
+
return watched.includes(event.entity) ? `/${event.entity}/${id}` : null;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** The record out of the ledger's answer: Xero's `{ Invoices: [x] }`, QuickBooks' `{ Bill: x }`. */
|
|
588
|
+
export function unwrapRecord(answer: unknown): Rec {
|
|
589
|
+
if (!isRec(answer)) return {};
|
|
590
|
+
for (const v of Object.values(answer)) {
|
|
591
|
+
if (Array.isArray(v) && v.length && isRec(v[0])) return v[0];
|
|
592
|
+
if (isRec(v) && Object.keys(answer).length <= 2) return v;
|
|
593
|
+
}
|
|
594
|
+
return answer;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* A change worth watching, from an event and the record as it now stands.
|
|
599
|
+
* Null for one nobody needs to see: a draft saved, a contact's phone number.
|
|
600
|
+
*
|
|
601
|
+
* `previousBank` is the masked bank details Deliverd last saw on that
|
|
602
|
+
* contact (null the first time, which records a baseline and flags nothing).
|
|
603
|
+
*/
|
|
604
|
+
export interface LedgerChange {
|
|
605
|
+
actionId: FinanceActionId;
|
|
606
|
+
summary: string;
|
|
607
|
+
/** What a covering gate's input must mention. */
|
|
608
|
+
subjectTerms: string[];
|
|
609
|
+
/** A contact's bank details, masked: store it as the next baseline. */
|
|
610
|
+
bankNow?: string;
|
|
611
|
+
/** Nothing to record: only the baseline changed hands (the first sight of a contact, or no bank change). */
|
|
612
|
+
baselineOnly?: boolean;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
export function changeFrom(event: LedgerEvent, record: Rec, previousBank: string | null | undefined): LedgerChange | null {
|
|
616
|
+
const ledger = event.ledger;
|
|
617
|
+
const op = event.operation;
|
|
618
|
+
const status = (str(field(record, "status")) ?? "").toUpperCase();
|
|
619
|
+
const type = (str(field(record, "type")) ?? "").toUpperCase();
|
|
620
|
+
const amount = amountOf(record);
|
|
621
|
+
const currency = currencyOf(record);
|
|
622
|
+
const who = counterpartyOf(record, event.entity === "contact" || event.entity === "vendor");
|
|
623
|
+
const terms = (...t: (string | undefined)[]) => t.filter((x): x is string => !!x).map((x) => x.slice(0, 200));
|
|
624
|
+
const make = (actionId: FinanceActionId, recordType: string, extra: Partial<LedgerInput> = {}): LedgerChange => {
|
|
625
|
+
const input: LedgerInput = { ledger, tool: `${event.entity}.${op}`, recordType, ...(amount !== undefined ? { amount } : {}), ...(currency ? { currency } : {}), ...(who ? { counterparty: who } : {}), ...extra };
|
|
626
|
+
return { actionId, summary: summarise({ actionId, input }), subjectTerms: terms(who, amount !== undefined ? String(amount) : undefined) };
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
if (event.entity === "contact" || event.entity === "vendor") {
|
|
630
|
+
const bank = bankDetailsIn(record);
|
|
631
|
+
const now = bank ? maskAccount(bank) : undefined;
|
|
632
|
+
const bankNow = now ?? "none on file";
|
|
633
|
+
if (previousBank === null || previousBank === undefined || bankNow === previousBank) {
|
|
634
|
+
return { ...make(FINANCE_ACTIONS.ledgerWrite, event.entity), subjectTerms: [], bankNow, baselineOnly: true };
|
|
635
|
+
}
|
|
636
|
+
const c = make(FINANCE_ACTIONS.supplierBankDetails, event.entity, { previousBankDetails: previousBank, newBankDetails: bankNow });
|
|
637
|
+
return { ...c, summary: `${c.summary}: ${previousBank} → ${bankNow}`, subjectTerms: terms(who), bankNow };
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
if (op === "delete" || op === "void" || status === "VOIDED" || status === "DELETED") return make(FINANCE_ACTIONS.voidRecord, event.entity);
|
|
641
|
+
|
|
642
|
+
if (ledger === "xero") {
|
|
643
|
+
if (event.entity === "invoice" && type === "ACCPAY" && status === "AUTHORISED") return make(FINANCE_ACTIONS.approveBill, "bill");
|
|
644
|
+
if (event.entity === "invoice" && status === "PAID") return make(FINANCE_ACTIONS.recordPayment, type === "ACCPAY" ? "bill" : "invoice");
|
|
645
|
+
if (event.entity === "creditnote" && status === "AUTHORISED") return make(FINANCE_ACTIONS.creditNote, "credit_note");
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
// QuickBooks has no approval state: a bill saved is a bill to pay.
|
|
649
|
+
const map: Record<string, FinanceActionId> = {
|
|
650
|
+
bill: FINANCE_ACTIONS.approveBill,
|
|
651
|
+
billpayment: FINANCE_ACTIONS.recordPayment,
|
|
652
|
+
journalentry: FINANCE_ACTIONS.postJournal,
|
|
653
|
+
purchase: FINANCE_ACTIONS.bankTransaction,
|
|
654
|
+
deposit: FINANCE_ACTIONS.bankTransaction,
|
|
655
|
+
transfer: FINANCE_ACTIONS.bankTransaction,
|
|
656
|
+
creditmemo: FINANCE_ACTIONS.creditNote,
|
|
657
|
+
refundreceipt: FINANCE_ACTIONS.creditNote,
|
|
658
|
+
vendorcredit: FINANCE_ACTIONS.creditNote,
|
|
659
|
+
};
|
|
660
|
+
if (event.entity === "invoice" && op === "emailed") return make(FINANCE_ACTIONS.sendInvoice, "invoice");
|
|
661
|
+
const a = map[event.entity];
|
|
662
|
+
if (a && (op === "create" || op === "update")) return make(a, event.entity);
|
|
663
|
+
return null;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** Is this Xero record a bill waiting for someone to approve it? */
|
|
667
|
+
export function awaitingApproval(record: Rec): boolean {
|
|
668
|
+
return (str(field(record, "type")) ?? "").toUpperCase() === "ACCPAY" && (str(field(record, "status")) ?? "").toUpperCase() === "SUBMITTED";
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/* ─── what the approver should know ──────────────────────────────────────── */
|
|
672
|
+
|
|
673
|
+
export interface PastRecord {
|
|
674
|
+
id?: string;
|
|
675
|
+
reference?: string;
|
|
676
|
+
amount?: number;
|
|
677
|
+
date?: string;
|
|
678
|
+
status?: string;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
export interface CheckInput {
|
|
682
|
+
amount?: number;
|
|
683
|
+
currency?: string;
|
|
684
|
+
reference?: string;
|
|
685
|
+
recordId?: string;
|
|
686
|
+
/** The counterparty's recent records of the same kind, newest first. */
|
|
687
|
+
recent?: PastRecord[];
|
|
688
|
+
/** The record's date, `YYYY-MM-DD`. */
|
|
689
|
+
date?: string;
|
|
690
|
+
/** The ledger's lock date, `YYYY-MM-DD`: nothing on or before it should change. */
|
|
691
|
+
lockDate?: string | null;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* The findings an approver reads above Approve, and the flags rules key on.
|
|
696
|
+
* A duplicate is the same reference, or the same amount within 30 days.
|
|
697
|
+
*/
|
|
698
|
+
export function ledgerChecks(c: CheckInput): { checks: string[]; newCounterparty?: boolean; closedPeriod?: boolean } {
|
|
699
|
+
const checks: string[] = [];
|
|
700
|
+
const recent = (c.recent ?? []).filter((r) => !c.recordId || r.id !== c.recordId);
|
|
701
|
+
let newCounterparty: boolean | undefined;
|
|
702
|
+
if (c.recent) {
|
|
703
|
+
newCounterparty = recent.length === 0;
|
|
704
|
+
if (newCounterparty) checks.push("First record for this counterparty in the ledger.");
|
|
705
|
+
}
|
|
706
|
+
const day = (s: string | undefined) => (s ? Date.parse(s.slice(0, 10)) : NaN);
|
|
707
|
+
for (const r of recent) {
|
|
708
|
+
const sameRef = c.reference && r.reference && r.reference.trim().toLowerCase() === c.reference.trim().toLowerCase();
|
|
709
|
+
const near = Number.isFinite(day(r.date)) && Number.isFinite(day(c.date)) && Math.abs(day(r.date) - day(c.date)) <= 30 * 86_400_000;
|
|
710
|
+
const sameAmount = c.amount !== undefined && r.amount !== undefined && Math.abs(r.amount - c.amount) < 0.005;
|
|
711
|
+
if (sameRef || (sameAmount && near)) {
|
|
712
|
+
checks.push(`Possible duplicate of ${r.reference || r.id || "an earlier record"}${r.date ? ` dated ${r.date.slice(0, 10)}` : ""}${r.amount !== undefined ? ` for ${money(r.amount, c.currency)}` : ""}.`);
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
const amounts = recent.map((r) => r.amount).filter((a): a is number => a !== undefined);
|
|
717
|
+
if (c.amount !== undefined && amounts.length >= 2) {
|
|
718
|
+
const largest = Math.max(...amounts);
|
|
719
|
+
if (c.amount > largest * 2) checks.push(`More than twice the largest of the last ${amounts.length} (${money(largest, c.currency)}).`);
|
|
720
|
+
}
|
|
721
|
+
if (recent.length) {
|
|
722
|
+
checks.push(`Last ${Math.min(recent.length, 3)}: ${recent
|
|
723
|
+
.slice(0, 3)
|
|
724
|
+
.map((r) => [r.reference || r.id, r.date?.slice(0, 10), r.amount !== undefined ? money(r.amount, c.currency) : undefined].filter(Boolean).join(", "))
|
|
725
|
+
.join("; ")}.`);
|
|
726
|
+
}
|
|
727
|
+
let closedPeriod: boolean | undefined;
|
|
728
|
+
if (c.lockDate !== undefined) {
|
|
729
|
+
closedPeriod = !!(c.lockDate && c.date && c.date.slice(0, 10) <= c.lockDate.slice(0, 10));
|
|
730
|
+
if (closedPeriod) checks.push(`Dated in a locked period (locked to ${c.lockDate!.slice(0, 10)}).`);
|
|
731
|
+
}
|
|
732
|
+
return { checks, ...(newCounterparty !== undefined ? { newCounterparty } : {}), ...(closedPeriod !== undefined ? { closedPeriod } : {}) };
|
|
733
|
+
}
|