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