jaz-clio 5.47.4 → 5.47.6
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/assets/skills/api/SKILL.md +1 -1
- package/assets/skills/cli/SKILL.md +2 -2
- package/assets/skills/cli/references/command-catalog.md +65 -66
- package/assets/skills/cli/references/common-workflows.md +1 -1
- package/assets/skills/conversion/SKILL.md +1 -1
- package/assets/skills/jaz-kit/SKILL.md +1 -1
- package/assets/skills/jaz-pseudo-sql/SKILL.md +1 -1
- package/assets/skills/jobs/SKILL.md +1 -1
- package/assets/skills/transaction-recipes/SKILL.md +1 -1
- package/cli.mjs +3 -3
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: jaz-cli
|
|
3
|
-
version: 5.47.
|
|
3
|
+
version: 5.47.6
|
|
4
4
|
description: >-
|
|
5
5
|
Use this skill when running Clio CLI commands, building shell scripts with
|
|
6
6
|
Clio, debugging auth issues, understanding --json output, paginating results,
|
|
@@ -267,7 +267,7 @@ Sending `lineItems[]` to the FLAT endpoint silently ignores them and creates a $
|
|
|
267
267
|
|
|
268
268
|
**Reports & Exports**: `reports` (16 report types), `exports`
|
|
269
269
|
|
|
270
|
-
**AI & Automation**: `magic` (create, status
|
|
270
|
+
**AI & Automation**: `magic` (create, status), `quick-fix`, `capsules`, `capsule-transaction` (alias: `ct`, 13 recipe types)
|
|
271
271
|
|
|
272
272
|
**Judgment journal**: `jots` (create, recall, dispose). Every write command also takes `--jot "<one line>"` to log the judgment behind that specific write inline, no extra call (see `--jot` in Common Flags).
|
|
273
273
|
|
|
@@ -11,13 +11,13 @@ Complete reference for all 66 command groups. Organized by domain.
|
|
|
11
11
|
|------------|-----------|
|
|
12
12
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
13
13
|
| `get <id>` | `--json` |
|
|
14
|
-
| `search` | `--
|
|
15
|
-
| `create` | `--contact`, `--date`, `--due`, `--ref`, `--currency`, `--rate`, `--lines`, `--
|
|
16
|
-
| `update <id>` | `--
|
|
14
|
+
| `search` | `--reference`, `--contact-name`, `--status`, `--from`, `--to`, `--tag`, `--sort`, `--order` |
|
|
15
|
+
| `create` | `--contact`, `--date`, `--due`, `--ref`, `--currency`, `--exchange-rate`, `--lines`, `--finalize`, `--input` |
|
|
16
|
+
| `update <id>` | `--date`, `--due`, `--ref`, `--lines`, `--input` |
|
|
17
17
|
| `delete <id>` | |
|
|
18
|
-
| `pay <id>` | `--amount`, `--
|
|
18
|
+
| `pay <id>` | `--amount`, `--transaction-amount`, `--account`, `--method`, `--ref`, `--date` |
|
|
19
19
|
| `apply-credits <id>` | `--credit-note`, `--amount` |
|
|
20
|
-
| `download <id>` | `--
|
|
20
|
+
| `download <id>` | `--json` — returns the PDF URL; writes no file |
|
|
21
21
|
| `draft list` | `--max-rows N`, `--ids`, `--json` — ⚠️ fans out 1 attachment lookup per draft (5 in flight); pass `--max-rows 10` for spot checks |
|
|
22
22
|
| `draft finalize <id>` | `--account`, `--input` |
|
|
23
23
|
| `bulk-upsert` | `--input <file>`, `--json` — **FLAT** shape (one line per row via `itemDescription`+`totalAmount`+`invoiceAccountResourceId`). Async → jobId. `currencyCode` REQUIRED |
|
|
@@ -28,11 +28,11 @@ Complete reference for all 66 command groups. Organized by domain.
|
|
|
28
28
|
|------------|-----------|
|
|
29
29
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
30
30
|
| `get <id>` | `--json` |
|
|
31
|
-
| `search` | `--
|
|
32
|
-
| `create` | `--contact`, `--date`, `--due`, `--ref`, `--currency`, `--rate`, `--lines`, `--
|
|
33
|
-
| `update <id>` | `--
|
|
31
|
+
| `search` | `--reference`, `--contact-name`, `--status`, `--from`, `--to`, `--tag`, `--sort`, `--order` |
|
|
32
|
+
| `create` | `--contact`, `--date`, `--due`, `--ref`, `--currency`, `--exchange-rate`, `--lines`, `--finalize`, `--input` |
|
|
33
|
+
| `update <id>` | `--date`, `--due`, `--ref`, `--lines`, `--input` |
|
|
34
34
|
| `delete <id>` | |
|
|
35
|
-
| `pay <id>` | `--amount`, `--
|
|
35
|
+
| `pay <id>` | `--amount`, `--transaction-amount`, `--account`, `--method`, `--ref`, `--date` |
|
|
36
36
|
| `apply-credits <id>` | `--credit-note`, `--amount` |
|
|
37
37
|
| `draft list` | `--max-rows N`, `--ids`, `--json` — same attachment fan-out warning as invoices |
|
|
38
38
|
| `draft finalize <id>` | `--account`, `--input` |
|
|
@@ -44,13 +44,13 @@ Complete reference for all 66 command groups. Organized by domain.
|
|
|
44
44
|
|------------|-----------|
|
|
45
45
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
46
46
|
| `get <id>` | `--json` |
|
|
47
|
-
| `search` | `--
|
|
48
|
-
| `create` | `--contact`, `--date`, `--ref`, `--currency`, `--rate`, `--lines`, `--
|
|
49
|
-
| `update <id>` | `--
|
|
47
|
+
| `search` | `--reference`, `--contact-name`, `--status`, `--from`, `--to`, `--tag`, `--sort`, `--order` |
|
|
48
|
+
| `create` | `--contact`, `--date`, `--ref`, `--currency`, `--exchange-rate`, `--lines`, `--finalize`, `--input` |
|
|
49
|
+
| `update <id>` | `--date`, `--ref`, `--lines`, `--input` |
|
|
50
50
|
| `delete <id>` | |
|
|
51
51
|
| `refund <id>` | `--amount`, `--account`, `--method`, `--ref`, `--date` |
|
|
52
52
|
| `refunds <id>` | List refunds for a credit note |
|
|
53
|
-
| `download <id>` | `--
|
|
53
|
+
| `download <id>` | `--json` — returns the PDF URL; writes no file |
|
|
54
54
|
| `draft list` | `--max-rows N`, `--ids`, `--json` |
|
|
55
55
|
| `bulk-upsert` | `--input <file>`, `--json` — Nested `lineItems[]`. Async → jobId. `currencyCode` REQUIRED |
|
|
56
56
|
|
|
@@ -59,9 +59,9 @@ Complete reference for all 66 command groups. Organized by domain.
|
|
|
59
59
|
|------------|-----------|
|
|
60
60
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
61
61
|
| `get <id>` | `--json` |
|
|
62
|
-
| `search` | `--
|
|
63
|
-
| `create` | `--contact`, `--date`, `--ref`, `--currency`, `--rate`, `--lines`, `--
|
|
64
|
-
| `update <id>` | `--
|
|
62
|
+
| `search` | `--reference`, `--contact-name`, `--status`, `--from`, `--to`, `--tag`, `--sort`, `--order` |
|
|
63
|
+
| `create` | `--contact`, `--date`, `--ref`, `--currency`, `--exchange-rate`, `--lines`, `--finalize`, `--input` |
|
|
64
|
+
| `update <id>` | `--date`, `--ref`, `--lines`, `--input` |
|
|
65
65
|
| `delete <id>` | |
|
|
66
66
|
| `refund <id>` | `--amount`, `--account`, `--method`, `--ref`, `--date` |
|
|
67
67
|
| `refunds <id>` | List refunds for a credit note |
|
|
@@ -73,11 +73,11 @@ Complete reference for all 66 command groups. Organized by domain.
|
|
|
73
73
|
|------------|-----------|
|
|
74
74
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
75
75
|
| `get <id>` | `--json` |
|
|
76
|
-
| `search` | `--
|
|
77
|
-
| `create` | `--date`, `--ref`, `--entries`, `--
|
|
76
|
+
| `search` | `--reference`, `--from`, `--to`, `--status`, `--tag`, `--type`, `--sort`, `--order` |
|
|
77
|
+
| `create` | `--date`, `--ref`, `--entries`, `--finalize`, `--input` |
|
|
78
78
|
| `update <id>` | `--date`, `--ref`, `--entries`, `--input` |
|
|
79
79
|
| `delete <id>` | |
|
|
80
|
-
| `transfer-trial-balance` (alias: `ttb`) | `--
|
|
80
|
+
| `transfer-trial-balance` (alias: `ttb`) | `--date`, `--entries`, `--input`, `--currency`, `--exchange-rate`, `--rate-direction` |
|
|
81
81
|
| `draft list` | `--max-rows N`, `--ids`, `--json` |
|
|
82
82
|
| `bulk-upsert` | `--input <file>`, `--json` — ⚠️ Natural key is `journalReference` (NOT `reference`); legs use `journalEntries[]` (NOT `entries[]`); each leg is `organizationAccountResourceId` (NOT `accountResourceId`) + exactly one of `debitAmount`/`creditAmount` (NOT `amount`+`type`), omitting the unused side. No `currencyCode` on journal rows. Async → jobId |
|
|
83
83
|
|
|
@@ -100,7 +100,7 @@ Same subcommands and flags as `cash-in`.
|
|
|
100
100
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
101
101
|
| `get <id>` | `--json` |
|
|
102
102
|
| `search` | `--ref`, `--from`, `--to`, `--status` |
|
|
103
|
-
| `create` | `--from-account`, `--to-account`, `--amount`, `--date`, `--ref`, `--
|
|
103
|
+
| `create` | `--from-account`, `--to-account`, `--amount`, `--date`, `--ref`, `--input` |
|
|
104
104
|
| `delete <id>` | |
|
|
105
105
|
|
|
106
106
|
### `clio payments` — Cashflow transactions (read-only)
|
|
@@ -109,14 +109,13 @@ Same subcommands and flags as `cash-in`.
|
|
|
109
109
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
110
110
|
| `search` | `--from`, `--to`, `--type`, `--direction`, `--ref`, `--sort`, `--order` |
|
|
111
111
|
| `get <id>` | `--json` |
|
|
112
|
-
| `update <id>` | `--date`, `--
|
|
112
|
+
| `update <id>` | `--date`, `--reference`, `--input` |
|
|
113
113
|
| `delete <id>` | |
|
|
114
114
|
|
|
115
115
|
### `clio cashflow` — Cashflow search
|
|
116
116
|
| Subcommand | Key flags |
|
|
117
117
|
|------------|-----------|
|
|
118
118
|
| `search` | `--from`, `--to`, `--type`, `--direction`, `--ref`, `--sort`, `--order`, `--limit`, `--offset`, `--all` |
|
|
119
|
-
| `delete <id>` | |
|
|
120
119
|
|
|
121
120
|
---
|
|
122
121
|
|
|
@@ -139,8 +138,8 @@ Same subcommands and flags as `cash-in`.
|
|
|
139
138
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
140
139
|
| `get <id>` | `--json` |
|
|
141
140
|
| `search <query>` | `--limit`, `--offset` |
|
|
142
|
-
| `create` | `--name
|
|
143
|
-
| `update <id>` | `--name
|
|
141
|
+
| `create` | `--name` |
|
|
142
|
+
| `update <id>` | `--name` |
|
|
144
143
|
| `delete <id>` | |
|
|
145
144
|
|
|
146
145
|
### `clio accounts` — Chart of accounts
|
|
@@ -158,7 +157,7 @@ Same subcommands and flags as `cash-in`.
|
|
|
158
157
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
159
158
|
| `get <id>` | `--json` |
|
|
160
159
|
| `search <query>` | `--limit`, `--offset`, `--all` |
|
|
161
|
-
| `create` | `--
|
|
160
|
+
| `create` | `--sale-account`, `--purchase-account`, `--sale-tax`, `--purchase-tax`, `--name`, `--sale-name`, `--purchase-name`, `--sale-price`, `--purchase-price`, `--input` |
|
|
162
161
|
| `update <id>` | Same as create flags |
|
|
163
162
|
| `delete <id>` | |
|
|
164
163
|
|
|
@@ -192,7 +191,7 @@ Same subcommands and flags as `cash-in`.
|
|
|
192
191
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
193
192
|
| `get <id>` | `--json` |
|
|
194
193
|
| `search <query>` | `--limit`, `--offset` |
|
|
195
|
-
| `create` | `--
|
|
194
|
+
| `create` | `--rate`, `--name`, `--tax-type-code` |
|
|
196
195
|
| `update <id>` | `--name`, `--rate` |
|
|
197
196
|
| `types` | List available tax type codes |
|
|
198
197
|
| `wht-codes` | List withholding tax codes |
|
|
@@ -246,7 +245,7 @@ Same subcommands and flags as `cash-in`.
|
|
|
246
245
|
### `clio claims` — Employee-expense claims
|
|
247
246
|
| Subcommand | Key flags |
|
|
248
247
|
|------------|-----------|
|
|
249
|
-
| `search`
|
|
248
|
+
| `search` | `--status`, `--employee-resource-id`, `--contact-resource-id`, `--reference`, `--from`, `--to`, `--sort`, `--order` |
|
|
250
249
|
| `get <id>` | `--json` |
|
|
251
250
|
| `create` | `--value-date`*, `--currency`*, `--employee`, `--contact` / `--vendor-name` (XOR), `--items <json>`, `--custom-fields <json>`, `--tags`, `--submit` |
|
|
252
251
|
| `update <id>` | partial; `--items` non-empty REPLACES all lines, `--submit` |
|
|
@@ -260,13 +259,13 @@ Same subcommands and flags as `cash-in`.
|
|
|
260
259
|
| `preview-conversion` | `--ids`, `--posting-rule`, `--payout-flow` |
|
|
261
260
|
| `convert` | `--ids`, `--value-date`*, `--posting-rule`, `--include-payout`, `--idempotency-key` |
|
|
262
261
|
| `record-payout` | `--employee`, `--amount`, `--payment-account`, `--payout-for` (REIMBURSEMENT / ADVANCE) |
|
|
263
|
-
| `payouts`
|
|
262
|
+
| `payouts` | `--employee-resource-id`, `--employee-name`, `--reference`, `--payout-status`, `--payout-type` |
|
|
264
263
|
| `tracking-tags` / `custom-field-values` | picker arrays |
|
|
265
264
|
|
|
266
265
|
### `clio employees` — Claim members
|
|
267
266
|
| Subcommand | Key flags |
|
|
268
267
|
|------------|-----------|
|
|
269
|
-
| `search`
|
|
268
|
+
| `search` | `--name`, `--email`, `--active`, `--claim-profile-resource-id`, `--sort`, `--order` |
|
|
270
269
|
| `balances` (alias `search-balances`) | per-employee, per-currency reimbursement owed |
|
|
271
270
|
| `get <id>` | `--json` |
|
|
272
271
|
| `create` | `--name`, `--user`* (bind login), `--claim-profile`*, `--employment-type`, `--email`, `--manager` |
|
|
@@ -311,9 +310,9 @@ EmploymentType: `FULL_TIME` · `PART_TIME` · `CONTRACTOR` · `INTERN` · `TEMPO
|
|
|
311
310
|
| `accounts` | `--limit`, `--json` |
|
|
312
311
|
| `get <id>` | `--json` |
|
|
313
312
|
| `records <accountId>` | `--from`, `--to`, `--status`, `--description`, `--limit`, `--offset`, `--all` |
|
|
314
|
-
| `add-records <accountId>` | `--
|
|
315
|
-
| `import <accountId> <file>` | Supports CSV, OFX, XLS, XLSX |
|
|
316
|
-
| `auto-recon` | READ-ONLY reconciliation suggestions. `--type <workflow>` and `--entries <id,...>` are both REQUIRED (per-entry; no account-wide mode). `--account` optional. |
|
|
313
|
+
| `add-records <accountId>` | `--records`, (JSON array of bank records) |
|
|
314
|
+
| `import <accountId> <file>` | `--file`, `--account`, Supports CSV, OFX, XLS, XLSX |
|
|
315
|
+
| `auto-recon` | `--type`, `--entries`, READ-ONLY reconciliation suggestions. `--type <workflow>` and `--entries <id,...>` are both REQUIRED (per-entry; no account-wide mode). `--account` optional. |
|
|
317
316
|
|
|
318
317
|
### `clio bank-rules` — Bank reconciliation rules
|
|
319
318
|
| Subcommand | Key flags |
|
|
@@ -337,12 +336,12 @@ Dynamic strings in rules: `{{bankReference}}`, `{{bankPayee}}`, `{{bankDescripti
|
|
|
337
336
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
338
337
|
| `get <id>` | `--json` |
|
|
339
338
|
| `search <query>` | `--limit`, `--offset` |
|
|
340
|
-
| `create` | `--
|
|
339
|
+
| `create` | `--amount`, `--name`, `--type`, `--date`, `--input` |
|
|
341
340
|
| `update <id>` | `--name`, `--input` |
|
|
342
341
|
| `delete <id>` | |
|
|
343
|
-
| `discard <id>` | `--date`, `--account` |
|
|
344
|
-
| `sell <id>` | `--date`, `--
|
|
345
|
-
| `transfer <id>` | `--date`, `--
|
|
342
|
+
| `discard <id>` | `--disposal-date`, `--gain-loss-account` |
|
|
343
|
+
| `sell <id>` | `--id`, `--depreciation-end-date`, `--sale-type`, `--gain-loss-account` |
|
|
344
|
+
| `transfer <id>` | `--date`, `--type` |
|
|
346
345
|
| `undo-disposal <id>` | Reverse a discard or sale |
|
|
347
346
|
| `bulk-upsert` | `--input <file>`, `--json` — ⚠️ Date field is `valueDate` (NOT `purchaseDate` — that's the GET response field; bulk request uses `valueDate`). `cost`/`purchaseAmount` synonyms accepted. `effectiveLife`/`usefulLifeMonths` synonyms accepted. Required: `reference`, `registrationType` ("NEW" or "TRANSFER"). Async → jobId |
|
|
348
347
|
|
|
@@ -401,9 +400,9 @@ All seven of `--item-code`, `--name`, `--unit`, `--costing-method`, `--cogs-acco
|
|
|
401
400
|
| `list-invoices` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
402
401
|
| `list-bills` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
403
402
|
| `list-journals` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
404
|
-
| `create-invoice` | `--contact`, `--
|
|
405
|
-
| `create-bill` | `--contact`, `--
|
|
406
|
-
| `create-journal` | `--
|
|
403
|
+
| `create-invoice` | `--contact`, `--reference`, `--repeat`, `--start-date`, `--line-items`, `--input` |
|
|
404
|
+
| `create-bill` | `--contact`, `--reference`, `--repeat`, `--start-date`, `--line-items`, `--input` |
|
|
405
|
+
| `create-journal` | `--reference`, `--repeat`, `--start-date`, `--entries`, `--input` |
|
|
407
406
|
|
|
408
407
|
Dynamic strings in schedulers: `{{Day}}`, `{{Date}}`, `{{Date+X}}`, `{{DateRange:X}}`, `{{Month}}`, `{{Month+X}}`, `{{MonthRange:X}}`, `{{Year}}`, `{{Year+X}}`
|
|
409
408
|
|
|
@@ -442,7 +441,6 @@ Also: `clio reports pdf` — generate PDF from a message/document.
|
|
|
442
441
|
|------------|-----------|
|
|
443
442
|
| `create` | one of `--file <path>` / `--url <url>` / `--html <string\|@file>`; `--type` (invoice, bill, credit-note-customer, credit-note-supplier); `--merged` (split a multi-doc PDF). `--html` takes raw HTML (e.g. an email body), rendered to a PDF server-side. Encrypted PDFs: `name__pw__password.pdf`. |
|
|
444
443
|
| `status <workflowIds>` | Comma-separated workflow IDs |
|
|
445
|
-
| `search` | `--type`, `--status`, `--from`, `--to`, `--limit`, `--offset` |
|
|
446
444
|
|
|
447
445
|
### `clio quick-fix <entity>` — Bulk-update transactions
|
|
448
446
|
Entities: `invoices`, `bills`, `customer-credit-notes`, `supplier-credit-notes`, `journals`, `cash-entries`, `sale-schedules`, `purchase-schedules`, `subscription-schedules`, `journal-schedules`
|
|
@@ -486,16 +484,16 @@ All calculators work offline (no auth). Use `--json` for structured output.
|
|
|
486
484
|
| `loan` | `--principal`, `--rate`, `--term` |
|
|
487
485
|
| `lease` | `--payment`, `--term`, `--rate` (optional: `--useful-life` for hire purchase) |
|
|
488
486
|
| `depreciation` | `--cost`, `--salvage`, `--life`, `--method` |
|
|
489
|
-
| `prepaid-expense` | `--amount`, `--start-date
|
|
490
|
-
| `deferred-revenue` | `--amount`, `--start-date
|
|
487
|
+
| `prepaid-expense` | `--amount`, `--periods`, `--frequency`, `--start-date` |
|
|
488
|
+
| `deferred-revenue` | `--amount`, `--periods`, `--frequency`, `--start-date` |
|
|
491
489
|
| `fx-reval` | `--amount`, `--book-rate`, `--closing-rate`, `--rate-direction`, `--currency` |
|
|
492
|
-
| `ecl` | `--
|
|
493
|
-
| `provision` | `--amount`, `--rate`, `--
|
|
490
|
+
| `ecl` | `--current`, `--30d`, `--60d`, `--90d`, `--120d`, `--rates`, `--existing-provision` |
|
|
491
|
+
| `provision` | `--amount`, `--rate`, `--term`, `--start-date` |
|
|
494
492
|
| `fixed-deposit` | `--principal`, `--rate`, `--term` |
|
|
495
|
-
| `asset-disposal` | `--cost`, `--
|
|
496
|
-
| `accrued-expense` | `--amount`, `--start-date
|
|
497
|
-
| `leave-accrual` | `--
|
|
498
|
-
| `dividend` | `--
|
|
493
|
+
| `asset-disposal` | `--cost`, `--salvage`, `--life`, `--acquired`, `--disposed`, `--proceeds`, `--method` |
|
|
494
|
+
| `accrued-expense` | `--amount`, `--periods`, `--frequency`, `--start-date` |
|
|
495
|
+
| `leave-accrual` | `--employees`, `--days`, `--daily-rate`, `--periods`, `--start-date` |
|
|
496
|
+
| `dividend` | `--amount`, `--declaration-date`, `--payment-date`, `--withholding-rate` |
|
|
499
497
|
|
|
500
498
|
Common optional flags: `--start-date`, `--currency`, `--json`
|
|
501
499
|
|
|
@@ -508,21 +506,21 @@ Blueprints are offline (no auth). Tools require auth.
|
|
|
508
506
|
|
|
509
507
|
| Subcommand | Type | Key flags |
|
|
510
508
|
|------------|------|-----------|
|
|
511
|
-
| `month-end` | Blueprint | `--
|
|
512
|
-
| `quarter-end` | Blueprint | `--
|
|
513
|
-
| `year-end` | Blueprint | `--
|
|
514
|
-
| `bank-recon` | Blueprint | `--
|
|
509
|
+
| `month-end` | Blueprint | `--period`, `--currency` |
|
|
510
|
+
| `quarter-end` | `--period`, Blueprint | `--currency` |
|
|
511
|
+
| `year-end` | `--period`, Blueprint | `--currency` |
|
|
512
|
+
| `bank-recon` | Blueprint | `--account`, `--period`, `--currency` |
|
|
515
513
|
| `match` | Tool | `--input` (bank records + transactions JSON) |
|
|
516
|
-
| `gst-vat` | Blueprint | `--period
|
|
517
|
-
| `payment-run` | Blueprint | `--
|
|
518
|
-
| `outstanding` | Tool | `--
|
|
519
|
-
| `credit-control` |
|
|
520
|
-
| `supplier-recon` | Blueprint |
|
|
521
|
-
| `audit-prep` | Blueprint |
|
|
522
|
-
| `fa-review` | Blueprint |
|
|
523
|
-
| `document-collection` | Blueprint | `--
|
|
524
|
-
| `ingest` | Tool | `<path>` (classify + upload documents) |
|
|
525
|
-
| `statutory-filing` | Blueprint | `--jurisdiction`, `--
|
|
514
|
+
| `gst-vat` | Blueprint | `--period` |
|
|
515
|
+
| `payment-run` | Blueprint | `--due-before`, `--currency` |
|
|
516
|
+
| `outstanding` | Tool | `--limit` (group outstanding bills) |
|
|
517
|
+
| `credit-control` | `--overdue-days`, Blueprint | |
|
|
518
|
+
| `supplier-recon` | `--supplier`, `--period`, Blueprint | |
|
|
519
|
+
| `audit-prep` | `--period`, Blueprint | |
|
|
520
|
+
| `fa-review` | `--currency`, Blueprint | |
|
|
521
|
+
| `document-collection` | Blueprint | `--currency` |
|
|
522
|
+
| `ingest` | `--source`, Tool | `<path>` (classify + upload documents) |
|
|
523
|
+
| `statutory-filing` | Blueprint | `--ya`, `--jurisdiction`, `--currency` |
|
|
526
524
|
| `sg-cs` | Tool | `--input` (compute Singapore Form C-S) |
|
|
527
525
|
| `sg-ca` | Tool | `--input` (compute Singapore capital allowances) |
|
|
528
526
|
|
|
@@ -553,8 +551,8 @@ Batch create via `--input` file or stdin (`{ "entries": [...] }`, 1-100 per call
|
|
|
553
551
|
|------------|-----------|
|
|
554
552
|
| `list` | `--limit`, `--offset`, `--all`, `--format`, `--json` |
|
|
555
553
|
| `search <query>` | `--limit`, `--offset` |
|
|
556
|
-
| `invite` | `--email`, `--first-name`, `--last-name`, `--
|
|
557
|
-
| `update <id>` | `--
|
|
554
|
+
| `invite` | `--email`, `--first-name`, `--last-name`, `--role`, `--input` |
|
|
555
|
+
| `update <id>` | `--role`, `--input` |
|
|
558
556
|
| `remove <id>` | |
|
|
559
557
|
|
|
560
558
|
### `clio auth` — Authentication
|
|
@@ -569,8 +567,9 @@ See SKILL.md Auth Precedence section for full details.
|
|
|
569
567
|
|------------|-----------|
|
|
570
568
|
| `list` | `--type` (invoices, bills, journals, etc.), `--id` |
|
|
571
569
|
| `add` | `--type`, `--id`, `<file>` |
|
|
572
|
-
| `delete
|
|
573
|
-
|
|
570
|
+
| `delete <attachmentId>` | `--type`, `--id` (the transaction; the attachment id is positional) |
|
|
571
|
+
|
|
572
|
+
`list` renders the tabular view — pass `--format table` (the default) or `--format csv`.
|
|
574
573
|
|
|
575
574
|
### `clio help-center` (alias: `hc`) — Help center search
|
|
576
575
|
```
|
|
@@ -249,7 +249,7 @@ clio magic create --html @./email-body.html --type invoice --json
|
|
|
249
249
|
clio magic status "wf-id-1,wf-id-2,wf-id-3" --json
|
|
250
250
|
|
|
251
251
|
# Search past magic workflows
|
|
252
|
-
clio magic
|
|
252
|
+
clio magic status <workflowIds> --json # comma-separated ids from `magic create`
|
|
253
253
|
|
|
254
254
|
# For encrypted PDFs — embed the password in the filename via __pw__
|
|
255
255
|
clio magic create --file ./encrypted-file__pw__secret123.pdf --type invoice --json
|
package/cli.mjs
CHANGED
|
@@ -678,7 +678,7 @@ Unsupported type: `+t.type,"ENOTSUP");t._finish()})};Jc.prototype._stat=function
|
|
|
678
678
|
`,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function Dvr(){let t=Ait(import.meta.url),e=mit(t),r=[fm(e,"..","..","..","help-center-mirror"),fm(e,"..","..","..","assets","skills","api","help-center-mirror"),fm(e,"help-center-mirror")];for(let n of r)try{return _de(fm(n,"index.md"),"utf-8"),n}catch{}return null}var fit,pit,yvr,Evr,bvr,Cvr,Ivr,vvr,wvr,cz,hit,wde,hB=X(()=>{"use strict";vde();Jb();fit=1.2,pit=.75,yvr=1.5,Evr=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","shall","should","may","might","must","can","could","am","i","me","my","we","our","you","your","he","she","it","they","them","this","that","these","those","what","which","who","whom","how","when","where","why","if","then","than","so","no","not","or","and","but","in","on","at","to","for","of","with","by","from","as","into","about","between","through","after","before","during","above","below","up","down","out","off","over","under","again","further","just","also","very","too","only","own","same","both","each","all","any","few","more","most","other","some","such","here","there"]),bvr=new Map([["recon",["reconciliation","reconcile","reconciled"]],["txn",["transaction","transactions"]],["txns",["transactions","transaction"]],["acct",["account","accounts"]],["accts",["accounts","account"]],["inv",["invoice","invoices"]],["cn",["credit","note"]],["ar",["receivable","receivables"]],["ap",["payable","payables"]],["pmt",["payment","payments"]],["stmt",["statement","statements"]],["bal",["balance","balances"]],["fa",["fixed","assets","asset"]],["gst",["tax","goods","services"]],["vat",["tax","value","added"]],["fx",["foreign","exchange","currency"]],["config",["configuration","configure","settings"]],["depr",["depreciation"]],["amort",["amortization"]],["coa",["chart","accounts"]],["po",["purchase","order"]],["so",["sales","order"]],["org",["organization"]],["subs",["subscription","subscriptions"]],["amt",["amount","amounts"]],["qty",["quantity"]],["desc",["description"]],["ref",["reference"]],["num",["number"]]]);Cvr=.7,Ivr=3,vvr=32,wvr=5;cz=null,hit=null;wde=null});import{existsSync as Svr,readFileSync as Rvr}from"node:fs";import{dirname as xvr,join as Sde}from"node:path";import{fileURLToPath as Tvr}from"node:url";function mB(t){let e=t??Fvr();if(!e)return null;if(lz&&Cit===e)return lz;try{let r=Rvr(e,"utf-8");return lz=JSON.parse(r),Cit=e,lz}catch{return null}}function Fvr(){let t=Tvr(import.meta.url),e=xvr(t),r=[Sde(e,"..","..","..","help-center-mirror","help-center-embeddings.json"),Sde(e,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),Sde(e,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(Svr(n))return n;return null}function wit(t,e){let r=Math.min(t.length,e.length),n=0;for(let i=0;i<r;i++)n+=t[i]*e[i];return n}function _it(){return uz!==null?uz:(uz=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",uz||null)}async function Rde(t){let e=_it();if(!e)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),kvr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:Bvr,input:t}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!Iit&&(Iit=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
|
|
679
679
|
`)),null)}catch{return null}}async function AB(t,e,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??Nvr,c=n.minBm25??Ovr;if(i==="bm25"||!e)return Ty(t,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Rde(r);return m?vit(t,e,m,{limit:o,section:s}).filter(g=>g.score>=a):Ty(t,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Rde(r),Promise.resolve(Ty(t,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=vit(t,e,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Dit(p,h,o)}function vit(t,e,r,n){let i=new Map(t.sections.map(c=>[c.slug,c])),o=new Map(t.articles.map(c=>[c.id,c])),s=[];for(let c of e.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=wit(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function Dit(t,e,r){let n=new Map;for(let o=0;o<t.length;o++){let s=t[o],a=1/(bit+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<e.length;o++){let s=e[o],a=1/(bit+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function xde(t){return t!==null&&!!_it()}var Bvr,kvr,bit,Nvr,Ovr,lz,Cit,uz,Iit,dz=X(()=>{"use strict";hB();Bvr="text-embedding-3-small",kvr=2e3,bit=60,Nvr=.3,Ovr=1.5,lz=null,Cit=null,uz=null,Iit=!1});async function Sit(t,e={}){let r=String(t??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof e.limit=="number"&&!Number.isNaN(e.limit)?e.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof e.section=="string"?e.section:void 0,s=e.mode??"hybrid";try{let a=fB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:mB(),u=await AB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(Dde(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Rit(){let t=process.env.CLIO_HELP_CENTER_URL?.trim();return t&&t.length>0?t:Qvr}async function fz(t,e={}){let r=String(t??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Rit())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof e.limit=="number"&&Number.isFinite(e.limit)&&i.searchParams.set("limit",String(e.limit)),typeof e.section=="string"&&e.section&&i.searchParams.set("section",e.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(Lvr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return Mvr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function Mvr(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.results)?!0:typeof e.error=="string"}async function Tde(t,e={}){return process.env.CLIO_DAEMON==="1"||pB()?Sit(t,e):fz(t,e)}var Qvr,Lvr,xit=X(()=>{"use strict";hB();dz();Qvr="https://mcp.jaz.ai/help-center/search",Lvr=4e3});var Bde=X(()=>{"use strict";hB();dz();xit();hB()});var Tit,Bit=X(()=>{"use strict";Tit={loan:["cash-in"],lease:["journal"],"prepaid-expense":["bill","cash-out"],"deferred-revenue":["invoice","cash-in"],provision:["journal"],"fixed-deposit":["cash-out"],"accrued-expense":["journal"],dividend:["journal"]}});async function pz(t,e){let{blueprint:r,accountMap:n,finalize:i}=e,o=!i;Pvr(e);let s=await Uvr(t,r.capsuleType),a=r.steps[0]?.date??new Date().toISOString().slice(0,10),c=`${r.capsuleName} (${a})`,d={resourceId:(await hA(t,{capsuleTypeResourceId:s,title:c,description:r.capsuleDescription})).data.resourceId,type:r.capsuleType,title:c},f=Oit(e),p=[],h=[];for(let A of r.steps){if(A.step===f){p.push({step:A.step,action:A.action,status:"existing",resourceId:e.existingTxnId,description:A.description});continue}if(A.action==="fixed-asset"||A.action==="note"){p.push({step:A.step,action:A.action,status:"skipped",description:A.description}),h.push(`Step ${A.step} (${A.action}): ${A.description}`);continue}let g=await $vr(t,A,e,o);p.push(g),g.error&&h.push(`Step ${A.step} failed: ${g.error}`)}let m={total:p.length,created:p.filter(A=>A.status==="created").length,existing:p.filter(A=>A.status==="existing").length,skipped:p.filter(A=>A.status==="skipped").length,errors:p.filter(A=>A.status==="error").length,notes:h};return{recipe:e.calcType,capsule:d,steps:p,summary:m}}function Pvr(t){let{blueprint:e,accountMap:r,bankAccountId:n,contactId:i}=t;if(!e.steps.length)throw new Error("Blueprint has no steps to execute.");let o=[];for(let d of e.steps)for(let f of d.lines)Nde(f.account,r)||o.push(f.account);let s=[...new Set(o)];if(s.length>0)throw new Error(`Unmapped account(s) in --input: ${s.join(", ")}.
|
|
680
680
|
Add these to your account mapping JSON.`);let a=Oit(t);if(e.steps.some(d=>(d.action==="cash-in"||d.action==="cash-out")&&d.step!==a)&&!n)throw new Error("--bank-account is required for recipes with cash-in/cash-out steps.");if(e.steps.some(d=>(d.action==="bill"||d.action==="invoice")&&d.step!==a)&&!i)throw new Error("--contact is required for recipes with bill/invoice steps.")}async function Uvr(t,e){let n=(await kE(t)).data.find(o=>o.displayName.toLowerCase()===e.toLowerCase());return n?n.resourceId:(await Ow(t,{displayName:e})).data.resourceId}function Oit(t){if(!t.existingTxnId)return null;let e=Tit[t.calcType];return e?t.blueprint.steps.find(n=>e.includes(n.action))?.step??null:null}async function $vr(t,e,r,n){let{accountMap:i,referencePrefix:o}=r,s=o?`${o}-${e.step}`:void 0;try{let a;switch(e.action){case"journal":{a=(await og(t,{reference:s,valueDate:e.date,journalEntries:kde(e.lines,i),internalNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await fA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:kit(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await ng(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:kit(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=Nit(e.lines,r.bankAccountId,i);a=(await Fv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:kde(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=Nit(e.lines,r.bankAccountId,i);a=(await Qv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:kde(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}default:return{step:e.step,action:e.action,status:"skipped",description:e.description}}return{step:e.step,action:e.action,status:"created",resourceId:a,description:e.description}}catch(a){return{step:e.step,action:e.action,status:"error",description:e.description,error:a.message}}}function kde(t,e){return t.map(r=>({accountResourceId:Ode(r.account,e),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function kit(t,e){return t.filter(r=>Nde(r.account,e)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:Ode(r.account,e)}))}function Nit(t,e,r){let n=[],i=null;for(let o of t)Ode(o.account,r)===e&&!i?i=o:n.push(o);return i?{bankLine:i,contraLines:n}:{bankLine:t[0],contraLines:t.slice(1)}}function Nde(t,e){if(e[t])return t;let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return n;return null}function Ode(t,e){let r=Nde(t,e);if(!r)throw new Error(`Unmapped account: "${t}"`);return e[r]}var Fde=X(()=>{"use strict";sg();_d();ig();zH();Qw();Bit()});async function Fit(t,e){let n=(await Op((s,a)=>Dd(t,{offset:s,limit:a}))).data;if(n.length===0)return{mapping:{},failures:e.map(s=>({name:s,candidates:[]}))};let i={},o=[];for(let s of e){let a=lP(s,n);if(a)i[s]=a.resourceId;else{let c=fC(s,n,{threshold:.3,limit:3});o.push({name:s,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:o}}async function Qit(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let d=(await Zf(t,e)).data;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}let n=e.trim(),o=(await pc(t,{filter:{billingName:{contains:n}},limit:50})).data;if(o.length===0&&(o=(await Wf(t,{offset:0,limit:500})).data),o.length===0)throw new Error("No contacts found. Create one in Jaz first.");let s=n.toLowerCase(),a=o.find(u=>u.billingName?.toLowerCase()===s||u.name?.toLowerCase()===s);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=uP(n,o,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],d=c.length>1?c[1].score:0;if(c.length===1||u.score-d>=.1){let f=u.item;return{resourceId:f.resourceId,displayName:f.billingName||f.name||"Unknown"}}}if(c.length>1){let u=c.map(d=>`${d.item.billingName||d.item.name} (${(d.score*100).toFixed(0)}%)`).join(", ");throw new Error(`Multiple contacts match "${n}": ${u}. Be more specific.`)}throw new Error(`No contact matching "${n}".`)}async function Lit(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let i=await Hb(t,e);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await YA(t,e);return{resourceId:n.resourceId,displayName:n.name}}var Mit=X(()=>{"use strict";TE();Xf();vp();VM();lX();uX();ZL()});async function pm(t,e){await t.delete(`/api/v1/cash-entries/${e}`)}async function hm(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}var gB=X(()=>{"use strict";mn()});async function hz(t,e){return t.post("/api/v1/transfer-trial-balance",{...e,currency:Ur(e.currency),taxCurrency:Ur(e.taxCurrency)})}var Qde=X(()=>{"use strict";An()});async function mz(t,e){return t.list("/api/v1/organization/bookmarks",e)}async function Az(t,e){return t.get(`/api/v1/organization/bookmarks/${e}`)}async function yB(t,e){return t.post("/api/v1/organization/bookmarks",{items:e})}async function gz(t,e,r){return t.put(`/api/v1/organization/bookmarks/${e}`,r)}var Lde=X(()=>{"use strict"});function qvr(t){let{refs:e,...r}=t;return e?{...r,refs:e.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Mv(t,e){return t.post("/api/v1/jots",{entries:e.map(qvr)})}async function yz(t,e){return t.post("/api/v1/jots/search",e)}async function Pit(t,e,r){return t.post(`/api/v1/jots/${e}/disposition`,r)}var Ez=X(()=>{"use strict"});async function Uit(t,e){return t.post("/api/v1/agents/memories",e)}async function Mde(t,e){return t.post("/api/v1/agents/memories/forget",e)}var $it=X(()=>{"use strict"});function bz(){return process.env.ENABLE_MEMORY==="true"}function Pde(){return process.env.ENABLE_MEMORY_CHAT==="true"}function qit(t){return!bz()||!t||!t.progressive?"memory_disabled":t.isInboxOwner?null:"not_owner"}var Ude=X(()=>{"use strict"});var qde={};bs(qde,{default:()=>Yvr,log:()=>$de});var Cz,jvr,jit,$de,Yvr,jde=X(()=>{"use strict";Cz=()=>{},jvr=()=>$de,jit=(...t)=>{try{process.stderr.write(t.map(String).join(" ")+`
|
|
681
|
-
`)}catch{}},$de={info:Cz,warn:Cz,error:jit,debug:Cz,trace:Cz,fatal:jit,child:jvr,level:"error"},Yvr=$de});import{createHash as Hvr}from"node:crypto";function r0r(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>300?[null,"directive_too_long"]:zit.some(r=>e.includes(r))?[null,"directive_invalid"]:Hit.test(e)?[null,"directive_invalid"]:Zvr.test(e)?[null,"directive_contains_url"]:Xvr.test(e)?[null,"directive_contains_email"]:[e,null]}function n0r(t){if(t==null)return[null,null];let e=t.normalize("NFKC").trim();return e?e.length>Kvr?[null,"match_condition_too_long"]:zit.some(r=>e.includes(r))?[null,"match_condition_invalid"]:Hit.test(e)?[null,"match_condition_invalid"]:[e,null]:[null,"match_condition_invalid"]}function i0r(t){return t==null?[null,null]:Number.isInteger(t)?t<e0r||t>t0r?[null,"invalid_importance"]:[t,null]:[null,"invalid_importance"]}function o0r(t,e,r,n,i,o,s,a){if(t)return Hvr("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function s0r(t){Promise.resolve().then(()=>(jde(),qde)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function Wit(t,e,r){let n=e.action,i=e.category,o=Vvr[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(s0r({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=t.memoryTurn,f=qit(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>zvr||!Wvr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[C,E]=r0r(e.directive);if(E)return u(E);p=C;let[I,v]=i0r(e.importance);if(v)return u(v);h=I}let[m,A]=n0r(e.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=Gvr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let C={gtid:g};d.quote&&(C.quote=d.quote.slice(0,Jvr));let E=o0r(g,n,o,i,s,p,e.confirms_key,e.replaces_key),I={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...e.replaces_key?{replacesKey:e.replaces_key}:{},...e.confirms_key?{confirmsKey:e.confirms_key}:{},pending:e.pending===!0,source:r?.source??"TOOL",provenance:C,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await Yde(()=>Uit(t.client,I)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let C={category:i,key:s,scope:o};y=await Yde(()=>Mde(t.client,C))}else{let C={forgetAll:!0};y=await Yde(()=>Mde(t.client,C))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function Yde(t){try{let e=await t(),r=e&&typeof e=="object"&&e.data&&typeof e.data=="object"?e.data:e??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(e){return e instanceof lo?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var Hit,zit,zvr,Gvr,Jvr,Git,Jit,Vit,Vvr,Wvr,Zvr,Xvr,Kvr,e0r,t0r,Zit=X(()=>{"use strict";$it();Sa();Ude();Ude();Hit=/[\x00-\x1f\x7f]/,zit=["{{","}}","```","<",">"],zvr=120,Gvr=3,Jvr=140,Git=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Jit=["set","forget","forget_all"],Vit=["this_org","all_orgs"],Vvr={this_org:"ORG_USER",all_orgs:"USER"},Wvr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Zvr=/https?:\/\//i,Xvr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Kvr=255,e0r=0,t0r=100});async function Iz(t,e){return t.list("/api/v1/organization-users",e)}async function vz(t,e){return t.search("/api/v1/organization-users/search",e)}async function Pv(t,e){return t.post("/api/v1/organization-users/invite",e)}async function wz(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function _z(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var Hde=X(()=>{"use strict"});async function Dz(t,e){return t.search("/api/v1/cashflow-transactions/search",{limit:e?.limit??100,offset:e?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function EB(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function Sz(t,e){return t.get(`/api/v1/payments/${e}`)}async function Rz(t,e,r){return t.put(`/api/v1/payments/${e}`,{...r,currency:Ur(r.currency)})}async function xz(t,e){await t.delete(`/api/v1/payments/${e}`)}function Tz(t,e){return(r,n)=>r.post(`/api/v1/${t}/${e}`,{...n,transactions:n.transactions.map(i=>({...i,currency:Ur(i.currency)}))})}var win,_in,Din,Sin,zde=X(()=>{"use strict";An();win=Tz("sales","bulk-payments"),_in=Tz("sales","batch-payments"),Din=Tz("purchases","bulk-payments"),Sin=Tz("purchases","batch-payments")});async function Bz(t,e,r={}){let n=a0r.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var a0r,Gde=X(()=>{"use strict";a0r=new Set(["statement-of-account-export"])});import{createHash as c0r}from"node:crypto";import{writeFile as l0r,mkdir as u0r}from"node:fs/promises";import{dirname as d0r,isAbsolute as f0r,join as p0r}from"node:path";async function Xit(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function Jde(t,e,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),t.post("/api/v1/reports/sql-query/export",{query:e},{headers:n})}async function Vde(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function h0r(t){return c0r("sha256").update(t).digest("hex").slice(0,16)}async function Kit(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=h0r(e),o=await Jde(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await Vde(t,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!f0r(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??p0r(f,"Downloads",`pseudo-sql-${s}.csv`);return await u0r(d0r(p),{recursive:!0}),await l0r(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}async function eot(t){let e=await t.get("/api/v1/reports/sql-query/schema"),r=e.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return e}var tot=X(()=>{"use strict"});async function kz(t){return t.get("/api/v1/capsule-recipes")}async function Nz(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function Oz(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function Fz(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function Qz(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function ha(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((o,s)=>{if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var Wde=X(()=>{"use strict"});async function li(t,e,r){let n=await t.get(`/api/v1/${e}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function Mz(t,e){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=e,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),t.postMultipart(`/api/v1/${r}/${n}/attachments`,o)}async function Pz(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var Lz,mm=X(()=>{"use strict";Lz=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function ui(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Uz=X(()=>{"use strict"});async function $z(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function qz(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new Error('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var bB,Zde=X(()=>{"use strict";bB=["POST","POST_AND_RECORD"]});async function jz(t,e){if(!(e.amount>0))throw new Error("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function Yz(t,e){return t.search("/api/v1/employees/payouts/search",e)}var rot,Xde=X(()=>{"use strict";rot=["REIMBURSEMENT","ADVANCE"]});function not(t){return{source:t.source,sourceType:t.sourceType,...t.cloudProvider?{cloudProvider:t.cloudProvider}:{},summary:t.summary,files:t.folders.flatMap(e=>e.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}var iot=X(()=>{"use strict"});import{randomUUID as m0r}from"node:crypto";import{rmSync as A0r}from"node:fs";function efe(t){for(let e of t.tempDirs??[])try{A0r(e,{recursive:!0,force:!0})}catch{}}function sot(t){for(let[e,r]of By)t-r.createdAt>oot&&(efe(r.plan),By.delete(e))}function y0r(){Kde||(Kde=setInterval(()=>sot(Date.now()),g0r),Kde.unref?.())}function aot(t,e){let r=Date.now();sot(r),y0r();let n=`dc_${m0r()}`;return By.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function cot(t,e){let r=By.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>oot?(efe(r.plan),By.delete(t),null):r.plan}function lot(t,e){let r=By.get(t);!r||r.ownerKey!==e||(efe(r.plan),By.delete(t))}var oot,g0r,By,Kde,uot=X(()=>{"use strict";oot=1800*1e3,g0r=300*1e3,By=new Map});function E0r(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function b0r(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>$1(i.documentType)&&r.has(i.documentType))}))}}async function dot(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?b0r(e,i):e;if(!n&&C0r(o))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");let s=await XL({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?E0r(u.response):void 0,error:u.error})),c=a.map(u=>u.workflowId).filter(u=>!!u);return{total:s.total,uploaded:s.success,skipped:a.filter(u=>u.status==="skipped").length,failed:s.failed,workflowIds:c,files:a}}function C0r(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var fot=X(()=>{"use strict";c7();np()});async function ed(t,e,r){if(!e)return t;let n=I0r(t);if(!n)return t;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return t&&typeof t=="object"?{...t,_hydration:s}:{result:t,_hydration:s}}}function I0r(t){if(!t||typeof t!="object")return;let e=t,r=e.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=e.resourceId;if(typeof n=="string"&&n.length>0)return n}function Sf(t,e){return!e||!t||typeof t!="object"?t:{_fx:e,...t}}var pot=X(()=>{"use strict"});async function Hz(t,e){return t.list("/api/v1/bank-rules",e)}async function CB(t,e){let r=await t.get(`/api/v1/bank-rules/${e}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${e}`)}async function zz(t,e){return t.search("/api/v1/bank-rules/search",e)}async function Gz(t,e){return t.post("/api/v1/bank-rules",e)}async function Jz(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function Vz(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var tfe=X(()=>{"use strict"});async function Wz(t,e){return t.list("/api/v1/fixed-assets",e)}async function IB(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function Zz(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function Xz(t,e){return t.post("/api/v1/fixed-assets",e)}async function Kz(t,e,r){let i=(await IB(t,e)).data,o={};for(let s of v0r){let a=i[s];if(a==null)continue;let c=w0r.has(s)?hc(a):a;c!==void 0&&(o[s]=c)}for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=e,t.put(`/api/v1/fixed-assets/${e}`,o)}async function e8(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function t8(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function vB(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function r8(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function n8(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function i8(t,e){return po(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var v0r,w0r,o8=X(()=>{"use strict";mn();pA();v0r=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","fixedAssetsSetting","capsuleResourceId"],w0r=new Set(["purchaseDate","depreciationStartDate"])});async function s8(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function wB(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function a8(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function c8(t,e,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.endDate){let i=!n.startDate,o=!n.repeat;if(i||o){let s=await wB(t,e);if(i){let a=hc(s.data.startDate);if(!a)throw new Error("Subscription has no readable startDate \u2014 cannot auto-fill for update");n.startDate=a}if(o){if(!s.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=s.data.interval}}}return t.put(`/api/v1/scheduled/subscriptions/${e}`,n)}async function l8(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function u8(t,e,r){return t.put(`/api/v1/scheduled/cancel-subscriptions/${e}`,{resourceId:e,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function d8(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var rfe=X(()=>{"use strict";pA()});async function f8(t,e){return t.list("/api/v1/contact-groups",e)}async function p8(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function h8(t,e){return t.search("/api/v1/contact-groups/search",e)}async function m8(t,e){return t.post("/api/v1/contact-groups",e)}async function A8(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,_E(r,c9))}async function g8(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var nfe=X(()=>{"use strict";mn()});async function y8(t,e){return t.list("/api/v1/inventory-items",e)}async function E8(t,e){return t.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...e})}async function b8(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var ife=X(()=>{"use strict"});async function C8(t,e){return t.list("/api/v1/custom-fields",e)}async function _B(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function I8(t,e){return t.search("/api/v1/custom-fields/search",e)}async function v8(t,e){return t.post("/api/v1/custom-fields",e)}function D0r(t){return t!==void 0&&_0r.every(e=>t[e]!==void 0)}function S0r(t){let e=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:e(t.applyToSales),bills:e(t.applyToPurchase),customerCredits:e(t.applyToSaleCreditNote??t.applyToCreditNote),supplierCredits:e(t.applyToPurchaseCreditNote??t.applyToCreditNote),payments:e(t.applyToPayment)}}function R0r(t){return[t.applyToSales,t.applyToPurchase,t.applyToSaleCreditNote,t.applyToPurchaseCreditNote,t.applyToPayment,t.applyToCreditNote].some(e=>e==="PRINT")}async function w8(t,e,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!D0r(n.appliesTo)){let i=await _B(t,e);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??R0r(i.data),n.appliesTo={...S0r(i.data),...r.appliesTo}}return t.put(`/api/v1/custom-fields/${e}`,n)}async function _8(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var _0r,ofe=X(()=>{"use strict";_0r=["invoices","bills","customerCredits","supplierCredits","payments"]});function hot(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function DB(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return hot(n)}async function SB(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return hot(n)}var x0r,T0r,B0r,Uv,sfe=X(()=>{"use strict";x0r=["invoices","bills","customer-credit-notes","supplier-credit-notes"],T0r=["journals","cash-entries"],B0r=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],Uv=[...x0r,...T0r,...B0r]});async function D8(t,e){return t.list("/api/v1/nano-classifiers",e)}async function S8(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function R8(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function RB(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function xB(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,{...r,resourceId:e})}async function x8(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var afe=X(()=>{"use strict"});async function T8(t,e){return t.post("/api/v1/export-records",e)}async function B8(t,e){return t.post("/api/v1/export-records/preview",e)}async function k8(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var cfe=X(()=>{"use strict"});async function TB(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var lfe=X(()=>{"use strict"});function N8(t,e){if(!e.has(t))throw new Error(`unknown entity "${t}" \u2014 expected one of ${[...e].join(", ")}`)}function Aot(t,e,r,n=!1){if(!Array.isArray(t))throw new Error(`${r}: resourceIds must be an array, not a ${typeof t}`);if(t.length===0)throw new Error(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(t).size!==t.length)throw new Error(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(t.length>e)throw new Error(`${r}: ${t.length} ids exceeds the ${e}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${e} or fewer.`)}async function got(t,e,r){return N8(e,ufe),ts(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/approve`)}async function yot(t,e,r){return N8(e,ufe),Aot(r,k0r,"bulk approve",!0),r.forEach(n=>ts(n,"resourceIds[]","Every id must be a document resourceId.")),t.post(`/api/v1/${encodeURIComponent(e)}/bulk-approve`,{resourceIds:r})}async function Eot(t,e,r,n){N8(e,mot),ts(r,"resourceId","Pass the document resourceId."),Cot(n);let i=await t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:F0r(i)}}}async function bot(t,e,r,n){return N8(e,mot),Cot(n),Aot(r,N0r,"bulk request changes"),r.forEach(i=>ts(i,"resourceIds[]","Every id must be a document resourceId.")),t.post(O0r(e),{resourceIds:r,message:n})}function O0r(t){return t==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${encodeURIComponent(t)}/bulk-request-changes`}function Cot(t){if(!t||t.trim().length===0)throw new Error("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function F0r(t){let e=t?.data??t;if(!e||typeof e!="object")return[];let r=e.records;if(Array.isArray(r))return r;let n=e.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var ufe,mot,k0r,N0r,Iot=X(()=>{"use strict";An();ufe=new Set(["invoices","bills","customer-credit-notes","supplier-credit-notes"]),mot=new Set([...ufe,"purchase-orders","purchase-requests","sale-orders","sale-quotes","claims"]);k0r=100,N0r=500});function Q0r(t,e,r){let n=Math.random().toString(36).slice(2,10);return`restore:${t}:${vot(e)}:${vot(r)}:${n}`}function vot(t){return t.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function dfe(t){if(!wot.has(t))throw new Error(`unknown entity "${t}" \u2014 expected one of ${[...wot].join(", ")}`)}async function _ot(t,e,r){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}`)}async function Dot(t,e,r,n){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function Sot(t,e,r,n,i){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/rollback/${encodeURIComponent(e)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??Q0r(e,r,n)}})}async function Rot(t,e,r){return t.get(`/api/v1/organization/currencies/${encodeURIComponent(e)}/effective-rate`,r?{date:r}:void 0)}var wot,xot=X(()=>{"use strict";An();wot=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function $v(t){Nt(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!L0r.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function O8(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:P0r(r.data)}}function M0r(t){return{btResourceId:t.btResourceId,btType:t.btType,eligible:t.eligible,errors:t.errors,displayData:t.displayData,contactSignals:t.contactInsight??null,breakdown:t.breakdown??null}}function P0r(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(M0r),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function F8(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function Q8(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var L0r,ffe=X(()=>{"use strict";mn();L0r=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function Bot(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function pfe(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);dl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&dl([i],["valueDate"])}function q0r(t,e){let r=typeof e=="number"&&!Number.isNaN(e)?e:void 0,n=typeof t=="number"&&!Number.isNaN(t)?t:void 0;if(r!==void 0)return r>=U0r?"high":r>=Tot?"medium":"low";if(n!==void 0){if(n>=$0r)return"high";if(n>=Tot)return"medium"}return"low"}function kot(t,e={}){let r=t??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let d=u.slice().sort((D,B)=>{let L=D.confidenceScore??D.matchScore??-1;return(B.confidenceScore??B.matchScore??-1)-L}),f=d[0],p=typeof f.recommendationType=="string"?f.recommendationType:void 0,h=typeof f.matchScore=="number"?f.matchScore:void 0,m=typeof f.confidenceScore=="number"?f.confidenceScore:void 0,A=typeof f.isCrossCurrency=="boolean"?f.isCrossCurrency:void 0,g=typeof f.cftBtResourceId=="string"?f.cftBtResourceId:void 0,y=Array.isArray(f.cftBtResourceIds)?f.cftBtResourceIds:[],C=f.isBatch===!0||y.length>1,E=typeof f.cftAmount=="number"?f.cftAmount:void 0,I,v;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(I=BB.magicMatch,v={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(I=BB.withPayments,v={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof f.learnedPredictionResourceId=="string"?f.learnedPredictionResourceId:void 0,B=typeof f.predictedPayload=="string"?f.predictedPayload:void 0,L=typeof f.predictedPayloadSchemaVersion=="string"?f.predictedPayloadSchemaVersion:void 0;D&&B&&L&&(I=BB.learnedPrediction,v={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:B,predictedPayloadSchemaVersion:L});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=f.actionShortcut??{},B=typeof D.resourceId=="string"?D.resourceId:void 0;B&&(I=BB.applyBankRule,v={actionShortcutResourceId:B,businessTransactionResourceIds:[c]});break}default:break}let x=I?q0r(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,z=I!==BB.withPayments||S,q=x==="high"&&!!I&&!!v&&z&&N;o.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:I,execute:v,confidenceTier:x,autoCommitEligible:q,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function Y0r(t,e,r){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,bankLine:e,match:r}}async function H0r(t,e,r){let n=e.matchedTransactionResourceId,i=e.matchedTransactionCount;if(!n)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:i}:null;let o=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let s of o)try{let{data:a}=s==="bill"?await xs(t,n):await Qs(t,n);return{type:s,reference:a.reference,amount:e.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:e.matchAmount,count:i,resourceId:n}}async function Not(t,e,r){let n=r.filter(o=>o.recommendedTool&&!o.autoCommitEligible).slice(0,j0r);if(n.length===0)return[];let i=new Map;if(e)try{let o=await zb(t,e,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let s of o.data??[])i.set(s.resourceId,s)}catch{}return Promise.all(n.map(async o=>{let s=i.get(o.bankStatementEntryResourceId),a=s?{valueDate:s.valueDate,netAmount:s.netAmount,currencyCode:s.currencyCode,currencySymbol:s.currencySymbol,description:s.description,counterparty:s.extContactName}:null;return Y0r(o,a,await H0r(t,o,a?.netAmount))}))}async function L8(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function M8(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function P8(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function U8(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function $8(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function q8(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function j8(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function Y8(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function H8(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function z8(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function G8(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}async function J8(t,e){return t.post("/api/v1/reconciliations/reset",e)}var BB,U0r,$0r,Tot,j0r,hfe=X(()=>{"use strict";vp();_d();mn();ig();BB={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},U0r=.9,$0r=.95,Tot=.7;j0r=25});function Ys(t,e,r="lineItems"){let n=[];for(let i of e)if(i.perLineItem){let o=t[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(t)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function Co(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:mfe(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=mfe(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=mfe(t,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=t[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(v=>v.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,I=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||I||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function mfe(t,e,r,n,i){let o=i.find(s=>s.field===e);if(!o){let s=t[e];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(t)){let s=t[e];return e==="contactResourceId"?{status:"ok",value:t.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function $o(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Ys(t,e,n),a=Co(t,e,n);return{resourceId:t.resourceId,reference:t.reference||null,totalAmount:t.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var ma,Vc,oo,Jl,Oot=X(()=>{"use strict";ma=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:t=>!!t.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:t=>t.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:t=>!!t.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:t=>t.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0}],Vc=[...ma],oo=ma.filter(t=>t.field!=="dueDate"),Jl=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:t=>t.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:t=>t.amount!=null&&t.amount>0||t.debitAmount!=null&&t.debitAmount>0||t.creditAmount!=null&&t.creditAmount>0,perLineItem:!0}]});function Wc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function qv(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Pt(t){if(t)return t.split("T")[0]}var Afe=X(()=>{"use strict"});function td(t,e){let r={};if(e.contact&&(r.contactResourceId=e.contact),e.date&&(r.valueDate=e.date),e.due&&(r.dueDate=e.due),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.tag!==void 0&&(r.tag=e.tag),e.tax&&(r.isTaxVatApplicable=!0),e.tax&&e.taxInclusive?r.taxInclusion=!0:e.tax&&(r.taxInclusion=!1),e.lines)r.lineItems=e.lines;else if(e.account||e.taxProfile){let n=t.lineItems??[];r.lineItems=n.map(i=>{let o=Wc(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),e.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=e.taxProfile),o})}return r}function V8(t,e){let r={};if(e.date&&(r.valueDate=e.date),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.entries)r.journalEntries=e.entries;else if(e.account){let n=t.journalEntries??[];r.journalEntries=n.map(i=>{let o=qv(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var Fot=X(()=>{"use strict";Afe()});var gfe=X(()=>{"use strict";Oot();Afe();Fot()});var kB,Vl,Qot=X(()=>{"use strict";kB="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Vl="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function Efe(t){return z0r.get(t)}function Lot(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!yfe.has(o));return n.length===0?[]:Ti.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,e).map(o=>o.ns)}var Ti,yfe,z0r,rd=X(()=>{"use strict";Ti=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Twelve endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created \u2014 it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",title:"Tracking Categories",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",title:"IFRS Recipes & Capsules",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve documents awaiting approval, or send them back for changes. Covers invoices, bills, both credit notes, sale/purchase orders, quotes, requests and claims. Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:"Quick Fix: bulk-update multiple transactions or line items in one call. Change dates, contacts, tags, accounts, tax profiles, custom fields across many invoices/bills/journals/credit-notes/cash-entries/schedulers at once. Also: batch update, mass edit.",groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions \u2014 both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK \u2014 one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user \u2014 including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see \u2014 for invoices, bills, reports, settings, or a specific transaction.",groups:["navigation"]}],yfe=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),z0r=new Map(Ti.flatMap(t=>t.groups.map(e=>[e,t.name])))});function jv(t){let e=new Set,r=[];for(let n of t)for(let i of Wl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function NB(){return Ti.map(t=>{let e=jv(t.groups),r=e.filter(i=>i.isDestructive??!1).length,n=e.filter(i=>i.readOnly).length;return{namespace:t.name,operations:e.length,read:n,write:e.length-n-r,destructive:r,summary:(t.description.split(".")[0]??"").trim()}})}function G0r(t,e,r){let n=t==="namespace"?`Each entry in your tool list is a namespace router: ${e} entries, ${r} operations. Every tool's description lists its own operations.`:t==="meta"?`Your tool list holds discovery tools, not the catalogue: ${e} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${e} entries for ${r} operations.`;return{shape:t,this_connector_lists:e,operations:r,note:n}}function ky(t,e=!1){let r=Yv(void 0).length,n=Ti.length,i=t==="namespace"?n+(e?1:0):t==="flat"?r+(e?1:0):t==="meta"?3+(e?1:0):void 0;return{operations:r,namespaces:n,...t&&i!==void 0?{packaging:G0r(t,i,r)}:{},map:NB(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var W8=X(()=>{"use strict";rd();nd()});function Z8(t){let e={type:t.type};if(t.description&&(e.description=t.description),t.enum&&(e.enum=t.enum),t.type==="array"&&t.items&&(e.items=Z8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=Z8(i);e.properties=r,t.required?.length&&(e.required=[...t.required])}return e}function Rf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=Z8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function Ny(t){return{name:t.name,description:t.description,input_schema:Rf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var Hv=X(()=>{"use strict"});function OB(t){if(typeof t!="string")return t.isDestructive??!1;let e=t;return e.startsWith("delete_")||e.startsWith("pay_")||e.startsWith("finalize_")||e.includes("refund")||e==="remove_org_user"}function X8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&OB(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function V0r(t){return t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function W0r(t){let e=V0r(t);return!e||J0r.has(e)?!0:e.split(" ").filter(n=>n.length>=2&&!yfe.has(n)).length===0}function K8(t){if(W0r(t)){let{next:i,...o}=ky();return{...o,hint:"Call search_tools with a namespace name or keyword to see operation names in that area, then describe_tools for full schemas before executing."}}let e=Lot(t,5);if(e.length===0){let{operations:i,namespaces:o}=ky();return{matches:[],hint:`No operation matches "${t}". Jaz has ${i} operations across ${o} namespaces \u2014 call search_tools with an empty query for the full map before concluding this is unsupported. Namespaces are named after accounting objects (contacts, employees, journals, claims), not task wording.`}}let n=t.toLowerCase().split(/\s+/).filter(Boolean);return{matches:e.map(i=>{let o=i.groups.flatMap(u=>Wl(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
|
|
681
|
+
`)}catch{}},$de={info:Cz,warn:Cz,error:jit,debug:Cz,trace:Cz,fatal:jit,child:jvr,level:"error"},Yvr=$de});import{createHash as Hvr}from"node:crypto";function r0r(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>300?[null,"directive_too_long"]:zit.some(r=>e.includes(r))?[null,"directive_invalid"]:Hit.test(e)?[null,"directive_invalid"]:Zvr.test(e)?[null,"directive_contains_url"]:Xvr.test(e)?[null,"directive_contains_email"]:[e,null]}function n0r(t){if(t==null)return[null,null];let e=t.normalize("NFKC").trim();return e?e.length>Kvr?[null,"match_condition_too_long"]:zit.some(r=>e.includes(r))?[null,"match_condition_invalid"]:Hit.test(e)?[null,"match_condition_invalid"]:[e,null]:[null,"match_condition_invalid"]}function i0r(t){return t==null?[null,null]:Number.isInteger(t)?t<e0r||t>t0r?[null,"invalid_importance"]:[t,null]:[null,"invalid_importance"]}function o0r(t,e,r,n,i,o,s,a){if(t)return Hvr("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function s0r(t){Promise.resolve().then(()=>(jde(),qde)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function Wit(t,e,r){let n=e.action,i=e.category,o=Vvr[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(s0r({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=t.memoryTurn,f=qit(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>zvr||!Wvr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[C,E]=r0r(e.directive);if(E)return u(E);p=C;let[I,v]=i0r(e.importance);if(v)return u(v);h=I}let[m,A]=n0r(e.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=Gvr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let C={gtid:g};d.quote&&(C.quote=d.quote.slice(0,Jvr));let E=o0r(g,n,o,i,s,p,e.confirms_key,e.replaces_key),I={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...e.replaces_key?{replacesKey:e.replaces_key}:{},...e.confirms_key?{confirmsKey:e.confirms_key}:{},pending:e.pending===!0,source:r?.source??"TOOL",provenance:C,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await Yde(()=>Uit(t.client,I)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let C={category:i,key:s,scope:o};y=await Yde(()=>Mde(t.client,C))}else{let C={forgetAll:!0};y=await Yde(()=>Mde(t.client,C))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function Yde(t){try{let e=await t(),r=e&&typeof e=="object"&&e.data&&typeof e.data=="object"?e.data:e??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(e){return e instanceof lo?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var Hit,zit,zvr,Gvr,Jvr,Git,Jit,Vit,Vvr,Wvr,Zvr,Xvr,Kvr,e0r,t0r,Zit=X(()=>{"use strict";$it();Sa();Ude();Ude();Hit=/[\x00-\x1f\x7f]/,zit=["{{","}}","```","<",">"],zvr=120,Gvr=3,Jvr=140,Git=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Jit=["set","forget","forget_all"],Vit=["this_org","all_orgs"],Vvr={this_org:"ORG_USER",all_orgs:"USER"},Wvr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Zvr=/https?:\/\//i,Xvr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Kvr=255,e0r=0,t0r=100});async function Iz(t,e){return t.list("/api/v1/organization-users",e)}async function vz(t,e){return t.search("/api/v1/organization-users/search",e)}async function Pv(t,e){return t.post("/api/v1/organization-users/invite",e)}async function wz(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function _z(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var Hde=X(()=>{"use strict"});async function Dz(t,e){return t.search("/api/v1/cashflow-transactions/search",{limit:e?.limit??100,offset:e?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function EB(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function Sz(t,e){return t.get(`/api/v1/payments/${e}`)}async function Rz(t,e,r){return t.put(`/api/v1/payments/${e}`,{...r,currency:Ur(r.currency)})}async function xz(t,e){await t.delete(`/api/v1/payments/${e}`)}function Tz(t,e){return(r,n)=>r.post(`/api/v1/${t}/${e}`,{...n,transactions:n.transactions.map(i=>({...i,currency:Ur(i.currency)}))})}var win,_in,Din,Sin,zde=X(()=>{"use strict";An();win=Tz("sales","bulk-payments"),_in=Tz("sales","batch-payments"),Din=Tz("purchases","bulk-payments"),Sin=Tz("purchases","batch-payments")});async function Bz(t,e,r={}){let n=a0r.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var a0r,Gde=X(()=>{"use strict";a0r=new Set(["statement-of-account-export"])});import{createHash as c0r}from"node:crypto";import{writeFile as l0r,mkdir as u0r}from"node:fs/promises";import{dirname as d0r,isAbsolute as f0r,join as p0r}from"node:path";async function Xit(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function Jde(t,e,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),t.post("/api/v1/reports/sql-query/export",{query:e},{headers:n})}async function Vde(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function h0r(t){return c0r("sha256").update(t).digest("hex").slice(0,16)}async function Kit(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=h0r(e),o=await Jde(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await Vde(t,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!f0r(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??p0r(f,"Downloads",`pseudo-sql-${s}.csv`);return await u0r(d0r(p),{recursive:!0}),await l0r(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}async function eot(t){let e=await t.get("/api/v1/reports/sql-query/schema"),r=e.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return e}var tot=X(()=>{"use strict"});async function kz(t){return t.get("/api/v1/capsule-recipes")}async function Nz(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function Oz(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function Fz(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function Qz(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function ha(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((o,s)=>{if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var Wde=X(()=>{"use strict"});async function li(t,e,r){let n=await t.get(`/api/v1/${e}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function Mz(t,e){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=e,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),t.postMultipart(`/api/v1/${r}/${n}/attachments`,o)}async function Pz(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var Lz,mm=X(()=>{"use strict";Lz=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function ui(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Uz=X(()=>{"use strict"});async function $z(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function qz(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new Error('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var bB,Zde=X(()=>{"use strict";bB=["POST","POST_AND_RECORD"]});async function jz(t,e){if(!(e.amount>0))throw new Error("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function Yz(t,e){return t.search("/api/v1/employees/payouts/search",e)}var rot,Xde=X(()=>{"use strict";rot=["REIMBURSEMENT","ADVANCE"]});function not(t){return{source:t.source,sourceType:t.sourceType,...t.cloudProvider?{cloudProvider:t.cloudProvider}:{},summary:t.summary,files:t.folders.flatMap(e=>e.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}var iot=X(()=>{"use strict"});import{randomUUID as m0r}from"node:crypto";import{rmSync as A0r}from"node:fs";function efe(t){for(let e of t.tempDirs??[])try{A0r(e,{recursive:!0,force:!0})}catch{}}function sot(t){for(let[e,r]of By)t-r.createdAt>oot&&(efe(r.plan),By.delete(e))}function y0r(){Kde||(Kde=setInterval(()=>sot(Date.now()),g0r),Kde.unref?.())}function aot(t,e){let r=Date.now();sot(r),y0r();let n=`dc_${m0r()}`;return By.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function cot(t,e){let r=By.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>oot?(efe(r.plan),By.delete(t),null):r.plan}function lot(t,e){let r=By.get(t);!r||r.ownerKey!==e||(efe(r.plan),By.delete(t))}var oot,g0r,By,Kde,uot=X(()=>{"use strict";oot=1800*1e3,g0r=300*1e3,By=new Map});function E0r(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function b0r(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>$1(i.documentType)&&r.has(i.documentType))}))}}async function dot(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?b0r(e,i):e;if(!n&&C0r(o))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");let s=await XL({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?E0r(u.response):void 0,error:u.error})),c=a.map(u=>u.workflowId).filter(u=>!!u);return{total:s.total,uploaded:s.success,skipped:a.filter(u=>u.status==="skipped").length,failed:s.failed,workflowIds:c,files:a}}function C0r(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var fot=X(()=>{"use strict";c7();np()});async function ed(t,e,r){if(!e)return t;let n=I0r(t);if(!n)return t;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return t&&typeof t=="object"?{...t,_hydration:s}:{result:t,_hydration:s}}}function I0r(t){if(!t||typeof t!="object")return;let e=t,r=e.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=e.resourceId;if(typeof n=="string"&&n.length>0)return n}function Sf(t,e){return!e||!t||typeof t!="object"?t:{_fx:e,...t}}var pot=X(()=>{"use strict"});async function Hz(t,e){return t.list("/api/v1/bank-rules",e)}async function CB(t,e){let r=await t.get(`/api/v1/bank-rules/${e}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${e}`)}async function zz(t,e){return t.search("/api/v1/bank-rules/search",e)}async function Gz(t,e){return t.post("/api/v1/bank-rules",e)}async function Jz(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function Vz(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var tfe=X(()=>{"use strict"});async function Wz(t,e){return t.list("/api/v1/fixed-assets",e)}async function IB(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function Zz(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function Xz(t,e){return t.post("/api/v1/fixed-assets",e)}async function Kz(t,e,r){let i=(await IB(t,e)).data,o={};for(let s of v0r){let a=i[s];if(a==null)continue;let c=w0r.has(s)?hc(a):a;c!==void 0&&(o[s]=c)}for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=e,t.put(`/api/v1/fixed-assets/${e}`,o)}async function e8(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function t8(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function vB(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function r8(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function n8(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function i8(t,e){return po(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var v0r,w0r,o8=X(()=>{"use strict";mn();pA();v0r=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","fixedAssetsSetting","capsuleResourceId"],w0r=new Set(["purchaseDate","depreciationStartDate"])});async function s8(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function wB(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function a8(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function c8(t,e,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.endDate){let i=!n.startDate,o=!n.repeat;if(i||o){let s=await wB(t,e);if(i){let a=hc(s.data.startDate);if(!a)throw new Error("Subscription has no readable startDate \u2014 cannot auto-fill for update");n.startDate=a}if(o){if(!s.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=s.data.interval}}}return t.put(`/api/v1/scheduled/subscriptions/${e}`,n)}async function l8(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function u8(t,e,r){return t.put(`/api/v1/scheduled/cancel-subscriptions/${e}`,{resourceId:e,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function d8(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var rfe=X(()=>{"use strict";pA()});async function f8(t,e){return t.list("/api/v1/contact-groups",e)}async function p8(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function h8(t,e){return t.search("/api/v1/contact-groups/search",e)}async function m8(t,e){return t.post("/api/v1/contact-groups",e)}async function A8(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,_E(r,c9))}async function g8(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var nfe=X(()=>{"use strict";mn()});async function y8(t,e){return t.list("/api/v1/inventory-items",e)}async function E8(t,e){return t.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...e})}async function b8(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var ife=X(()=>{"use strict"});async function C8(t,e){return t.list("/api/v1/custom-fields",e)}async function _B(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function I8(t,e){return t.search("/api/v1/custom-fields/search",e)}async function v8(t,e){return t.post("/api/v1/custom-fields",e)}function D0r(t){return t!==void 0&&_0r.every(e=>t[e]!==void 0)}function S0r(t){let e=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:e(t.applyToSales),bills:e(t.applyToPurchase),customerCredits:e(t.applyToSaleCreditNote??t.applyToCreditNote),supplierCredits:e(t.applyToPurchaseCreditNote??t.applyToCreditNote),payments:e(t.applyToPayment)}}function R0r(t){return[t.applyToSales,t.applyToPurchase,t.applyToSaleCreditNote,t.applyToPurchaseCreditNote,t.applyToPayment,t.applyToCreditNote].some(e=>e==="PRINT")}async function w8(t,e,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!D0r(n.appliesTo)){let i=await _B(t,e);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??R0r(i.data),n.appliesTo={...S0r(i.data),...r.appliesTo}}return t.put(`/api/v1/custom-fields/${e}`,n)}async function _8(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var _0r,ofe=X(()=>{"use strict";_0r=["invoices","bills","customerCredits","supplierCredits","payments"]});function hot(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function DB(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return hot(n)}async function SB(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return hot(n)}var x0r,T0r,B0r,Uv,sfe=X(()=>{"use strict";x0r=["invoices","bills","customer-credit-notes","supplier-credit-notes"],T0r=["journals","cash-entries"],B0r=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],Uv=[...x0r,...T0r,...B0r]});async function D8(t,e){return t.list("/api/v1/nano-classifiers",e)}async function S8(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function R8(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function RB(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function xB(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,{...r,resourceId:e})}async function x8(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var afe=X(()=>{"use strict"});async function T8(t,e){return t.post("/api/v1/export-records",e)}async function B8(t,e){return t.post("/api/v1/export-records/preview",e)}async function k8(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var cfe=X(()=>{"use strict"});async function TB(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var lfe=X(()=>{"use strict"});function N8(t,e){if(!e.has(t))throw new Error(`unknown entity "${t}" \u2014 expected one of ${[...e].join(", ")}`)}function Aot(t,e,r,n=!1){if(!Array.isArray(t))throw new Error(`${r}: resourceIds must be an array, not a ${typeof t}`);if(t.length===0)throw new Error(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(t).size!==t.length)throw new Error(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(t.length>e)throw new Error(`${r}: ${t.length} ids exceeds the ${e}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${e} or fewer.`)}async function got(t,e,r){return N8(e,ufe),ts(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/approve`)}async function yot(t,e,r){return N8(e,ufe),Aot(r,k0r,"bulk approve",!0),r.forEach(n=>ts(n,"resourceIds[]","Every id must be a document resourceId.")),t.post(`/api/v1/${encodeURIComponent(e)}/bulk-approve`,{resourceIds:r})}async function Eot(t,e,r,n){N8(e,mot),ts(r,"resourceId","Pass the document resourceId."),Cot(n);let i=await t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:F0r(i)}}}async function bot(t,e,r,n){return N8(e,mot),Cot(n),Aot(r,N0r,"bulk request changes"),r.forEach(i=>ts(i,"resourceIds[]","Every id must be a document resourceId.")),t.post(O0r(e),{resourceIds:r,message:n})}function O0r(t){return t==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${encodeURIComponent(t)}/bulk-request-changes`}function Cot(t){if(!t||t.trim().length===0)throw new Error("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function F0r(t){let e=t?.data??t;if(!e||typeof e!="object")return[];let r=e.records;if(Array.isArray(r))return r;let n=e.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var ufe,mot,k0r,N0r,Iot=X(()=>{"use strict";An();ufe=new Set(["invoices","bills","customer-credit-notes","supplier-credit-notes"]),mot=new Set([...ufe,"purchase-orders","purchase-requests","sale-orders","sale-quotes","claims"]);k0r=100,N0r=500});function Q0r(t,e,r){let n=Math.random().toString(36).slice(2,10);return`restore:${t}:${vot(e)}:${vot(r)}:${n}`}function vot(t){return t.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function dfe(t){if(!wot.has(t))throw new Error(`unknown entity "${t}" \u2014 expected one of ${[...wot].join(", ")}`)}async function _ot(t,e,r){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}`)}async function Dot(t,e,r,n){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function Sot(t,e,r,n,i){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/rollback/${encodeURIComponent(e)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??Q0r(e,r,n)}})}async function Rot(t,e,r){return t.get(`/api/v1/organization/currencies/${encodeURIComponent(e)}/effective-rate`,r?{date:r}:void 0)}var wot,xot=X(()=>{"use strict";An();wot=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function $v(t){Nt(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!L0r.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function O8(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:P0r(r.data)}}function M0r(t){return{btResourceId:t.btResourceId,btType:t.btType,eligible:t.eligible,errors:t.errors,displayData:t.displayData,contactSignals:t.contactInsight??null,breakdown:t.breakdown??null}}function P0r(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(M0r),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function F8(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function Q8(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var L0r,ffe=X(()=>{"use strict";mn();L0r=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function Bot(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function pfe(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);dl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&dl([i],["valueDate"])}function q0r(t,e){let r=typeof e=="number"&&!Number.isNaN(e)?e:void 0,n=typeof t=="number"&&!Number.isNaN(t)?t:void 0;if(r!==void 0)return r>=U0r?"high":r>=Tot?"medium":"low";if(n!==void 0){if(n>=$0r)return"high";if(n>=Tot)return"medium"}return"low"}function kot(t,e={}){let r=t??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let d=u.slice().sort((D,B)=>{let L=D.confidenceScore??D.matchScore??-1;return(B.confidenceScore??B.matchScore??-1)-L}),f=d[0],p=typeof f.recommendationType=="string"?f.recommendationType:void 0,h=typeof f.matchScore=="number"?f.matchScore:void 0,m=typeof f.confidenceScore=="number"?f.confidenceScore:void 0,A=typeof f.isCrossCurrency=="boolean"?f.isCrossCurrency:void 0,g=typeof f.cftBtResourceId=="string"?f.cftBtResourceId:void 0,y=Array.isArray(f.cftBtResourceIds)?f.cftBtResourceIds:[],C=f.isBatch===!0||y.length>1,E=typeof f.cftAmount=="number"?f.cftAmount:void 0,I,v;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(I=BB.magicMatch,v={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(I=BB.withPayments,v={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof f.learnedPredictionResourceId=="string"?f.learnedPredictionResourceId:void 0,B=typeof f.predictedPayload=="string"?f.predictedPayload:void 0,L=typeof f.predictedPayloadSchemaVersion=="string"?f.predictedPayloadSchemaVersion:void 0;D&&B&&L&&(I=BB.learnedPrediction,v={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:B,predictedPayloadSchemaVersion:L});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=f.actionShortcut??{},B=typeof D.resourceId=="string"?D.resourceId:void 0;B&&(I=BB.applyBankRule,v={actionShortcutResourceId:B,businessTransactionResourceIds:[c]});break}default:break}let x=I?q0r(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,z=I!==BB.withPayments||S,q=x==="high"&&!!I&&!!v&&z&&N;o.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:I,execute:v,confidenceTier:x,autoCommitEligible:q,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function Y0r(t,e,r){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,bankLine:e,match:r}}async function H0r(t,e,r){let n=e.matchedTransactionResourceId,i=e.matchedTransactionCount;if(!n)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:i}:null;let o=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let s of o)try{let{data:a}=s==="bill"?await xs(t,n):await Qs(t,n);return{type:s,reference:a.reference,amount:e.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:e.matchAmount,count:i,resourceId:n}}async function Not(t,e,r){let n=r.filter(o=>o.recommendedTool&&!o.autoCommitEligible).slice(0,j0r);if(n.length===0)return[];let i=new Map;if(e)try{let o=await zb(t,e,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let s of o.data??[])i.set(s.resourceId,s)}catch{}return Promise.all(n.map(async o=>{let s=i.get(o.bankStatementEntryResourceId),a=s?{valueDate:s.valueDate,netAmount:s.netAmount,currencyCode:s.currencyCode,currencySymbol:s.currencySymbol,description:s.description,counterparty:s.extContactName}:null;return Y0r(o,a,await H0r(t,o,a?.netAmount))}))}async function L8(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function M8(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function P8(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function U8(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function $8(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function q8(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function j8(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function Y8(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function H8(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function z8(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function G8(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}async function J8(t,e){return t.post("/api/v1/reconciliations/reset",e)}var BB,U0r,$0r,Tot,j0r,hfe=X(()=>{"use strict";vp();_d();mn();ig();BB={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},U0r=.9,$0r=.95,Tot=.7;j0r=25});function Ys(t,e,r="lineItems"){let n=[];for(let i of e)if(i.perLineItem){let o=t[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(t)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function Co(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:mfe(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=mfe(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=mfe(t,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=t[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(v=>v.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,I=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||I||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function mfe(t,e,r,n,i){let o=i.find(s=>s.field===e);if(!o){let s=t[e];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(t)){let s=t[e];return e==="contactResourceId"?{status:"ok",value:t.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function $o(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Ys(t,e,n),a=Co(t,e,n);return{resourceId:t.resourceId,reference:t.reference||null,totalAmount:t.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var ma,Vc,oo,Jl,Oot=X(()=>{"use strict";ma=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:t=>!!t.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:t=>t.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:t=>!!t.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:t=>t.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0}],Vc=[...ma],oo=ma.filter(t=>t.field!=="dueDate"),Jl=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:t=>t.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:t=>t.amount!=null&&t.amount>0||t.debitAmount!=null&&t.debitAmount>0||t.creditAmount!=null&&t.creditAmount>0,perLineItem:!0}]});function Wc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function qv(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Pt(t){if(t)return t.split("T")[0]}var Afe=X(()=>{"use strict"});function td(t,e){let r={};if(e.contact&&(r.contactResourceId=e.contact),e.date&&(r.valueDate=e.date),e.due&&(r.dueDate=e.due),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.tag!==void 0&&(r.tag=e.tag),e.tax&&(r.isTaxVatApplicable=!0),e.tax&&e.taxInclusive?r.taxInclusion=!0:e.tax&&(r.taxInclusion=!1),e.lines)r.lineItems=e.lines;else if(e.account||e.taxProfile){let n=t.lineItems??[];r.lineItems=n.map(i=>{let o=Wc(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),e.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=e.taxProfile),o})}return r}function V8(t,e){let r={};if(e.date&&(r.valueDate=e.date),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.entries)r.journalEntries=e.entries;else if(e.account){let n=t.journalEntries??[];r.journalEntries=n.map(i=>{let o=qv(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var Fot=X(()=>{"use strict";Afe()});var gfe=X(()=>{"use strict";Oot();Afe();Fot()});var kB,Vl,Qot=X(()=>{"use strict";kB="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Vl="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function Efe(t){return z0r.get(t)}function Lot(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!yfe.has(o));return n.length===0?[]:Ti.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,e).map(o=>o.ns)}var Ti,yfe,z0r,rd=X(()=>{"use strict";Ti=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Twelve endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created \u2014 it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",title:"Tracking Categories",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",title:"IFRS Recipes & Capsules",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve documents awaiting approval, or send them back for changes. Covers invoices, bills, both credit notes, sale/purchase orders, quotes, requests and claims. Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:"Quick Fix: bulk-update multiple transactions or line items in one call. Change dates, contacts, tags, accounts, tax profiles, custom fields across many invoices/bills/journals/credit-notes/cash-entries/schedulers at once. Also: batch update, mass edit.",groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions \u2014 both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK \u2014 one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user \u2014 including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see \u2014 for invoices, bills, reports, settings, or a specific transaction.",groups:["navigation"]}],yfe=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),z0r=new Map(Ti.flatMap(t=>t.groups.map(e=>[e,t.name])))});function jv(t){let e=new Set,r=[];for(let n of t)for(let i of Wl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function NB(){return Ti.map(t=>{let e=jv(t.groups),r=e.filter(i=>i.isDestructive??!1).length,n=e.filter(i=>i.readOnly).length;return{namespace:t.name,operations:e.length,read:n,write:e.length-n-r,destructive:r,summary:(t.description.split(".")[0]??"").trim()}})}function G0r(t,e,r){let n=t==="namespace"?`Each entry in your tool list is a namespace router: ${e} entries, ${r} operations. Every tool's description lists its own operations.`:t==="meta"?`Your tool list holds discovery tools, not the catalogue: ${e} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${e} entries for ${r} operations.`;return{shape:t,this_connector_lists:e,operations:r,note:n}}function ky(t,e=!1){let r=Yv(void 0).length,n=Ti.length,i=t==="namespace"?n+(e?1:0):t==="flat"?r+(e?1:0):t==="meta"?3+(e?1:0):void 0;return{operations:r,namespaces:n,...t&&i!==void 0?{packaging:G0r(t,i,r)}:{},map:NB(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var W8=X(()=>{"use strict";rd();nd()});function Z8(t){let e={type:t.type};if(t.description&&(e.description=t.description),t.enum&&(e.enum=t.enum),t.type==="array"&&t.items&&(e.items=Z8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=Z8(i);e.properties=r,t.required?.length&&(e.required=[...t.required])}return e}function Rf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=Z8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function Ny(t){return{name:t.name,description:t.description,input_schema:Rf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var Hv=X(()=>{"use strict"});function OB(t){if(typeof t!="string")return t.isDestructive??!1;let e=t;return e.startsWith("delete_")||e.startsWith("pay_")||e.startsWith("finalize_")||e.includes("refund")||e==="remove_org_user"}function X8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&OB(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function V0r(t){return t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function W0r(t){let e=V0r(t);return!e||J0r.has(e)?!0:e.split(" ").filter(n=>n.length>=2&&!yfe.has(n)).length===0}function K8(t){if(W0r(t)){let{next:i,...o}=ky();return{...o,hint:"Call search_tools with a namespace name or keyword to see operation names in that area, then describe_tools for full schemas before executing."}}let e=Lot(t,5);if(e.length===0){let{operations:i,namespaces:o}=ky();return{matches:[],hint:`No operation matches "${t}". Jaz has ${i} operations across ${o} namespaces \u2014 call search_tools with an empty query for the full map before concluding this is unsupported. Namespaces are named after accounting objects (contacts, employees, journals, claims), not task wording.`}}let n=t.toLowerCase().split(/\s+/).filter(Boolean);return{matches:e.map(i=>{let o=i.groups.flatMap(u=>Wl(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
|
|
682
682
|
`)[0],...u.tool.searchHint?{searchHint:u.tool.searchHint}:{}}))}}),hint:"Call describe_tools with the tool names you need, then execute_tool to run them."}}function Mot(t){if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))return{error:"Invalid `tools` parameter. Expected string[]."};if(t.length===0)return{error:"Provide at least one tool name. Use search_tools first to discover tool names."};let e=[],r=[];for(let n of t){let i=e3(n);if(!i){r.push(n);continue}e.push({...Ny(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&OB(i),group:i.group})}return{tools:e,...r.length>0?{notFound:r,hint:`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var J0r,Z0r,X0r,K0r,xf,Am,zv=X(()=>{"use strict";rd();W8();nd();Hv();J0r=new Set(["capabilities","capability","overview","everything","catalog","catalogue","menu","features","feature list","functions","tool list","all tools","all operations","list tools","list all tools","list operations","full list","full catalog","full catalogue","whats available","what is available","whats possible","show everything","show me everything","what else can you do","how many tools","how many operations"]);Z0r={name:"search_tools",description:"Search for available Jaz accounting tools by keyword. Returns matching tool namespaces with tool names and descriptions. Call with empty query to list all namespaces. ALWAYS call this first to discover what tools are available.",inputSchema:Rf({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};X0r={name:"describe_tools",description:"Get full JSON Schema (parameters, types, required fields) for specific tools. Call this after search_tools to get the exact input format before calling execute_tool.",inputSchema:Rf({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},K0r={name:"execute_tool",description:"Execute a Jaz accounting tool. Call describe_tools first to get the required parameters. Pass the tool name and its arguments.",inputSchema:Rf({tool:{type:"string",description:'Tool name (e.g. "create_invoice")'},arguments:{type:"object",description:"Tool arguments (see describe_tools for schema)"},org_id:{type:"string",description:"Organization ID (UUID). Required in multi-org mode (PAT or multiple API keys). Call list_organizations to get available IDs."}},["tool"])},xf={name:"list_organizations",description:"List organizations available to the current authentication. Returns org names and resource IDs for use as org_id in execute_tool calls.",inputSchema:Rf({},[])},Am=[Z0r,X0r,K0r]});function nwr(t){if(!(Zl in t))return{cleanedInput:t};let{[Zl]:e,...r}=t;return{jotText:typeof e=="string"&&e.trim()!==""?e.trim():void 0,cleanedInput:r}}function $ot(t,e){if(t.params[Zl])return{cleanedInput:e};let{jotText:r,cleanedInput:n}=nwr(e);return t.readOnly?{cleanedInput:n}:{jotText:r,cleanedInput:n}}function iwr(t){let e=twr.exec(t);return e?{kind:e[1],call:t.slice(e[0].length)||t}:{call:t}}function swr(t){let e=t.toLowerCase();for(let[r,n]of owr)if(n.test(e))return r}function awr(t,e){let r=swr(t),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=Pot||a>rwr||!s||typeof s!="object")){if(Array.isArray(s)){for(let c of s)o(c,a+1);return}for(let[c,u]of Object.entries(s)){if(n.length>=Pot)return;c==="resourceId"&&typeof u=="string"&&u&&!i.has(u)?(i.add(u),n.push(u)):o(u,a+1)}}};return o(e,0),n.map(s=>({id:s,...r?{relation:r}:{}}))}function t3(t,e,r,n){let{kind:i,call:o}=iwr(r),s=awr(e,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${e}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};Mv(t,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(jde(),qde)).then(({log:d})=>d.error({tool:e,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${e}): ${u}
|
|
683
683
|
`))})}var Zl,Uot,ewr,twr,Pot,rwr,owr,r3=X(()=>{"use strict";Ez();yC();Zl="jot",Uot='Optional but valued: if this action involved a judgment call (which account, which match, an assumption, a risk accepted, a deviation), record it in one line, e.g. "MATCH: treated as distinct from BILL bil_x because references differ". Skip it for mechanical actions. '+vP,ewr=["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],twr=new RegExp(`^(${ewr.join("|")})\\s*:\\s*`),Pot=20,rwr=6;owr=[["RECONCILE",/(?:^|_)reconcile(?:_|$)/],["PAY",/(?:^|_)(?:pay|payment|payout|cash_out|disburse|disbursement|refund)(?:_|$)/],["FINALIZE",/(?:^|_)(?:finalize|convert_drafts_to_active)(?:_|$)/],["DELETE",/(?:^|_)(?:delete|void|discard)(?:_|$)|^rollback_capsule_recipe$/],["TRIGGER",/(?:^|_)(?:recipe|trigger|execute)(?:_|$)/],["UPDATE",/(?:^|_)update(?:_|$)|^rollback_document_version$/],["CREATE",/(?:^|_)create(?:_|$)/]]});function qot(t){let e=new Set,r=[];for(let n of t)for(let i of Wl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function cwr(t){return t.split("_").map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(" ")}function Gv(t){let e=t.readOnly?"read":OB(t)?"destructive":"write",r=Object.keys(t.params).filter(s=>!t.required.includes(s)),n=t.required.length?` required: ${t.required.join(", ")};`:"",i=r.length?` optional: ${r.slice(0,10).join(", ")}${r.length>10?", \u2026":""}`:"",o=(t.searchHint||t.description.split(`
|
|
684
684
|
`)[0]||"").trim().slice(0,140);return`- ${t.name} (${e}): ${o}${n}${i}`}function n3(t=!1){return Ti.map(e=>{let r=qot(e.groups),n=r.map(d=>d.name),i=r.length>0&&r.every(d=>d.readOnly),o=r.some(d=>!d.readOnly),s=r.some(d=>OB(d)),a=r.filter(d=>d.acceptsHostFile).map(d=>d.name),c=`${e.description}
|
|
@@ -834,7 +834,7 @@ No linked purchase transaction needed \u2014 unlike create_fixed_asset which req
|
|
|
834
834
|
|
|
835
835
|
accountResourceId + taxProfileResourceId apply to ALL line items (immutable). interval: WEEKLY | MONTHLY | QUARTERLY | YEARLY. reference REQUIRED. proratedConfig (optional) tunes the first period; response carries bundledPeriodEndDate + bundledAmount when includeNextPeriod=true.
|
|
836
836
|
|
|
837
|
-
Dynamic strings (reference/lineItem name/notes): ${kB} \u2014 relative to transaction date.`,params:{interval:{type:"string",enum:["WEEKLY","MONTHLY","QUARTERLY","YEARLY"],description:"Billing interval"},startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD, optional for ongoing)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},reference:{type:"string",description:"Invoice reference (REQUIRED). Supports dynamic strings: {{Month}}, {{Year}}, etc."},valueDate:{type:"string",description:"Invoice date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Due date (YYYY-MM-DD)"},accountResourceId:{type:"string",description:"Revenue account resourceId (applied to ALL line items \u2014 must be same)"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId (applied to ALL line items \u2014 must be same)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"}},required:["name","unitPrice","quantity"]},description:"Line items (name, unitPrice, quantity only \u2014 account/tax set at top level)"},proratedConfig:{type:"object",description:"Optional prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"Prorated window start (YYYY-MM-DD). Defaults to subscription startDate."},proratedAdjustmentLineText:{type:"string",description:'Adjustment line label on the prorated invoice (default "Prorated adjustment").'},itemResourceId:{type:"string",description:"Non-inventory item resourceId (UUIDv4) for the prorated adjustment line. Defaults to the subscription's first line item."},includeNextPeriod:{type:"boolean",description:"If true: bundle the next full period at 2x quantity AND advance nextScheduleDate by one extra interval. Response carries bundledPeriodEndDate + bundledAmount."}}}},required:["interval","startDate","contactResourceId","lineItems","accountResourceId","valueDate","dueDate","reference"],group:"subscriptions",readOnly:!1,searchHint:"create new recurring subscription billing schedule with proration",execute:async(t,e)=>{let{interval:r,startDate:n,endDate:i,contactResourceId:o,reference:s,valueDate:a,dueDate:c,accountResourceId:u,taxProfileResourceId:d,lineItems:f,proratedConfig:p}=e,h=f.map(A=>({...A,accountResourceId:u,...d?{taxProfileResourceId:d}:{}})),m={repeat:r,startDate:n,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment",...p??{}},invoice:{contactResourceId:o,reference:s||ui("SUB"),valueDate:a,dueDate:c,lineItems:h,saveAsDraft:!1}};return i&&(m.endDate=i),a8(t.client,m)}},{name:"update_subscription",description:"Update an existing subscription (interval, end date, transaction template, or proratedConfig). When the user asks to update a subscription, use this tool directly. NOTE: accountResourceId and taxProfileResourceId on line items are immutable after creation \u2014 to change them, cancel and recreate. proratedConfig fields can be amended on update (proratedStartDate, proratedAdjustmentLineText, itemResourceId, includeNextPeriod).",params:{resourceId:{type:"string",description:"Subscription resourceId"},interval:{type:"string",enum:["WEEKLY","MONTHLY","QUARTERLY","YEARLY"]},endDate:{type:"string",description:"New end date (YYYY-MM-DD)"},proratedConfig:{type:"object",description:"Amend the prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"YYYY-MM-DD"},proratedAdjustmentLineText:{type:"string"},itemResourceId:{type:"string",description:"UUIDv4"},includeNextPeriod:{type:"boolean"}}},data:{type:"object",description:"Updated transaction template"}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"update subscription schedule amount details proration",execute:async(t,e)=>{let{resourceId:r,...n}=e;return c8(t.client,r,n)}},Wr("delete_subscription","Delete a subscription. Removes the recurring schedule.","subscriptions",(t,e)=>l8(t,e),"permanently delete a subscription schedule"),{name:"cancel_subscription",description:"Cancel an active subscription. Prorates remaining period and stops future billing. Safe to call \u2014 subscriptions can be reactivated after cancellation. Always use this tool when the user asks to cancel a subscription. Must cancel before delete.",params:{resourceId:{type:"string",description:"Subscription resourceId"},cancelDateType:{type:"string",enum:["END_OF_CURRENT_PERIOD","END_OF_LAST_PERIOD","CUSTOM_DATE"],description:"When to end (default: END_OF_CURRENT_PERIOD)"},endDate:{type:"string",description:"Custom cancel date YYYY-MM-DD (only with CUSTOM_DATE)"},proratedAdjustmentLineText:{type:"string",description:'Label for proration line item (default: "Prorated adjustment")'}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"cancel stop a recurring subscription",isDestructive:!0,execute:async(t,e)=>u8(t.client,e.resourceId,{cancelDateType:e.cancelDateType,endDate:e.endDate,proratedAdjustmentLineText:e.proratedAdjustmentLineText})},Wt({name:"search_scheduled_transactions",description:"Search scheduled transactions (subscriptions / recurring invoices / journals / cash entries).",group:"subscriptions",fields:ES,defaults:bS,fetcher:d8,searchHint:"find scheduled recurring transactions subscriptions schedulers by type status interval contact"}),{name:"generate_vat_ledger",description:"Generate VAT/GST ledger report showing all tax transactions for the period.",params:{startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD)"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate VAT GST tax ledger report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>N2(t.client,{startDate:e.startDate,endDate:e.endDate})},{name:"generate_equity_movement",description:"Generate equity movement report (statement of changes in equity).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},compareWith:{type:"string",description:'Compare with period (e.g., "PREVIOUS_YEAR")'},compareCount:{type:"number",description:"Number of comparison periods"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"financial_reports",readOnly:!0,searchHint:"generate equity movement statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>O2(t.client,e)},{name:"generate_bank_balance_summary",description:"Generate bank balance summary report \u2014 snapshot of all bank account balances at a point in time.",params:{primarySnapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["primarySnapshotDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank account balance summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>F2(t.client,{primarySnapshotDate:e.primarySnapshotDate,currencyCode:e.currencyCode})},{name:"generate_bank_recon_summary",description:"Generate bank reconciliation summary for a specific bank account. Essential for month-end close \u2014 call this for each in-scope bank account for the current entity and reporting period. Use for bank recon status, unreconciled items count, or reconciliation summaries.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>Q2(t.client,e)},{name:"generate_bank_recon_details",description:"Generate detailed bank reconciliation report showing matched/unmatched items.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},filter:{type:"object",description:"Report filter. valueDate is required.",properties:{valueDate:{type:"object",description:"Report window.",properties:{range:{type:"array",items:{type:"string"},description:"Inclusive [from, to], YYYY-MM-DD. The only accepted operator."}},required:["range"]},reconciliationStatus:{type:"string",description:"Reconciliation status (no published enum)."}},required:["valueDate"]},currencyCode:{type:"string",description:"Currency code"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate","filter"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation detailed report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>L2(t.client,e)},{name:"generate_fa_summary",description:"Generate fixed assets summary report grouped by account, type, category, or status.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["ACCOUNT","TYPE","CATEGORY","STATUS"],description:"Grouping dimension"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate","groupBy"],group:"operational_reports",readOnly:!0,searchHint:"generate fixed asset summary depreciation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>M2(t.client,e)},{name:"generate_fa_recon_summary",description:"Generate fixed assets reconciliation summary \u2014 reconciles asset register with general ledger.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Filter by specific asset account IDs"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate fixed asset reconciliation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>P2(t.client,e)},{name:"generate_ar_report",description:"Generate accounts receivable aging report. Shows outstanding invoices grouped by aging buckets. Use this when discussing customer payment allocation, credit control, or AR status \u2014 generate the report to show the full picture.",params:{endDate:{type:"string",description:"Report date (YYYY-MM-DD) \u2014 point-in-time snapshot"}},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate detailed accounts receivable report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>U2(t.client,{endDate:e.endDate})},{name:"get_ledger_highlights",description:"Get ledger highlights \u2014 summary metadata about the org general ledger: transaction counts by type, date range, active accounts, active currencies, and cross-currency detection. No parameters needed.",params:{},required:[],group:"operational_reports",readOnly:!0,searchHint:"get ledger highlights key metrics for period",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>$2(t.client)},hr("list_contact_groups","List contact groups with their associated contacts. Used to segment customers/suppliers.","contact_groups",(t,e,r)=>f8(t,{limit:r,offset:e}),"list contact groups customer supplier categories"),Bi("get_contact_group","Get contact group details including all associated contacts.","contact_groups",(t,e)=>p8(t,e),"get contact group details members"),Wt({name:"search_contact_groups",description:"Search contact groups.",group:"contact_groups",fields:WS,defaults:ZS,fetcher:h8,searchHint:"find contact groups segments categories by name"}),{name:"create_contact_group",description:'Create a new contact group for segmenting contacts (e.g., "VIP Customers", "Government", "Overdue > 90 Days").',params:{name:{type:"string",description:"Group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to add to the group"}},required:["name"],group:"contact_groups",readOnly:!1,searchHint:"create new contact group category",execute:async(t,e)=>m8(t.client,{name:e.name,contactResourceIds:e.contactResourceIds})},{name:"update_contact_group",description:"Update a contact group name or members. Membership replaces the existing set.",params:{resourceId:{type:"string",description:"Contact group resourceId"},name:{type:"string",description:"New group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to set as group members, max 50 (replaces existing). Sent as associatedContactResourceIds."}},required:["resourceId"],group:"contact_groups",readOnly:!1,searchHint:"update contact group name details",execute:async(t,e)=>A8(t.client,e.resourceId,{name:e.name,contactResourceIds:e.contactResourceIds})},Wr("delete_contact_group","Delete a contact group. Does not delete the contacts themselves.","contact_groups",(t,e)=>g8(t,e),"permanently delete a contact group"),hr("list_custom_fields","List custom fields defined for the organization. Custom fields add extra data to invoices, bills, credit notes, and payments.","custom_fields",(t,e,r)=>C8(t,{limit:r,offset:e}),"list custom fields metadata on transactions"),{name:"get_custom_field",description:"Get a custom field by resourceId. Returns full definition including appliesTo flags and list options.",params:{resourceId:{type:"string",description:"Custom field resourceId"}},required:["resourceId"],group:"custom_fields",readOnly:!0,searchHint:"get custom field definition details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>_B(t.client,e.resourceId)},Wt({name:"search_custom_fields",description:"Search custom fields.",group:"custom_fields",fields:JS,defaults:VS,fetcher:I8,searchHint:"find custom fields user-defined attributes by name data type"}),{name:"create_custom_field",description:`Create a new custom field. Custom fields appear on transactions (invoices, bills, credit notes, payments).
|
|
837
|
+
Dynamic strings (reference/lineItem name/notes): ${kB} \u2014 relative to transaction date.`,params:{interval:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Billing interval, sent as `repeat`. QUARTERLY is rejected with 422."},startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD, optional for ongoing)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},reference:{type:"string",description:"Invoice reference (REQUIRED). Supports dynamic strings: {{Month}}, {{Year}}, etc."},valueDate:{type:"string",description:"Invoice date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Due date (YYYY-MM-DD)"},accountResourceId:{type:"string",description:"Revenue account resourceId (applied to ALL line items \u2014 must be same)"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId (applied to ALL line items \u2014 must be same)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"}},required:["name","unitPrice","quantity"]},description:"Line items (name, unitPrice, quantity only \u2014 account/tax set at top level)"},proratedConfig:{type:"object",description:"Optional prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"Prorated window start (YYYY-MM-DD). Defaults to subscription startDate."},proratedAdjustmentLineText:{type:"string",description:'Adjustment line label on the prorated invoice (default "Prorated adjustment").'},itemResourceId:{type:"string",description:"Non-inventory item resourceId (UUIDv4) for the prorated adjustment line. Defaults to the subscription's first line item."},includeNextPeriod:{type:"boolean",description:"If true: bundle the next full period at 2x quantity AND advance nextScheduleDate by one extra interval. Response carries bundledPeriodEndDate + bundledAmount."}}}},required:["interval","startDate","contactResourceId","lineItems","accountResourceId","valueDate","dueDate","reference"],group:"subscriptions",readOnly:!1,searchHint:"create new recurring subscription billing schedule with proration",execute:async(t,e)=>{let{interval:r,startDate:n,endDate:i,contactResourceId:o,reference:s,valueDate:a,dueDate:c,accountResourceId:u,taxProfileResourceId:d,lineItems:f,proratedConfig:p}=e,h=f.map(A=>({...A,accountResourceId:u,...d?{taxProfileResourceId:d}:{}})),m={repeat:r,startDate:n,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment",...p??{}},invoice:{contactResourceId:o,reference:s||ui("SUB"),valueDate:a,dueDate:c,lineItems:h,saveAsDraft:!1}};return i&&(m.endDate=i),a8(t.client,m)}},{name:"update_subscription",description:"Update an existing subscription (interval, end date, transaction template, or proratedConfig). When the user asks to update a subscription, use this tool directly. NOTE: accountResourceId and taxProfileResourceId on line items are immutable after creation \u2014 to change them, cancel and recreate. proratedConfig fields can be amended on update (proratedStartDate, proratedAdjustmentLineText, itemResourceId, includeNextPeriod).",params:{resourceId:{type:"string",description:"Subscription resourceId"},interval:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Billing interval, sent as `repeat`."},endDate:{type:"string",description:"New end date (YYYY-MM-DD)"},proratedConfig:{type:"object",description:"Amend the prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"YYYY-MM-DD"},proratedAdjustmentLineText:{type:"string"},itemResourceId:{type:"string",description:"UUIDv4"},includeNextPeriod:{type:"boolean"}}},data:{type:"object",description:"Updated transaction template"}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"update subscription schedule amount details proration",execute:async(t,e)=>{let{resourceId:r,...n}=e;return c8(t.client,r,n)}},Wr("delete_subscription","Delete a subscription. Removes the recurring schedule.","subscriptions",(t,e)=>l8(t,e),"permanently delete a subscription schedule"),{name:"cancel_subscription",description:"Cancel an active subscription. Prorates remaining period and stops future billing. Safe to call \u2014 subscriptions can be reactivated after cancellation. Always use this tool when the user asks to cancel a subscription. Must cancel before delete.",params:{resourceId:{type:"string",description:"Subscription resourceId"},cancelDateType:{type:"string",enum:["END_OF_CURRENT_PERIOD","END_OF_LAST_PERIOD","CUSTOM_DATE"],description:"When to end (default: END_OF_CURRENT_PERIOD)"},endDate:{type:"string",description:"Custom cancel date YYYY-MM-DD (only with CUSTOM_DATE)"},proratedAdjustmentLineText:{type:"string",description:'Label for proration line item (default: "Prorated adjustment")'}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"cancel stop a recurring subscription",isDestructive:!0,execute:async(t,e)=>u8(t.client,e.resourceId,{cancelDateType:e.cancelDateType,endDate:e.endDate,proratedAdjustmentLineText:e.proratedAdjustmentLineText})},Wt({name:"search_scheduled_transactions",description:"Search scheduled transactions (subscriptions / recurring invoices / journals / cash entries).",group:"subscriptions",fields:ES,defaults:bS,fetcher:d8,searchHint:"find scheduled recurring transactions subscriptions schedulers by type status interval contact"}),{name:"generate_vat_ledger",description:"Generate VAT/GST ledger report showing all tax transactions for the period.",params:{startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD)"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate VAT GST tax ledger report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>N2(t.client,{startDate:e.startDate,endDate:e.endDate})},{name:"generate_equity_movement",description:"Generate equity movement report (statement of changes in equity).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},compareWith:{type:"string",description:'Compare with period (e.g., "PREVIOUS_YEAR")'},compareCount:{type:"number",description:"Number of comparison periods"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"financial_reports",readOnly:!0,searchHint:"generate equity movement statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>O2(t.client,e)},{name:"generate_bank_balance_summary",description:"Generate bank balance summary report \u2014 snapshot of all bank account balances at a point in time.",params:{primarySnapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["primarySnapshotDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank account balance summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>F2(t.client,{primarySnapshotDate:e.primarySnapshotDate,currencyCode:e.currencyCode})},{name:"generate_bank_recon_summary",description:"Generate bank reconciliation summary for a specific bank account. Essential for month-end close \u2014 call this for each in-scope bank account for the current entity and reporting period. Use for bank recon status, unreconciled items count, or reconciliation summaries.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>Q2(t.client,e)},{name:"generate_bank_recon_details",description:"Generate detailed bank reconciliation report showing matched/unmatched items.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},filter:{type:"object",description:"Report filter. valueDate is required.",properties:{valueDate:{type:"object",description:"Report window.",properties:{range:{type:"array",items:{type:"string"},description:"Inclusive [from, to], YYYY-MM-DD. The only accepted operator."}},required:["range"]},reconciliationStatus:{type:"string",description:"Reconciliation status (no published enum)."}},required:["valueDate"]},currencyCode:{type:"string",description:"Currency code"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate","filter"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation detailed report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>L2(t.client,e)},{name:"generate_fa_summary",description:"Generate fixed assets summary report grouped by account, type, category, or status.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["ACCOUNT","TYPE","CATEGORY","STATUS"],description:"Grouping dimension"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate","groupBy"],group:"operational_reports",readOnly:!0,searchHint:"generate fixed asset summary depreciation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>M2(t.client,e)},{name:"generate_fa_recon_summary",description:"Generate fixed assets reconciliation summary \u2014 reconciles asset register with general ledger.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Filter by specific asset account IDs"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate fixed asset reconciliation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>P2(t.client,e)},{name:"generate_ar_report",description:"Generate accounts receivable aging report. Shows outstanding invoices grouped by aging buckets. Use this when discussing customer payment allocation, credit control, or AR status \u2014 generate the report to show the full picture.",params:{endDate:{type:"string",description:"Report date (YYYY-MM-DD) \u2014 point-in-time snapshot"}},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate detailed accounts receivable report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>U2(t.client,{endDate:e.endDate})},{name:"get_ledger_highlights",description:"Get ledger highlights \u2014 summary metadata about the org general ledger: transaction counts by type, date range, active accounts, active currencies, and cross-currency detection. No parameters needed.",params:{},required:[],group:"operational_reports",readOnly:!0,searchHint:"get ledger highlights key metrics for period",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>$2(t.client)},hr("list_contact_groups","List contact groups with their associated contacts. Used to segment customers/suppliers.","contact_groups",(t,e,r)=>f8(t,{limit:r,offset:e}),"list contact groups customer supplier categories"),Bi("get_contact_group","Get contact group details including all associated contacts.","contact_groups",(t,e)=>p8(t,e),"get contact group details members"),Wt({name:"search_contact_groups",description:"Search contact groups.",group:"contact_groups",fields:WS,defaults:ZS,fetcher:h8,searchHint:"find contact groups segments categories by name"}),{name:"create_contact_group",description:'Create a new contact group for segmenting contacts (e.g., "VIP Customers", "Government", "Overdue > 90 Days").',params:{name:{type:"string",description:"Group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to add to the group"}},required:["name"],group:"contact_groups",readOnly:!1,searchHint:"create new contact group category",execute:async(t,e)=>m8(t.client,{name:e.name,contactResourceIds:e.contactResourceIds})},{name:"update_contact_group",description:"Update a contact group name or members. Membership replaces the existing set.",params:{resourceId:{type:"string",description:"Contact group resourceId"},name:{type:"string",description:"New group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to set as group members, max 50 (replaces existing). Sent as associatedContactResourceIds."}},required:["resourceId"],group:"contact_groups",readOnly:!1,searchHint:"update contact group name details",execute:async(t,e)=>A8(t.client,e.resourceId,{name:e.name,contactResourceIds:e.contactResourceIds})},Wr("delete_contact_group","Delete a contact group. Does not delete the contacts themselves.","contact_groups",(t,e)=>g8(t,e),"permanently delete a contact group"),hr("list_custom_fields","List custom fields defined for the organization. Custom fields add extra data to invoices, bills, credit notes, and payments.","custom_fields",(t,e,r)=>C8(t,{limit:r,offset:e}),"list custom fields metadata on transactions"),{name:"get_custom_field",description:"Get a custom field by resourceId. Returns full definition including appliesTo flags and list options.",params:{resourceId:{type:"string",description:"Custom field resourceId"}},required:["resourceId"],group:"custom_fields",readOnly:!0,searchHint:"get custom field definition details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>_B(t.client,e.resourceId)},Wt({name:"search_custom_fields",description:"Search custom fields.",group:"custom_fields",fields:JS,defaults:VS,fetcher:I8,searchHint:"find custom fields user-defined attributes by name data type"}),{name:"create_custom_field",description:`Create a new custom field. Custom fields appear on transactions (invoices, bills, credit notes, payments).
|
|
838
838
|
- appliesTo controls which transaction types show this field. Omit it and it shows on none.
|
|
839
839
|
- printOnDocuments controls whether the field appears on PDFs.`,params:{name:{type:"string",description:'Field name (e.g., "PO Number", "Cost Center")'},description:{type:"string",description:"Field description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents (default false)"},appliesTo:{type:"object",description:"Which transaction types: { invoices: true, bills: true, customerCredits: true, supplierCredits: true, payments: true }"},format:Jot},required:["name"],group:"custom_fields",readOnly:!1,searchHint:"create new custom field for transactions",execute:async(t,e)=>v8(t.client,{...e,printOnDocuments:e.printOnDocuments??!1})},{name:"update_custom_field",description:"Update a custom field definition. Omitted fields keep their current values.",params:{resourceId:{type:"string",description:"Custom field resourceId"},name:{type:"string",description:"New field name"},description:{type:"string",description:"New description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents"},appliesTo:{type:"object",description:"Which transaction types: { invoices, bills, customerCredits, supplierCredits, payments }"},format:Jot},required:["resourceId"],group:"custom_fields",readOnly:!1,searchHint:"update custom field name type settings",execute:async(t,e)=>{let{resourceId:r,...n}=e;return w8(t.client,r,n)}},Wr("delete_custom_field","Delete a custom field. Removes it from all future transactions.","custom_fields",(t,e)=>_8(t,e),"permanently delete a custom field definition"),{name:"list_withholding_tax_codes",description:"List withholding tax codes (industry classification codes for PH/SG compliance). Returns full list (no pagination).",params:{},required:[],group:"tax_profiles",readOnly:!0,searchHint:"list withholding tax WHT codes",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async t=>$F(t.client)},Wt({name:"search_tax_profiles",description:"Search tax profiles. Use appliesToSale / appliesToPurchase filters to scope by transaction type.",group:"tax_profiles",fields:YS,defaults:HS,fetcher:FE,searchHint:"find tax profiles GST VAT WHT by name tax type code applicability sale purchase"}),Bi("get_tax_profile","Get full tax profile details including tax rate, type code, and status.","tax_profiles",(t,e)=>Lw(t,e),"get tax profile details rate code"),{name:"update_tax_profile",description:"Update an existing tax profile. Omitted fields keep their current values; status is not updatable.",params:{resourceId:{type:"string",description:"Tax profile resourceId"},name:_fe,description:{type:"string"},vatValue:{type:"number",description:"Tax rate % (0-100)"},taxType:{type:"string",description:"Tax type code (list_tax_types)"}},required:["resourceId"],group:"tax_profiles",readOnly:!1,searchHint:"update tax profile name rate details",execute:async(t,e)=>UF(t.client,e.resourceId,{name:e.name,description:e.description,vatValue:e.vatValue,taxType:e.taxType})},{name:"create_claim_type",description:"Create a claim type (expense category for employee claims). Dedups by name. expenseAccountResourceId is server-required.",params:{name:{type:"string",description:"Claim type name (unique per org)"},expenseAccountResourceId:{type:"string",description:'Expense CoA resourceId \u2014 REQUIRED server-side (search_accounts; accountType is a display label e.g. "Operating Expense")'},taxProfileResourceId:{type:"string",description:"Default tax profile resourceId"},classifierConfig:{type:"string",description:"Magic OCR classifier defaults (JSON string)"},isDefault:{type:"boolean",description:"Make org default (sweeps prior default)"}},required:["name"],group:"claim_types",readOnly:!1,searchHint:"create claim type expense category",execute:async(t,e)=>{let r=e.name,n=await I1(t.client,r);return n?{_guard:"duplicate_skipped",message:`Claim type "${r}" already exists.`,existing:n}:VF(t.client,{name:r,expenseAccountResourceId:e.expenseAccountResourceId,taxProfileResourceId:e.taxProfileResourceId,classifierConfig:e.classifierConfig,isDefault:e.isDefault})}},{name:"update_claim_type",description:"Update a claim type. Omitted fields unchanged; clearFields NULLs optional fields.",params:{resourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"New name"},expenseAccountResourceId:{type:"string",description:"Default expense CoA resourceId"},taxProfileResourceId:{type:"string",description:"Default tax profile resourceId"},classifierConfig:{type:"string",description:"Classifier defaults (JSON string)"},isDefault:{type:"boolean",description:"Make org default"},clearFields:{type:"array",items:{type:"string",enum:[...Uw]},description:"Optional fields to NULL (clear)"}},required:["resourceId"],group:"claim_types",readOnly:!1,searchHint:"update claim type",execute:async(t,e)=>WF(t.client,e.resourceId,{name:e.name,expenseAccountResourceId:e.expenseAccountResourceId,taxProfileResourceId:e.taxProfileResourceId,classifierConfig:e.classifierConfig,isDefault:e.isDefault,...xy(e.clearFields,Uw)})},Wt({name:"search_claim_types",description:"Search claim types.",group:"claim_types",fields:TS,defaults:BS,fetcher:LE,searchHint:"find claim types by name default expense account tax profile"}),hr("list_claim_types","List claim types (alphabetical).","claim_types",(t,e,r)=>GF(t,{offset:e,limit:r}),"list claim types"),Bi("get_claim_type","Get a claim type incl. nested expense account + tax profile.","claim_types",(t,e)=>JF(t,e),"get claim type details"),Wr("delete_claim_type","Soft-delete a claim type (name becomes reusable).","claim_types",(t,e)=>ZF(t,e),"delete claim type"),{name:"create_claim_profile",description:"Create a claim profile (per-employee policy bundle: approver, limits, visible types, balance account). Dedups by name. taxMode EXCLUSIVE is rejected.",params:{name:{type:"string",description:"Profile name (unique per org)"},approverUserResourceId:{type:"string",description:"Default approver user resourceId"},visibleClaimTypeIds:{type:"array",items:{type:"string"},description:"Allowed claim type IDs"},visibleTaxProfileIds:{type:"array",items:{type:"string"},description:"Allowed tax profile IDs"},visibleClassifierIds:{type:"array",items:{type:"string"},description:"Allowed classifier IDs"},visibleVendorResourceIds:{type:"array",items:{type:"string"},description:"Allowed vendor contact IDs (free-text vendors always allowed)"},allowedCurrencies:{type:"array",items:{type:"string"},description:"Allowed ISO currency codes (null = no restriction)"},minClaimAmount:{type:"number",description:"Min claim total (<= max)"},maxClaimAmount:{type:"number",description:"Max claim total"},maxPerPeriodAmount:{type:"number",description:"Per-period spend cap (requires perPeriod)"},perPeriod:{type:"string",enum:[...$w],description:"Per-period window"},employeeBalanceAccountResourceId:{type:"string",description:"Per-employee liability (CURRENT_LIABILITY) CoA resourceId; required for reimbursement conversion"},taxMode:{type:"string",enum:[...l9],description:"Tax policy (NO_TAX or INCLUSIVE)"},isDefault:{type:"boolean",description:"Make org default"}},required:["name"],group:"claim_profiles",readOnly:!1,searchHint:"create claim profile policy approver limits",execute:async(t,e)=>{let r=e.name,n=await v1(t.client,r);return n?{_guard:"duplicate_skipped",message:`Claim profile "${r}" already exists.`,existing:n}:t1(t.client,{name:r,approverUserResourceId:e.approverUserResourceId,visibleClaimTypeIds:e.visibleClaimTypeIds,visibleTaxProfileIds:e.visibleTaxProfileIds,visibleClassifierIds:e.visibleClassifierIds,visibleVendorResourceIds:e.visibleVendorResourceIds,allowedCurrencies:e.allowedCurrencies,minClaimAmount:e.minClaimAmount,maxClaimAmount:e.maxClaimAmount,maxPerPeriodAmount:e.maxPerPeriodAmount,perPeriod:e.perPeriod,employeeBalanceAccountResourceId:e.employeeBalanceAccountResourceId,taxMode:e.taxMode,isDefault:e.isDefault})}},{name:"update_claim_profile",description:"Update a claim profile. Omitted fields unchanged; clearFields NULLs optional fields. Balance account cannot change while an employee has a non-zero balance.",params:{resourceId:{type:"string",description:"Claim profile resourceId"},name:{type:"string",description:"New name"},approverUserResourceId:{type:"string",description:"Default approver user resourceId"},visibleClaimTypeIds:{type:"array",items:{type:"string"},description:"Allowed claim type IDs (replaces)"},visibleTaxProfileIds:{type:"array",items:{type:"string"},description:"Allowed tax profile IDs (replaces)"},visibleClassifierIds:{type:"array",items:{type:"string"},description:"Allowed classifier IDs (replaces)"},visibleVendorResourceIds:{type:"array",items:{type:"string"},description:"Allowed vendor contact IDs (replaces)"},allowedCurrencies:{type:"array",items:{type:"string"},description:"Allowed ISO currency codes (replaces)"},minClaimAmount:{type:"number",description:"Min claim total"},maxClaimAmount:{type:"number",description:"Max claim total"},maxPerPeriodAmount:{type:"number",description:"Per-period spend cap"},perPeriod:{type:"string",enum:[...$w],description:"Per-period window"},employeeBalanceAccountResourceId:{type:"string",description:"Employee balance CoA resourceId"},taxMode:{type:"string",enum:[...l9],description:"Tax policy (NO_TAX or INCLUSIVE)"},isDefault:{type:"boolean",description:"Make org default"},clearFields:{type:"array",items:{type:"string",enum:[...qw]},description:"Optional fields to NULL (clear)"}},required:["resourceId"],group:"claim_profiles",readOnly:!1,searchHint:"update claim profile policy limits",execute:async(t,e)=>r1(t.client,e.resourceId,{name:e.name,approverUserResourceId:e.approverUserResourceId,visibleClaimTypeIds:e.visibleClaimTypeIds,visibleTaxProfileIds:e.visibleTaxProfileIds,visibleClassifierIds:e.visibleClassifierIds,visibleVendorResourceIds:e.visibleVendorResourceIds,allowedCurrencies:e.allowedCurrencies,minClaimAmount:e.minClaimAmount,maxClaimAmount:e.maxClaimAmount,maxPerPeriodAmount:e.maxPerPeriodAmount,perPeriod:e.perPeriod,employeeBalanceAccountResourceId:e.employeeBalanceAccountResourceId,taxMode:e.taxMode,isDefault:e.isDefault,...xy(e.clearFields,qw)})},Wt({name:"search_claim_profiles",description:"Search claim profiles.",group:"claim_profiles",fields:kS,defaults:NS,fetcher:ME,searchHint:"find claim profiles by name approver default limits balance account"}),hr("list_claim_profiles","List claim profiles (alphabetical).","claim_profiles",(t,e,r)=>KF(t,{offset:e,limit:r}),"list claim profiles"),Bi("get_claim_profile","Get a claim profile incl. nested balance account.","claim_profiles",(t,e)=>e1(t,e),"get claim profile details"),Wr("delete_claim_profile","Soft-delete a claim profile.","claim_profiles",(t,e)=>n1(t,e),"delete claim profile"),{name:"create_posting_rule",description:"Create a posting rule (how approved claims group into journals at conversion). outerAxis + innerAxis + lineDescriptionTemplate required. Dedups by name.",params:{name:{type:"string",description:"Rule name (unique per org)"},outerAxis:{type:"string",enum:[...Yw],description:"Outer grouping axis"},innerAxis:{type:"string",enum:[...Hw],description:"Inner line-aggregation axis"},lineDescriptionTemplate:{type:"string",description:'Handlebars line template, e.g. "{employeeName} - {claimType}"'},journalReferenceTemplate:{type:"string",description:"Optional Handlebars journal-header reference template"},defaultBankAccountResourceId:{type:"string",description:"Default reimbursement bank (Cash/Bank) account resourceId"},defaultIncludeReimbursementPayout:{type:"boolean",description:"Create reimbursement DCE by default"},isDefault:{type:"boolean",description:"Make org default rule"}},required:["name","outerAxis","innerAxis","lineDescriptionTemplate"],group:"posting_rules",readOnly:!1,searchHint:"create posting rule claim conversion grouping",execute:async(t,e)=>{let r=e.name,n=await w1(t.client,r);return n?{_guard:"duplicate_skipped",message:`Posting rule "${r}" already exists.`,existing:n}:s1(t.client,{name:r,outerAxis:e.outerAxis,innerAxis:e.innerAxis,lineDescriptionTemplate:e.lineDescriptionTemplate,journalReferenceTemplate:e.journalReferenceTemplate,defaultBankAccountResourceId:e.defaultBankAccountResourceId,defaultIncludeReimbursementPayout:e.defaultIncludeReimbursementPayout,isDefault:e.isDefault})}},{name:"update_posting_rule",description:"Update a posting rule. Omitted fields unchanged.",params:{resourceId:{type:"string",description:"Posting rule resourceId"},name:{type:"string",description:"New name"},outerAxis:{type:"string",enum:[...Yw],description:"Outer grouping axis"},innerAxis:{type:"string",enum:[...Hw],description:"Inner line-aggregation axis"},lineDescriptionTemplate:{type:"string",description:"Handlebars line template"},journalReferenceTemplate:{type:"string",description:"Journal-header reference template"},defaultBankAccountResourceId:{type:"string",description:"Default reimbursement bank account resourceId"},defaultIncludeReimbursementPayout:{type:"boolean",description:"Create reimbursement DCE by default"},isDefault:{type:"boolean",description:"Make org default rule"}},required:["resourceId"],group:"posting_rules",readOnly:!1,searchHint:"update posting rule",execute:async(t,e)=>a1(t.client,e.resourceId,{name:e.name,outerAxis:e.outerAxis,innerAxis:e.innerAxis,lineDescriptionTemplate:e.lineDescriptionTemplate,journalReferenceTemplate:e.journalReferenceTemplate,defaultBankAccountResourceId:e.defaultBankAccountResourceId,defaultIncludeReimbursementPayout:e.defaultIncludeReimbursementPayout,isDefault:e.isDefault})},Wt({name:"search_posting_rules",description:"Search posting rules.",group:"posting_rules",fields:OS,defaults:FS,fetcher:PE,searchHint:"find posting rules by name axis default bank reimbursement"}),hr("list_posting_rules","List posting rules (alphabetical).","posting_rules",(t,e,r)=>i1(t,{offset:e,limit:r}),"list posting rules"),Bi("get_posting_rule","Get a posting rule.","posting_rules",(t,e)=>o1(t,e),"get posting rule details"),Wr("delete_posting_rule","Delete a posting rule. The org default cannot be deleted while default (set another default first).","posting_rules",(t,e)=>c1(t,e),"delete posting rule"),Wt({name:"search_claims",description:'Search/list employee-expense claims. Status: DRAFT|SUBMITTED|APPROVED|CONVERTED|REJECTED|CANCELLED (CONVERTED = "Processed"). Claims are born via create_claim, attachment, or conversion (no bare list \u2014 use search).',group:"claims",fields:DS,defaults:SS,fetcher:BP,searchHint:"find employee expense claims by status employee contact reference date amount"}),Bi("get_claim","Get a claim incl. line items, employee, amounts, status.","claims",(t,e)=>kP(t,e),"get claim details line items"),{name:"create_claim",description:"Create an employee-expense claim directly (bare create, no attachment). Vendor is EITHER contactResourceId OR vendorName, never both. saveAsDraft defaults to true (lands DRAFT with relaxed line validation); set false to validate + submit in one call (lands SUBMITTED). reference is REQUIRED when submitting (saveAsDraft=false) \u2014 omitting it returns 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT; a DRAFT saves without one.",params:{valueDate:{type:"string",description:"Business-transaction date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Claim currency (ISO 4217)"},saveAsDraft:{type:"boolean",description:"true (default) creates DRAFT; false validates + submits"},employeeResourceId:{type:"string",description:"Employee resourceId the claim is filed for"},contactResourceId:{type:"string",description:"Vendor contact resourceId (mutually exclusive with vendorName)"},vendorName:{type:"string",description:"Free-text vendor name (mutually exclusive with contactResourceId)"},reference:{type:"string",description:"User reference"},currencySymbol:{type:"string",description:"Currency symbol override"},taxInclusion:{type:"boolean",description:"Line amounts are tax-inclusive"},tags:{type:"array",items:{type:"string"},description:"Header-level tags"},internalNotes:{type:"string",description:"Internal notes (max 1000)"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId (defaults to org default)"},approverUserResourceId:{type:"string",description:"Approver user resourceId"},customFields:Qi,claimItems:rst},required:["valueDate","currencyCode"],group:"claims",readOnly:!1,searchHint:"create new employee expense claim draft vendor employee line items submit",execute:async(t,e)=>NP(t.client,{valueDate:e.valueDate,currencyCode:e.currencyCode,saveAsDraft:e.saveAsDraft,employeeResourceId:e.employeeResourceId,contactResourceId:e.contactResourceId,vendorName:e.vendorName,reference:e.reference,currencySymbol:e.currencySymbol,taxInclusion:e.taxInclusion,tags:e.tags,internalNotes:e.internalNotes,claimProfileResourceId:e.claimProfileResourceId,approverUserResourceId:e.approverUserResourceId,customFields:e.customFields,claimItems:e.claimItems})},{name:"update_claim",description:"Update a DRAFT claim (partial \u2014 omitted fields unchanged). claimItems non-empty REPLACES all lines, [] clears. Set saveAsDraft=false to validate + submit in one call \u2014 reference is REQUIRED at submit (else 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT); a DRAFT save needs none. Only DRAFT claims are editable.",params:{resourceId:{type:"string",description:"Claim resourceId"},saveAsDraft:{type:"boolean",description:"true (default) keeps editing; false validates + submits"},employeeResourceId:{type:"string",description:"Employee resourceId"},contactResourceId:{type:"string",description:"Vendor contact resourceId (mutually exclusive with vendorName)"},vendorName:{type:"string",description:"Free-text vendor name (mutually exclusive with contactResourceId)"},valueDate:{type:"string",description:"Business-transaction date (YYYY-MM-DD)"},reference:{type:"string",description:"User reference"},currencyCode:{type:"string",description:"Claim currency (ISO 4217)"},taxInclusion:{type:"boolean",description:"Line amounts are tax-inclusive"},tags:{type:"array",items:{type:"string"},description:"Header-level tags"},internalNotes:{type:"string",description:"Internal notes (max 1000)"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId"},approverUserResourceId:{type:"string",description:"Approver user resourceId"},customFields:Qi,claimItems:rst},required:["resourceId"],group:"claims",readOnly:!1,searchHint:"edit draft claim line items employee reference submit",execute:async(t,e)=>OP(t.client,e.resourceId,{saveAsDraft:e.saveAsDraft,employeeResourceId:e.employeeResourceId,contactResourceId:e.contactResourceId,vendorName:e.vendorName,valueDate:e.valueDate,reference:e.reference,currencyCode:e.currencyCode,taxInclusion:e.taxInclusion,tags:e.tags,internalNotes:e.internalNotes,claimProfileResourceId:e.claimProfileResourceId,approverUserResourceId:e.approverUserResourceId,customFields:e.customFields,claimItems:e.claimItems})},Wr("delete_claim","Delete a claim. Only DRAFT / REJECTED / CANCELLED claims are deletable (else 422).","claims",(t,e)=>FP(t,e),"delete remove claim record"),{name:"delete_claim_attachment",description:"Remove one attachment (receipt) from a claim. Returns the updated claim.",params:{resourceId:{type:"string",description:"Claim resourceId"},attachmentResourceId:{type:"string",description:"Attachment resourceId"}},required:["resourceId","attachmentResourceId"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"remove delete claim attachment receipt",execute:async(t,e)=>QP(t.client,e.resourceId,e.attachmentResourceId)},xfe("submit_claim","Submit a DRAFT claim for approval (DRAFT \u2192 SUBMITTED). Server enforces the transition. The claim must carry a reference \u2014 a referenceless DRAFT returns 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT (set it via update_claim first).","claims",(t,e)=>LP(t,e),{searchHint:"submit draft claim for approval"}),xfe("approve_claim","Approve a SUBMITTED claim (SUBMITTED \u2192 APPROVED). Approved claims become convertible to journals.","claims",(t,e)=>MP(t,e),{searchHint:"approve submitted claim"}),{name:"reject_claim",description:"Reject a SUBMITTED/APPROVED claim with a reason (\u2192 REJECTED).",params:{resourceId:{type:"string",description:"Claim resourceId"},rejectionReason:{type:"string",description:"Rejection reason (1-1000 chars)"}},required:["resourceId","rejectionReason"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"reject claim with reason",execute:async(t,e)=>PP(t.client,e.resourceId,e.rejectionReason)},{name:"cancel_claim",description:"Cancel a DRAFT/SUBMITTED claim with a reason (\u2192 CANCELLED).",params:{resourceId:{type:"string",description:"Claim resourceId"},cancellationReason:{type:"string",description:"Cancellation reason (1-1000 chars)"}},required:["resourceId","cancellationReason"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"cancel claim with reason",execute:async(t,e)=>UP(t.client,e.resourceId,e.cancellationReason)},xfe("unpost_claim","Unpost a CONVERTED claim \u2014 reverses the journal conversion back to APPROVED.","claims",(t,e)=>$P(t,e),{destructive:!0,searchHint:"unpost reverse converted claim conversion"}),{name:"bulk_submit_claims",description:"Bulk-submit DRAFT claims (ASYNC). Returns a job handle {jobId,...}; poll search_background_jobs by jobId for per-item results. Max 500 ids. Each claim must have a reference \u2014 referenceless claims fail per-item with CLAIM_REFERENCE_REQUIRED_AT_SUBMIT (check the job result).",params:{resourceIds:LB},required:["resourceIds"],group:"claim_processing",readOnly:!1,searchHint:"bulk submit many claims async job",execute:async(t,e)=>qP(t.client,e.resourceIds)},{name:"bulk_approve_claims",description:"Bulk-approve SUBMITTED claims (ASYNC). Returns a job handle; poll search_background_jobs by jobId. Max 500 ids.",params:{resourceIds:LB},required:["resourceIds"],group:"claim_processing",readOnly:!1,searchHint:"bulk approve many claims async job",execute:async(t,e)=>jP(t.client,e.resourceIds)},{name:"bulk_reject_claims",description:"Bulk-reject claims with one shared reason (ASYNC). Returns a job handle; poll search_background_jobs by jobId. Max 500 ids.",params:{resourceIds:LB,rejectionReason:{type:"string",description:"Reason applied to the whole batch (1-1000 chars)"}},required:["resourceIds","rejectionReason"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk reject many claims async job reason",execute:async(t,e)=>HP(t.client,e.resourceIds,e.rejectionReason)},{name:"bulk_cancel_claims",description:"Bulk-cancel claims with one shared reason (ASYNC). Returns a job handle; poll search_background_jobs by jobId. Max 500 ids.",params:{resourceIds:LB,cancellationReason:{type:"string",description:"Reason applied to the whole batch (1-1000 chars)"}},required:["resourceIds","cancellationReason"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk cancel many claims async job reason",execute:async(t,e)=>zP(t.client,e.resourceIds,e.cancellationReason)},{name:"bulk_delete_claims",description:"Bulk-delete claims (ASYNC; only DRAFT/REJECTED/CANCELLED are deletable). Returns a job handle; poll search_background_jobs by jobId. Max 500 ids.",params:{resourceIds:LB},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk delete many claims async job",execute:async(t,e)=>YP(t.client,e.resourceIds)},{name:"get_claim_tracking_tags",description:"List the tracking-tag values available across claims (picker; returns a bare array).",params:{},required:[],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"list claim tracking tags picker",execute:async t=>GP(t.client)},{name:"get_claim_custom_field_values",description:"List the custom-field values available across claims (picker; returns a bare array).",params:{},required:[],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"list claim custom field values picker",execute:async t=>JP(t.client)},{name:"preview_claims_conversion",description:"Preview the journals an APPROVED claim batch would produce at conversion \u2014 no write. Returns expenseSubTotal, previewJournals, and reimbursement DCE counts; non-APPROVED claims come back under erroredClaims (check it is empty before converting). Needs a default posting rule or an explicit postingRuleResourceId.",params:{claimResourceIds:{type:"array",items:{type:"string"},description:"APPROVED claim resourceIds (1-500)"},postingRuleResourceId:{type:"string",description:"Posting rule resourceId (null \u2192 org default rule)"},payoutFlow:{type:"string",enum:[...bB],description:"POST (journals only) or POST_AND_RECORD (+ books-only reimbursement DCE)"},includeReimbursementPayout:{type:"boolean",description:"Include per-employee reimbursement DCE lines"},bankAccountResourceId:{type:"string",description:"Reimbursement bank account for preview validation"}},required:["claimResourceIds"],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview claim conversion journals before posting",execute:async(t,e)=>$z(t.client,{claimResourceIds:e.claimResourceIds,postingRuleResourceId:e.postingRuleResourceId,payoutFlow:e.payoutFlow,includeReimbursementPayout:e.includeReimbursementPayout,bankAccountResourceId:e.bankAccountResourceId})},{name:"convert_claims_to_journal",description:"Convert an APPROVED claim batch into journals (atomic write). valueDate (YYYY-MM-DD) required. Preview first and confirm erroredClaims is empty. idempotencyKey is auto-generated for safe retries (pass your own to dedup across calls). includeReimbursementPayout adds a books-only reimbursement DCE \u2014 real-money disburse is intentionally not exposed.",params:{claimResourceIds:{type:"array",items:{type:"string"},description:"APPROVED claim resourceIds (1-500)"},valueDate:{type:"string",description:"Journal value date (YYYY-MM-DD)"},postingRuleResourceId:{type:"string",description:"Posting rule resourceId (null \u2192 org default rule)"},includeReimbursementPayout:{type:"boolean",description:"Create books-only reimbursement DCEs"},bankAccountResourceIdOverride:{type:"string",description:"Override the rule default reimbursement bank account"},contactResourceId:{type:"string",description:"Clearing contact for the reimbursement DCE cash-out"},idempotencyKey:{type:"string",description:"Optional retry-dedup token (must not start with CONV: / CONV-); auto-generated if omitted"}},required:["claimResourceIds","valueDate"],group:"claim_processing",readOnly:!1,searchHint:"convert post approved claims to journal entries",execute:async(t,e)=>qz(t.client,{claimResourceIds:e.claimResourceIds,valueDate:e.valueDate,postingRuleResourceId:e.postingRuleResourceId,includeReimbursementPayout:e.includeReimbursementPayout,bankAccountResourceIdOverride:e.bankAccountResourceIdOverride,contactResourceId:e.contactResourceId,idempotencyKey:e.idempotencyKey||ywr()})},{name:"record_employee_payout",description:"Record a books-only employee payout (reimbursement or advance) \u2014 a DCE, no real-money transfer. amount, paymentAccountResourceId and valueDate are required; reference auto-generated if omitted.",params:{employeeResourceId:{type:"string",description:"Employee resourceId"},amount:{type:"number",description:"Payout amount (> 0)"},paymentAccountResourceId:{type:"string",description:"Bank/cash account the DCE credits"},valueDate:{type:"string",description:"Value date (YYYY-MM-DD)"},payoutFor:{type:"string",enum:[...rot],description:"Classification (null \u2192 ADVANCE)"},currencyCode:{type:"string",description:"Settle currency (ISO 4217; omit \u2192 payment account currency)"},reference:{type:"string",description:"Payout reference (auto-generated if omitted)"},description:{type:"string",description:"Line description on the DCE"},internalNotes:{type:"string",description:"Internal notes"}},required:["employeeResourceId","amount","paymentAccountResourceId","valueDate"],group:"claim_processing",readOnly:!1,searchHint:"record employee reimbursement advance payout books-only DCE",execute:async(t,e)=>jz(t.client,{employeeResourceId:e.employeeResourceId,amount:e.amount,paymentAccountResourceId:e.paymentAccountResourceId,valueDate:e.valueDate,payoutFor:e.payoutFor,currencyCode:e.currencyCode,reference:e.reference||ui("EP"),description:e.description,internalNotes:e.internalNotes})},Wt({name:"search_employee_payouts",description:"Search recorded employee payouts (reimbursements + advances).",group:"claim_processing",fields:RS,defaults:xS,fetcher:Yz,searchHint:"find employee payouts reimbursements advances by employee reference status type"}),{name:"add_employee",description:"Create an employee (expense-claim member). The server requires userResourceId (a login user to bind \u2014 binding is PERMANENT) and claimProfileResourceId (REQUIRED \u2014 carries the employee balance account; the org default is NOT auto-applied). Dedups by email.",params:{name:{type:"string",description:"Employee display name"},userResourceId:{type:"string",description:"Login user's resourceId to bind \u2014 the userResourceId field from search_org_users, NOT the org-user record id (else EMPLOYEE_USER_NOT_FOUND). Required; permanent once set"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId \u2014 REQUIRED (carries the employee balance account; org default NOT auto-applied \u2192 EMPLOYEE_CLAIM_PROFILE_REQUIRED). search_claim_profiles"},email:{type:"string",description:"Work email (per-org unique)"},phone:{type:"string",description:"Phone (per-org unique)"},managerEmployeeResourceId:{type:"string",description:"Manager employee resourceId"},active:{type:"boolean",description:"Active flag (default true)"},employmentType:{type:"string",enum:[...mA],description:"Employment classification"}},required:["name","userResourceId","claimProfileResourceId"],group:"employees",readOnly:!1,searchHint:"create add employee claim member bind user",execute:async(t,e)=>{let r=e.email;if(r){let n=await _1(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Employee with email "${r}" already exists.`,existing:n}}return d1(t.client,{name:e.name,userResourceId:e.userResourceId,claimProfileResourceId:e.claimProfileResourceId,email:r,phone:e.phone,managerEmployeeResourceId:e.managerEmployeeResourceId,active:e.active,employmentType:e.employmentType})}},{name:"update_employee",description:"Update an employee (partial; omit = no change). To ARCHIVE, set active=false (reversible \u2014 prefer over delete_employee). userResourceId is NOT editable here \u2014 use bind_employee_user. Set clearEmploymentType to unset the classification.",params:{resourceId:{type:"string",description:"Employee resourceId"},name:{type:"string",description:"New name"},email:{type:"string",description:'Work email ("" clears it)'},phone:{type:"string",description:"Phone"},managerEmployeeResourceId:{type:"string",description:"Manager employee resourceId"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId"},active:{type:"boolean",description:"Active flag \u2014 set false to archive"},employmentType:{type:"string",enum:[...mA],description:"Employment classification"},clearEmploymentType:{type:"boolean",description:"Clear the classification back to unclassified"}},required:["resourceId"],group:"employees",readOnly:!1,searchHint:"update edit archive employee active claim profile",execute:async(t,e)=>f1(t.client,e.resourceId,{name:e.name,email:e.email,phone:e.phone,managerEmployeeResourceId:e.managerEmployeeResourceId,claimProfileResourceId:e.claimProfileResourceId,active:e.active,employmentType:e.employmentType,clearEmploymentType:e.clearEmploymentType})},Wt({name:"search_employees",description:"Search employees by name, email, phone, manager, claim profile, active, currency.",group:"employees",fields:QS,defaults:LS,fetcher:UE,searchHint:"find employees claim members by name email manager profile active"}),Wt({name:"search_employee_balances",description:"Search the employee-balance directory (per-currency reimbursement balances owed).",group:"employees",fields:MS,defaults:PS,fetcher:l1,searchHint:"employee reimbursement balances owed by currency employment type"}),Bi("get_employee","Get an employee incl. claim profile + user binding.","employees",(t,e)=>u1(t,e),"get employee details binding balance"),Wr("delete_employee","Delete an employee (server validates they are settled). Prefer update_employee active=false to archive reversibly.","employees",(t,e)=>p1(t,e),"delete remove employee"),{name:"bind_employee_user",description:"Bind a login user to an OFFLINE employee (one with no user bound yet \u2014 e.g. created via import without a binding email). ONE-WAY and PERMANENT: allowed only while unbound; rebind is blocked once set.",params:{resourceId:{type:"string",description:"Employee resourceId"},userResourceId:{type:"string",description:"Login user's resourceId \u2014 the userResourceId FIELD from search_org_users, NOT the org-user record id (else EMPLOYEE_USER_NOT_FOUND). One-way, permanent once set"}},required:["resourceId","userResourceId"],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"bind link login user to employee",execute:async(t,e)=>h1(t.client,e.resourceId,e.userResourceId)},{name:"preprocess_employees_file",description:"Preprocess an uploaded employee import sheet (CSV/XLSX) \u2014 returns a parsed row preview to review before import_employees. Provide the sheet fileUrl.",params:{fileUrl:{type:"string",description:"URL of the uploaded employee sheet"},fileName:{type:"string",description:"Display file name"},fileType:{type:"string",enum:["CSV","EML","HEIC","JPEG","JPG","PDF","PNG","TEXT","XLS","XLSX"],description:"File type (use CSV / XLS / XLSX for employee sheets)"}},required:["fileUrl"],group:"employees",readOnly:!0,isConcurrencySafe:!0,searchHint:"preprocess preview employee import sheet csv xlsx",execute:async(t,e)=>m1(t.client,{fileUrl:e.fileUrl,fileName:e.fileName,fileType:e.fileType})},{name:"import_employees",description:"Bulk create/update/delete employees from resolved rows (max 100 per array). Server validates rows synchronously (422 with row errors) then queues an async job \u2014 poll search_background_jobs by jobId. Create rows need a bound user + claim profile.",params:{create:{type:"array",description:"Create rows",items:{type:"object",properties:{name:{type:"string"},email:{type:"string"},userResourceId:{type:"string"},claimProfileResourceId:{type:"string"},employmentType:{type:"string",enum:[...mA]},managerEmployeeResourceId:{type:"string"},active:{type:"boolean"}},required:["name"]}},update:{type:"array",description:"Update rows",items:{type:"object",properties:{employeeResourceId:{type:"string"},name:{type:"string"},email:{type:"string"},employmentType:{type:"string",enum:[...mA]},active:{type:"boolean"}},required:["employeeResourceId"]}},delete:{type:"array",description:"Delete rows",items:{type:"object",properties:{employeeResourceId:{type:"string"}},required:["employeeResourceId"]}}},required:[],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"bulk import employees create update delete sheet async",execute:async(t,e)=>A1(t.client,{create:e.create,update:e.update,delete:e.delete})},hr("list_inventory_items","List inventory-tracked items with stock details, COGS accounts, and purchase/sale accounts.","inventory",(t,e,r)=>y8(t,{limit:r,offset:e}),"list inventory items stock levels quantities"),{name:"get_inventory_balance",description:"Get current inventory balance for a specific item \u2014 quantity on hand, average cost, base unit.",params:{itemResourceId:{type:"string",description:"Item resourceId"}},required:["itemResourceId"],group:"inventory",readOnly:!0,searchHint:"get inventory balance stock level for item",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>b8(t.client,e.itemResourceId)},{name:"create_inventory_item",description:"Create a new inventory-tracked item. Requires itemCode, name, unit, costingMethod (FIXED or WAC) and three account links. Use --input for full JSON body.",params:{itemCode:{type:"string",description:"Unique item code (SKU)"},name:{type:"string",description:"Item name"},unit:{type:"string",description:'Unit of measure, e.g. "pcs"'},costingMethod:{type:"string",enum:["FIXED","WAC"],description:"Costing method: FIXED or WAC"},cogsResourceId:{type:"string",description:"COGS account resourceId (Direct Costs type)"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId (Inventory type)"},saleAccountResourceId:{type:"string",description:"Sale account resourceId"},blockInsufficientDeductions:{type:"boolean",description:"Block transactions when insufficient stock (default: false)"}},required:["itemCode","name","unit","costingMethod","cogsResourceId","purchaseAccountResourceId","saleAccountResourceId"],group:"inventory",readOnly:!1,searchHint:"create new inventory tracked stock item",execute:async(t,e)=>E8(t.client,{itemCode:e.itemCode,name:e.name,unit:e.unit,costingMethod:e.costingMethod,cogsResourceId:e.cogsResourceId,purchaseAccountResourceId:e.purchaseAccountResourceId,saleAccountResourceId:e.saleAccountResourceId,appliesToSale:!0,appliesToPurchase:!0,blockInsufficientDeductions:e.blockInsufficientDeductions??!1})},Wr("delete_contact","Delete a contact. Cannot delete contacts with existing transactions.","contacts",(t,e)=>pF(t,e),"permanently delete a customer supplier contact"),Wr("delete_account","Delete a chart of accounts entry. Cannot delete accounts with existing transactions.","accounts",(t,e)=>NF(t,e),"permanently delete a chart of accounts entry"),Bi("get_cash_transfer","Get full cash transfer details by its cashflow-transaction resourceId (from search_cashflow_transactions), NOT the parentEntityResourceId create returns.","cash_transfers",(t,e)=>JH(t,e),"get cash transfer details between accounts"),PB("download_credit_note_pdf","customer credit note","customer_credit_notes",(t,e)=>X2(t,e)),{name:"get_transaction_summary",description:`Get a complete summary of any transaction \u2014 fetches the transaction, its attachments, and payment history in one call.
|
|
840
840
|
Works for invoices, bills, customer credit notes, supplier credit notes, and journals.`,params:{transactionType:{type:"string",enum:["invoice","bill","customer_credit_note","supplier_credit_note","journal"],description:"Transaction type"},resourceId:{type:"string",description:"Transaction resourceId"}},required:["transactionType","resourceId"],group:"search",readOnly:!0,searchHint:"get aggregated transaction counts totals by status",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>{let r=e.transactionType,n=e.resourceId,i=r==="invoice"?Qs(t.client,n):r==="bill"?xs(t.client,n):r==="customer_credit_note"?Ol(t.client,n):r==="supplier_credit_note"?Fl(t.client,n):Nl(t.client,n),o=r==="invoice"?"invoices":r==="bill"?"bills":r==="customer_credit_note"?"customer-credit-notes":r==="supplier_credit_note"?"supplier-credit-notes":"journals",[s,a]=await Promise.all([i,li(t.client,o,n)]),c;if(r==="invoice"||r==="bill")try{c=await EB(t.client,{filter:{businessTransactionResourceId:{eq:n}},limit:100})}catch{}let u=a.data??[];return{transaction:s.data,attachments:u,attachmentCount:u.length,...c?{payments:c.data,paymentCount:c.totalElements}:{}}}},{name:"bulk_finalize_drafts",description:"Finalize multiple draft transactions in one call. Attempts finalization for each item and returns per-item pass/fail results. Supports invoices, bills, and credit notes.",params:{items:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["invoice","bill","customer_credit_note","supplier_credit_note"],description:"Transaction type"},resourceId:{type:"string",description:"Transaction resourceId"}},required:["type","resourceId"]},description:"Array of {type, resourceId} to finalize"}},required:["items"],group:"drafts",readOnly:!1,searchHint:"bulk finalize approve multiple draft transactions",isDestructive:!0,execute:async(t,e)=>{let r=e.items,n=[];for(let i of r)try{let o=await UB(t.client,i.type,i.resourceId,{});i.type==="invoice"?await sR(t.client,i.resourceId,o):i.type==="bill"?await xw(t.client,i.resourceId,o):i.type==="customer_credit_note"?await mR(t.client,i.resourceId,o):i.type==="supplier_credit_note"&&await ER(t.client,i.resourceId,o),n.push({...i,success:!0})}catch(o){n.push({...i,success:!1,error:o instanceof Error?o.message:String(o)})}return{total:r.length,succeeded:n.filter(i=>i.success).length,failed:n.filter(i=>!i.success).length,results:n}}},{name:"bulk_invite_org_users",description:"Invite multiple users to the organization in one call. Accepts an array of user objects. Each user follows the same contract as invite_org_user. Returns per-user pass/fail results.",params:{users:{type:"array",items:{type:"object",properties:{email:{type:"string",description:"User email"},firstName:{type:"string",description:"First name"},lastName:{type:"string",description:"Last name"},userType:{type:"string",enum:[...rg],description:"ADMIN = full access (moduleRoles ignored). CUSTOM_USER = per-module access via moduleRoles."},moduleRoles:{type:"array",items:{type:"object",properties:{moduleName:{type:"string",enum:[...EC]},roleCode:{type:"string",enum:[...tg]}},required:["moduleName","roleCode"]},description:"Use when userType is CUSTOM_USER; ignored for ADMIN."}},required:["email","firstName","lastName","userType"]},description:"Array of users to invite"}},required:["users"],group:"org_users",readOnly:!1,searchHint:"bulk invite multiple users to organization",execute:async(t,e)=>{let r=e.users,n=[];for(let i of r)try{let o=await Pv(t.client,i);n.push({email:i.email,success:!0,resourceId:o.data?.resourceId})}catch(o){n.push({email:i.email,success:!1,error:o instanceof Error?o.message:String(o)})}return{total:r.length,succeeded:n.filter(i=>i.success).length,failed:n.filter(i=>!i.success).length,results:n}}},{name:"bulk_create_contacts",description:`Create multiple contacts in one call. Deduplicates against existing contacts (exact name match).
|
|
@@ -1048,7 +1048,7 @@ clio() {
|
|
|
1048
1048
|
\u2713 Journal finalized: ${y.reference||y.resourceId}`)),console.log(R(" Status:"),y.status),C.length>0&&console.log(R(" Updated:"),C.join(", ")))})(i)),r.command("attachments <resourceId>").description("List attachments for a journal (URLs for agent inspection)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let a=(await Nl(o,n)).data,u=(await li(o,"journals",n)).data;if(i.json)console.log(JSON.stringify({journalResourceId:n,journalReference:a.reference||null,attachments:u},null,2));else{if(u.length===0){console.log(`No attachments for journal ${a.reference||n}.`);return}console.log(R(`Attachments for ${a.reference||n}:
|
|
1049
1049
|
`));for(let d of u)console.log(` ${Se(d.resourceId)} ${d.fileName||"(unnamed)"}`),d.fileUrl&&console.log(` ${H(d.fileUrl)}`)}})(i)),e.command("bulk-upsert").description("Create or update manual journals in bulk (max 500). Natural key: journalReference (NOT reference). Each row carries multi-leg journalEntries[] (NOT entries[]); each leg is organizationAccountResourceId plus exactly one of debitAmount/creditAmount, omitting the unused side. Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`. Dates ISO 8601 only.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o=be(i);o||(console.error('Error: --input <file> is required (JSON with { "journals": [...] } or a bare array)'),process.exit(1));let s=o.journals??o;Array.isArray(s)||(console.error('Error: expected { "journals": [...] }'),process.exit(1)),Nt(s,"journals",500,"journals");let a=await w2(n,s);i.json?console.log(JSON.stringify(a.data,null,2)):(console.log(Y(`Bulk upsert started. Job ID: ${a.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${a.data.jobId}`)))}))}Fe();Mt();gB();At();_t();dr();Ut();fr();function d3(t){return!Number.isFinite(t)||t===0?"\u2014":new Date(t).toISOString().slice(0,10)}function Ffe(t){let e=En(t.transactionStatus);console.log(R("Reference:"),t.transactionReference||"(none)"),console.log(R(" ID:"),Se(t.resourceId)),console.log(R(" Status:"),e),console.log(R(" Date:"),d3(t.valueDate)),console.log(R(" Type:"),t.businessTransactionType),console.log(R(" Direction:"),t.direction),console.log(R(" Amount:"),`${t.currencySymbol}${t.totalAmount.toFixed(2)} ${t.currencyCode}`),console.log(R(" Account:"),t.account?.name||"\u2014",H(`(${t.organizationAccountResourceId})`)),t.contactResourceId&&console.log(R(" Contact:"),t.contactResourceId)}var Ust=[{key:"resourceId",header:"ID",format:Be},{key:"transactionReference",header:"Reference",format:zn},{key:"transactionStatus",header:"Status",format:t=>En(String(t))},{key:"totalAmount",header:"Amount",align:"right",format:bn},{key:"valueDate",header:"Date",format:t=>d3(Number(t))}];function Qfe(t,e){let r=t.command(e.name).description(`Manage ${e.label.toLowerCase()} entries`);r.command("list").description(`List ${e.label.toLowerCase()} entries`).option("--limit <n>","Max results (default 100)",de).option("--offset <n>","Page number offset (0-indexed)",Ye).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o=await He(i,s=>e.listFn(n,s),{label:`Fetching ${e.label.toLowerCase()} entries`});$e(o,Ust,i,e.label)})),r.command("get <resourceId>").description(`Get a ${e.label.toLowerCase()} entry by ID`).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let{data:s}=await e.getFn(o,n);i.json?console.log(JSON.stringify(s,null,2)):Ffe(s)})(i)),r.command("create").description(`Create a ${e.label.toLowerCase()} entry (saves as draft by default)`).option("--jot <text>",we).option("--account <resourceId>","Bank account name or resourceId").option("--entries <json>","Entry lines as JSON array (offset entries)",fc).option("--date <YYYY-MM-DD>","Value date").option("--ref <reference>","Reference").option("--notes <text>","Notes").option("--tag <tag>","Tag").option(mc,Ac).option(gc,yc,Ko).option(Wi,Ts,Zi).option("--finalize","Finalize instead of saving as draft").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o=be(i),s;if(o)s=await e.createFn(n,{...o,saveAsDraft:o.saveAsDraft??!i.finalize});else{Le(i,[{flag:"--account",key:"account"},{flag:"--entries",key:"entries"},{flag:"--date",key:"date"}]);let c=await oi(n,i.account,{filter:"bank",silent:i.json});i.account=c.resourceId;let u={accountResourceId:i.account,lines:i.entries,valueDate:i.date,saveAsDraft:!i.finalize};i.ref&&(u.reference=i.ref),i.notes&&(u.internalNotes=i.notes),i.tag&&(u.tags=[i.tag]);let d=Ec(i);bc(d,i),d&&(u.currency=d),s=await e.createFn(n,u)}let a=s.data;if(i.json)console.log(JSON.stringify(a,null,2));else{let c=i.finalize?"finalized":"draft";console.log(Y(`${e.label} created (${c}): ${a.resourceId}`)),console.log(R("ID:"),a.resourceId)}ve(n,`create_${e.name.replace(/-/g,"_")}`,i,s.data)})),r.command("update <resourceId>").description(`Update a ${e.label.toLowerCase()} entry`).option("--jot <text>",we).option("--entries <json>","Entry lines as JSON array",fc).option("--date <YYYY-MM-DD>","Value date").option("--ref <reference>","Reference").option("--notes <text>","Notes").option("--tag <tag>","Tag").option("--finalize","Finalize instead of saving as draft").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let s=be(i),a;if(s)a=await e.updateFn(o,n,{...s,saveAsDraft:s.saveAsDraft??!i.finalize});else{let u={};i.entries&&(u.lines=i.entries),i.date&&(u.valueDate=i.date),i.ref&&(u.reference=i.ref),i.notes&&(u.internalNotes=i.notes),i.tag&&(u.tags=[i.tag]),u.saveAsDraft=!i.finalize,a=await e.updateFn(o,n,u)}let c=a.data;if(i.json)console.log(JSON.stringify(c,null,2));else{let u=i.finalize?"finalized":"draft";console.log(Y(`${e.label} updated (${u}): ${c.resourceId||n}`))}ve(o,`update_${e.name.replace(/-/g,"_")}`,i,a.data)})(i)),Ve({parent:r,fields:zd,defaults:Gd,fetcher:hm,columns:Ust,label:`Searching ${e.label.toLowerCase()}`,baseFilter:{businessTransactionType:{eq:e.txnType}},preProcess:async(n,i)=>{if(i.account){let o=await oi(n,i.account,{filter:"bank",silent:!!i.json});i.accountId=o.resourceId}}}),r.command("delete <resourceId>").description(`Delete/void a ${e.label.toLowerCase()} entry`).option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{await pm(o,n),i.json?console.log(JSON.stringify({deleted:!0,resourceId:n})):console.log(Y(`${e.label} ${n} deleted.`)),ve(o,`delete_${e.name.replace(/-/g,"_")}`,i,{resourceId:n})})(i))}zH();Fe();bde();gB();At();_t();dr();Ut();Mt();fr();var $st=[{key:"resourceId",header:"ID",format:Be},{key:"transactionReference",header:"Reference",format:zn},{key:"transactionStatus",header:"Status",format:t=>En(String(t))},{key:"totalAmount",header:"Amount",align:"right",format:bn},{key:"valueDate",header:"Date",format:t=>d3(Number(t))}];function qst(t){let e=t.command("cash-transfer").description("Manage cash transfer entries");e.command("list").description("List cash transfers").option("--limit <n>","Max results (default 100)",de).option("--offset <n>","Page number offset (0-indexed)",Ye).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=await He(n,o=>GH(r,o),{label:"Fetching cash transfers"});$e(i,$st,n,"Cash Transfers")})),e.command("get <resourceId>").description("Get a cash transfer by ID").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{let{data:o}=await JH(i,r);n.json?console.log(JSON.stringify(o,null,2)):Ffe(o)})(n)),e.command("create").description("Create a cash transfer (saves as draft by default)").option("--jot <text>",we).option("--from-account <resourceId>","Source bank account name or resourceId (cash-out)").option("--to-account <resourceId>","Destination bank account name or resourceId (cash-in)").option("--amount <amount>","Transfer amount",ar).option("--date <YYYY-MM-DD>","Value date").option("--ref <reference>","Reference").option("--finalize","Finalize instead of saving as draft").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=be(n),o;if(i)o=await uB(r,{...i,saveAsDraft:i.saveAsDraft??!n.finalize});else{Le(n,[{flag:"--from-account",key:"fromAccount"},{flag:"--to-account",key:"toAccount"},{flag:"--amount",key:"amount"},{flag:"--date",key:"date"}]);let a=await oi(r,n.fromAccount,{filter:"bank",silent:n.json});n.fromAccount=a.resourceId;let c=await oi(r,n.toAccount,{filter:"bank",silent:n.json});if(n.toAccount=c.resourceId,n.fromAccount===n.toAccount)throw new Error("--from-account and --to-account must be different");let u={valueDate:n.date,cashOut:{accountResourceId:n.fromAccount,amount:n.amount},cashIn:{accountResourceId:n.toAccount,amount:n.amount},saveAsDraft:!n.finalize};n.ref&&(u.reference=n.ref),o=await uB(r,u)}let s=o.data;if(n.json)console.log(JSON.stringify(s,null,2));else{let a=n.finalize?"finalized":"draft";console.log(Y(`Cash transfer created (${a}): ${s.resourceId}`)),console.log(R("ID:"),s.resourceId)}ve(r,"create_cash_transfer",n,s)})),Ve({parent:e,fields:zd,defaults:Gd,fetcher:hm,columns:$st,label:"Searching cash transfers",baseFilter:{businessTransactionType:{eq:"JOURNAL_CASH_TRANSFER"}},preProcess:async(r,n)=>{if(n.account){let i=await oi(r,n.account,{filter:"bank",silent:!!n.json});n.accountId=i.resourceId}}}),e.command("delete <resourceId>").description("Delete/void a cash transfer").option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{await pm(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Cash transfer ${r} deleted.`)),ve(i,"delete_cash_transfer",n,{resourceId:r})})(n))}Fe();zde();At();_t();dr();fr();Ut();Mt();var jst=[{key:"resourceId",header:"ID",format:Be},{key:"businessTransactionReference",header:"Reference",format:zn},{key:"direction",header:"Dir",format:aP},{key:"valueDate",header:"Date",format:Qp},{key:"totalAmount",header:"Amount",align:"right"},{key:"businessTransactionType",header:"Type",format:t=>H(String(t??""))}];function Yst(t){let e=t.command("payments").description("Payment records: search, get, update, delete");e.command("list").description("List recent cashflow transactions").option("--limit <n>","Max results (default 100)",de).option("--offset <n>","Page number offset (0-indexed)",Ye).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=await He(n,o=>Dz(r,o),{label:"Fetching transactions"});$e(i,jst,n,"Payments")})),Ve({parent:e,fields:dS,defaults:fS,fetcher:EB,columns:jst,label:"Searching payments"}),e.command("get <resourceId>").description("Get a specific payment record").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{let s=(await Sz(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("ID:"),s.resourceId),console.log(R("Amount:"),s.paymentAmount),console.log(R("Date:"),s.valueDate),console.log(R("Method:"),s.paymentMethod),console.log(R("Reference:"),s.reference))})(n)),e.command("update <resourceId>").description("Update a payment record").option("--amount <n>","Corrected payment amount").option("--reference <ref>","Payment reference").option("--date <YYYY-MM-DD>","Payment date").option("--method <method>","Payment method (BANK_TRANSFER, CASH, CHEQUE, etc.)").option("--input <file>","Read full update body from JSON file (or pipe via stdin). Overrides flags").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{let o=be(n),s;o?s=o:(s={},n.amount&&(s.paymentAmount=parseFloat(n.amount)),n.reference&&(s.reference=n.reference),n.date&&(s.valueDate=n.date),n.method&&(s.paymentMethod=n.method));let a=await Rz(i,r,s);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(Y(`Payment ${r} updated.`))})(n)),e.command("delete <resourceId>").description("Delete (void) a payment record").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{await xz(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Payment ${r} deleted.`))})(n))}Fe();vp();ZD();At();import{readFileSync as Uwr}from"node:fs";import{basename as $wr,extname as qwr,resolve as jwr}from"node:path";_t();fr();Mt();var Ywr=[{key:"resourceId",header:"ID",format:Be},{key:"valueDate",header:"Date"},{key:"netAmount",header:"Amount",align:"right",format:bn},{key:"description",header:"Description"},{key:"extContactName",header:"Payer/Payee"},{key:"status",header:"Status"}],Hst={".csv":"text/csv",".ofx":"application/x-ofx",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function zst(t){let e=t.command("bank").description("Bank accounts and records");e.command("accounts").description("List bank accounts").option("--limit <n>","Max results",de).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o=await Yb(n,{limit:i.limit});if(i.json)console.log(JSON.stringify(o,null,2));else{console.log(R(`Bank Accounts (${o.data.length}):
|
|
1050
1050
|
`));for(let s of o.data)console.log(` ${Se(s.resourceId)} ${s.name} ${H(s.currencyCode)} ${s.status}`)}})),e.command("get <resourceId>").description("Get a bank account by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let a=(await Hb(o,n)).data;i.json?console.log(JSON.stringify(a,null,2)):(console.log(R("Name:"),a.name),console.log(R("ID:"),a.resourceId),console.log(R("Account ID:"),a.accountResourceId),console.log(R("Currency:"),a.currencyCode),console.log(R("Status:"),a.status))})(i)),Ve({parent:e,commandName:"records",fields:pS,defaults:hS,fetcher:zb,columns:Ywr,label:"Searching bank records",positionalArg:"accountResourceId",pathParam:"accountResourceId",pathParamDescription:"Bank account resourceId"}),e.command("add-records <accountResourceId>").description("Add bank records via JSON (1-100 records per call)").option("--jot <text>",we).requiredOption("--records <json>","JSON array: [{amount, transactionDate, description?, payerOrPayee?, reference?}]").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let s=JSON.parse(i.records);if(!Array.isArray(s))throw new Error("--records must be a JSON array");if(s.length<1||s.length>100)throw new Error("--records must contain 1-100 entries");for(let[u,d]of s.entries()){if(typeof d!="object"||d===null)throw new Error(`records[${u}] must be an object`);if(typeof d.amount!="number"||!Number.isFinite(d.amount))throw new Error(`records[${u}].amount must be a finite number`);if(typeof d.transactionDate!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(d.transactionDate))throw new Error(`records[${u}].transactionDate must be YYYY-MM-DD`)}let a=await WL(o,n,s),c=Array.isArray(a?.data?.errors)?a.data.errors:[];if(i.json)console.log(JSON.stringify(a.data,null,2));else if(c.length>0){console.log(ne(`${c.length} error(s):`));for(let u of c)console.log(` ${ne(String(u))}`)}else console.log(Y(`Created ${s.length} bank record(s).`));ve(o,"add_bank_records",i,a.data)})(i));let r=_P;e.command("auto-recon").description("Get auto-reconciliation recommendations for specific bank statement entries").requiredOption("--type <type>",`Recommendation type (${r.join(", ")}). RECOMMENDATIONS returns every type except MAGIC_MATCH in one ranked call and is cheaper; MAGIC_MATCH scans open transactions and is requested on its own.`).requiredOption("--entries <ids>","Comma-separated bank statement entry resourceIds. Required \u2014 there is no account-wide mode, because an unscoped scan exceeds the request timeout on high-volume accounts.").option("--account <resourceId>","Bank account resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o=i.type.toUpperCase();r.includes(o)||(console.error(ne(`Invalid --type: ${o}`)),console.error(H(`Valid types: ${r.join(", ")}`)),process.exit(1));let s=i.entries.split(",").map(a=>a.trim()).filter(Boolean);s.length===0&&(console.error(ne("--entries must name at least one bank statement entry")),process.exit(1));try{let a=await n.post("/api/v1/search-magic-reconciliation",{bankAccountResourceId:i.account,recommendationType:o,bankStatementEntryResourceIds:s});if(i.json)console.log(JSON.stringify(a,null,2));else{let c=a.data,u=Array.isArray(c)?c.length:0;if(console.log(R(`Auto-Reconciliation Suggestions (${o}): ${u} found
|
|
1051
|
-
`)),Array.isArray(c)){for(let d of c.slice(0,50)){let f=d,p=f.description??f.bankRecordDescription??"",h=typeof f.amount=="number"?H(` $${f.amount.toFixed(2)}`):"";console.log(` ${Se(String(f.bankRecordResourceId??f.resourceId??"?"))} ${p}${h}`)}c.length>50&&console.log(H(` ... and ${c.length-50} more (use --json for full output)`))}else console.log(JSON.stringify(a,null,2))}}catch(a){throw(a.status??a.response?.status)===404&&(console.error(ke("Auto-reconciliation endpoint not available on this server.")),process.exit(1)),a}})),e.command("import").description("Import a bank statement file (CSV, OFX, XLS, XLSX)").option("--jot <text>",we).requiredOption("--file <path>","Bank statement file path").requiredOption("--account <resourceId>","Bank account resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o=jwr(i.file),s=qwr(o).toLowerCase(),a=Hst[s];a||(console.error(ne(`Error: unsupported file type "${s}". Supported: ${Object.keys(Hst).join(", ")}`)),process.exit(1));let c=Uwr(o),u=new Blob([c],{type:a}),d=$wr(o),f=await Gb(n,{businessTransactionType:"BANK_STATEMENT",accountResourceId:i.account,sourceFile:u,sourceFileName:d});i.json?console.log(JSON.stringify(f.data,null,2)):(console.log(Y("Bank statement uploaded \u2014 processing started.")),console.log(R("File:"),d),console.log(H("Check status: clio
|
|
1051
|
+
`)),Array.isArray(c)){for(let d of c.slice(0,50)){let f=d,p=f.description??f.bankRecordDescription??"",h=typeof f.amount=="number"?H(` $${f.amount.toFixed(2)}`):"";console.log(` ${Se(String(f.bankRecordResourceId??f.resourceId??"?"))} ${p}${h}`)}c.length>50&&console.log(H(` ... and ${c.length-50} more (use --json for full output)`))}else console.log(JSON.stringify(a,null,2))}}catch(a){throw(a.status??a.response?.status)===404&&(console.error(ke("Auto-reconciliation endpoint not available on this server.")),process.exit(1)),a}})),e.command("import").description("Import a bank statement file (CSV, OFX, XLS, XLSX)").option("--jot <text>",we).requiredOption("--file <path>","Bank statement file path").requiredOption("--account <resourceId>","Bank account resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o=jwr(i.file),s=qwr(o).toLowerCase(),a=Hst[s];a||(console.error(ne(`Error: unsupported file type "${s}". Supported: ${Object.keys(Hst).join(", ")}`)),process.exit(1));let c=Uwr(o),u=new Blob([c],{type:a}),d=$wr(o),f=await Gb(n,{businessTransactionType:"BANK_STATEMENT",accountResourceId:i.account,sourceFile:u,sourceFileName:d});i.json?console.log(JSON.stringify(f.data,null,2)):(console.log(Y("Bank statement uploaded \u2014 processing started.")),console.log(R("File:"),d),console.log(H("Check status: clio background-jobs get <jobId>"))),ve(n,"import_bank_statement",i,f.data)}))}Fe();zX();At();_t();var Lfe=["trial-balance","balance-sheet","profit-loss","cashflow","aged-ar","aged-ap","cash-balance","general-ledger","vat-ledger","equity-movement","bank-balance-summary","bank-recon-summary","bank-recon-details","fa-summary","fa-recon-summary","ar-report","ledger-highlights"],Mfe=["ACCOUNT","CONTACT","TRANSACTION","RELATIONSHIP"],Pfe=["ACCOUNT","TYPE","CATEGORY","STATUS"];function Gst(t){t.command("reports").description("Generate financial reports").command("generate <type>").description(`Generate a report (${Lfe.join(", ")})`).option("--from <YYYY-MM-DD>","Start date (for P&L, cashflow, equity, recon)").option("--to <YYYY-MM-DD>","End/snapshot date").option("--currency <code>","Currency code override").option("--group-by <groupBy>",`Group by \u2014 general-ledger: ${Mfe.join(", ")} | fa-summary: ${Pfe.join(", ")} (default ACCOUNT)`).option("--bank-account <id>","Bank account resourceId (for bank-recon-*)").option("--aggregate","For aged-ar/aged-ap: compact aging-bucket summary instead of the full per-contact breakdown").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>(Lfe.includes(r)||(console.error(ne(`Invalid report type: ${r}`)),console.error(H(`Valid types: ${Lfe.join(", ")}`)),process.exit(1)),F(async i=>{let o=Z4(),s;switch(r){case"trial-balance":s=await _2(i,{endDate:n.to??o,currencyCode:n.currency});break;case"balance-sheet":s=await D2(i,{primarySnapshotDate:n.to??o,currencyCode:n.currency});break;case"profit-loss":s=await S2(i,{startDate:n.from??`${o.slice(0,4)}-01-01`,endDate:n.to??o,currencyCode:n.currency});break;case"cashflow":s=await R2(i,{startDate:n.from??`${o.slice(0,4)}-01-01`,endDate:n.to??o});break;case"aged-ar":{let a=await x2(i,{startDate:n.from??`${(n.to??o).slice(0,4)}-01-01`,endDate:n.to??o});s=n.aggregate?{data:DC(a,"receivables")}:a;break}case"aged-ap":{let a=await T2(i,{startDate:n.from??`${(n.to??o).slice(0,4)}-01-01`,endDate:n.to??o});s=n.aggregate?{data:DC(a,"payables")}:a;break}case"cash-balance":s=await B2(i,{endDate:n.to??o});break;case"general-ledger":{let a=(n.groupBy??"ACCOUNT").toUpperCase();Mfe.includes(a)||(console.error(ne(`Invalid --group-by: ${a}`)),console.error(H(`Valid values: ${Mfe.join(", ")}`)),process.exit(1)),s=await k2(i,{startDate:n.from??`${o.slice(0,4)}-01-01`,endDate:n.to??o,groupBy:a});break}case"vat-ledger":s=await N2(i,{startDate:n.from??`${o.slice(0,4)}-01-01`,endDate:n.to??o});break;case"equity-movement":s=await O2(i,{primarySnapshotStartDate:n.from??`${o.slice(0,4)}-01-01`,primarySnapshotEndDate:n.to??o,currencyCode:n.currency});break;case"bank-balance-summary":s=await F2(i,{primarySnapshotDate:n.to??o,currencyCode:n.currency});break;case"bank-recon-summary":n.bankAccount||(console.error(ne("--bank-account is required for bank-recon-summary")),process.exit(1)),s=await Q2(i,{bankAccountResourceId:n.bankAccount,primarySnapshotStartDate:n.from??`${o.slice(0,4)}-01-01`,primarySnapshotEndDate:n.to??o,currencyCode:n.currency});break;case"bank-recon-details":n.bankAccount||(console.error(ne("--bank-account is required for bank-recon-details")),process.exit(1)),s=await L2(i,{bankAccountResourceId:n.bankAccount,primarySnapshotStartDate:n.from??`${o.slice(0,4)}-01-01`,primarySnapshotEndDate:n.to??o,filter:{},currencyCode:n.currency});break;case"fa-summary":{let a=(n.groupBy??"ACCOUNT").toUpperCase();Pfe.includes(a)||(console.error(ne(`Invalid --group-by: ${a}`)),console.error(H(`Valid values: ${Pfe.join(", ")}`)),process.exit(1)),s=await M2(i,{primarySnapshotStartDate:n.from??`${o.slice(0,4)}-01-01`,primarySnapshotEndDate:n.to??o,groupBy:a,currencyCode:n.currency});break}case"fa-recon-summary":s=await P2(i,{primarySnapshotStartDate:n.from??`${o.slice(0,4)}-01-01`,primarySnapshotEndDate:n.to??o,currencyCode:n.currency});break;case"ar-report":s=await U2(i,{endDate:n.to??o});break;case"ledger-highlights":s=await $2(i);break}n.json||console.log(R(`${r} Report:
|
|
1052
1052
|
`)),console.log(JSON.stringify(s.data,null,2))})(n)))}Fe();ac();mn();xF();An();At();Ut();_t();dr();Mt();fr();var Jst=[{key:"resourceId",header:"ID",format:Be},{key:"name",header:"Name"},{key:"saleItemName",header:"Sale Name"},{key:"purchaseItemName",header:"Purchase Name"}];function Vst(t){let e=t.command("items").description("Manage items (products & services)");e.command("list").description("List items").option("--limit <n>","Max results (default 100)",de).option("--offset <n>","Page number offset (0-indexed)",Ye).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").addOption(new ri("--view <tier>","Payload tier: lean (summary rows) or full (default)").choices(["lean","full"])).option("--json","Output as JSON").action(F(async(r,n)=>{let i=await He(n,o=>_F(r,{...o,view:n.view}),{label:"Fetching items"});$e(i,Jst,n,"Items")})),Ve({parent:e,fields:mS,defaults:AS,fetcher:RE,columns:Jst,label:"Searching items"}),e.command("get <resourceId>").description("Get an item by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{let s=(await SE(i,r)).data;if(n.json)console.log(JSON.stringify(s,null,2));else{console.log(R("Name:"),s.internalName),console.log(R("Code:"),s.itemCode),console.log(R("ID:"),s.resourceId);let a=[s.appliesToSale&&"Sale",s.appliesToPurchase&&"Purchase"].filter(Boolean).join(", ");a&&console.log(R("Applies to:"),a)}})(n)),e.command("create").description("Create a new item").option("--jot <text>",we).option("--name <name>","Item name (internalName)").option("--code <code>","Item code").option("--sale","Applies to sales").option("--purchase","Applies to purchases").option("--sale-name <name>","Sale display name (defaults to --name)").option("--purchase-name <name>","Purchase display name (defaults to --name)").option("--sale-price <n>","Default sale price",ar).option("--purchase-price <n>","Default purchase price",ar).option("--sale-account <resourceId>","Sale account resourceId").option("--purchase-account <resourceId>","Purchase account resourceId").option("--sale-tax <resourceId>","Sale tax profile resourceId").option("--purchase-tax <resourceId>","Purchase tax profile resourceId").option("--custom-fields <json>",'Custom field values as JSON array: [{"customFieldName":"PO Number","actualValue":"PO-123"}]').option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=be(n),o=i?.itemCode??n.code;if(o){let a=await g1(r,o);if(a){n.json?console.log(JSON.stringify(a,null,2)):(console.log(Se(`Item with code "${o}" already exists`)),console.log(R("ID:"),a.resourceId));return}}let s;if(i)s=await kw(r,i);else{Le(n,[{flag:"--name",key:"name"},{flag:"--code",key:"code"}]);let a=n.customFields?un(n.customFields):void 0;s=await kw(r,{internalName:n.name,itemCode:n.code,appliesToSale:n.sale??void 0,appliesToPurchase:n.purchase??void 0,saleItemName:n.sale?n.saleName??n.name:void 0,purchaseItemName:n.purchase?n.purchaseName??n.name:void 0,salePrice:n.salePrice,purchasePrice:n.purchasePrice,saleAccountResourceId:n.saleAccount,purchaseAccountResourceId:n.purchaseAccount,saleTaxProfileResourceId:n.saleTax,purchaseTaxProfileResourceId:n.purchaseTax,customFields:a})}n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Y(`Item created: ${n.name}`)),console.log(R("ID:"),s.data.resourceId)),ve(r,"create_item",n,s.data)})),e.command("update <resourceId>").description("Update an item").option("--jot <text>",we).option("--name <name>","New name").option("--code <code>","New item code").option("--sale-price <n>","New sale price",ar).option("--purchase-price <n>","New purchase price",ar).option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full update body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{let o=be(n),s;o?s=o:(s={},n.name!==void 0&&(s.internalName=n.name),n.code!==void 0&&(s.itemCode=n.code),n.salePrice!==void 0&&(s.salePrice=n.salePrice),n.purchasePrice!==void 0&&(s.purchasePrice=n.purchasePrice),n.customFields&&(s.customFields=un(n.customFields)));let a=await DF(i,r,s);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(Y(`Item updated: ${a.data.internalName}`)),ve(i,"update_item",n,a.data)})(n)),e.command("delete <resourceId>").description("Delete an item").option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{await SF(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Item ${r} deleted.`)),ve(i,"delete_item",n,{resourceId:r})})(n)),e.command("bulk-upsert").description("Create or update items in bulk (max 500). Provide resourceId per item to update, omit to create.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=be(n);i||(console.error('Error: --input <file> is required (JSON with { "items": [...] })'),process.exit(1));let o=i.items??i;Array.isArray(o)||(console.error('Error: expected { "items": [...] } or a JSON array'),process.exit(1)),Nt(o,"items",500);let s=await RF(r,o);if(n.json)console.log(JSON.stringify(s.data,null,2));else{let a=s.data;console.log(Y(`Queued ${a.totalRecords??o.length} item(s) \u2014 job ${a.jobId}`)),console.log(` Poll: clio mcp-call search_background_jobs --args '{"filter":{"resourceId":{"eq":"${a.jobId}"}}}'`)}}))}Fe();zF();An();At();Ut();_t();dr();Mt();fr();var Wst=[{key:"resourceId",header:"ID",format:Be},{key:"name",header:"Name"}];function Zst(t){let e=t.command("tags").description("Manage tags");e.command("list").description("List tags").option("--limit <n>","Max results (default 100)",de).option("--offset <n>","Page number offset (0-indexed)",Ye).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(F(async(r,n)=>{let i=await He(n,o=>QE(r,o),{label:"Fetching tags"});$e(i,Wst,n,"Tags")})),e.command("get <resourceId>").description("Get a tag by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{let s=(await qF(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId))})(n)),Ve({parent:e,fields:qS,defaults:jS,fetcher:jF,columns:Wst,label:"Searching tags",positionalArg:"tagName",positionalFilter:r=>({tagName:{contains:r}})}),e.command("create").description("Create a new tag").option("--jot <text>",we).option("--name <name>","Tag name").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=be(n),o=i?.name??n.name;i||Le(n,[{flag:"--name",key:"name"}]);let s=await C1(r,o);if(s){n.json?console.log(JSON.stringify(s,null,2)):(console.log(ke(`Tag "${o}" already exists \u2014 reusing.`)),console.log(R("ID:"),s.resourceId));return}let a=i?await Pw(r,i):await Pw(r,{name:o});n.json?console.log(JSON.stringify(a.data,null,2)):(console.log(Y(`Tag created: ${o}`)),console.log(R("ID:"),a.data.resourceId)),ve(r,"create_tag",n,a.data)})),e.command("update <resourceId>").description("Rename a tag").option("--name <name>","New tag name").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{Le(n,[{flag:"--name",key:"name"}]);let o=await YF(i,r,{name:n.name});n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Tag renamed to "${n.name}".`)),console.log(R("ID:"),o.data.resourceId))})(n)),e.command("delete <resourceId>").description("Delete a tag").option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{await HF(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Tag ${r} deleted.`)),ve(i,"delete_tag",n,{resourceId:r})})(n))}Fe();Qw();At();Ut();_t();dr();Mt();fr();var Xst=[{key:"resourceId",header:"ID",format:Be},{key:"title",header:"Name"},{key:"status",header:"Status",format:t=>String(t)}];function Kst(t){let e=t.command("capsules").description("Manage capsules (transaction grouping)");e.command("list").description("List capsules").option("--limit <n>","Max results (default 100)",de).option("--offset <n>","Page number offset (0-indexed)",Ye).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(F(async(r,n)=>{let i=await He(n,o=>OF(r,o),{label:"Fetching capsules"});$e(i,Xst,n,"Capsules")})),Ve({parent:e,fields:zS,defaults:GS,fetcher:NE,columns:Xst,label:"Searching capsules",positionalArg:"title",positionalFilter:r=>({title:{contains:r}})}),e.command("get <resourceId>").description("Get a capsule by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{let s=(await Fw(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Title:"),s.title),s.description&&console.log(R("Description:"),s.description),console.log(R("ID:"),s.resourceId),s.type&&console.log(R("Type:"),s.type),s.capsuleType?.resourceId&&console.log(R("Type ID:"),s.capsuleType.resourceId))})(n)),e.command("create").description("Create a new capsule").option("--jot <text>",we).option("--title <title>","Capsule title").option("--type <resourceId>","Capsule type resourceId").option("--description <text>","Description").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=be(n),o;i?o=await hA(r,i):(Le(n,[{flag:"--title",key:"title"},{flag:"--type",key:"type"}]),o=await hA(r,{capsuleTypeResourceId:n.type,title:n.title,description:n.description})),n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Capsule created: ${n.title}`)),console.log(R("ID:"),o.data.resourceId)),ve(r,"create_capsule",n,o.data)})),e.command("update <resourceId>").description("Update a capsule").option("--jot <text>",we).option("--title <title>","New title").option("--description <text>","New description").option("--input <file>","Read full update body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{let o=be(n),s;o?s=o:(s={},n.title!==void 0&&(s.title=n.title),n.description!==void 0&&(s.description=n.description));let a=await FF(i,r,s);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(Y(`Capsule updated: ${a.data.title}`)),ve(i,"update_capsule",n,a.data)})(n)),e.command("delete <resourceId>").description("Delete a capsule").option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>F(async i=>{await QF(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Capsule ${r} deleted.`)),ve(i,"delete_capsule",n,{resourceId:r})})(n)),e.command("types").description("List capsule types").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=await kE(r);if(n.json)console.log(JSON.stringify(i.data,null,2));else{console.log(R(`Capsule Types (${i.data.length}):
|
|
1053
1053
|
`));for(let o of i.data)console.log(` ${Se(o.resourceId)} ${o.displayName}${o.description?H(` \u2014 ${o.description}`):""}`)}})),e.command("create-type").description("Create a new capsule type").option("--name <name>","Capsule type display name").option("--description <text>","Description").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(r,n)=>{let i=be(n),o;i?o=await Ow(r,i):(Le(n,[{flag:"--name",key:"name"}]),o=await Ow(r,{displayName:n.name,description:n.description})),n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Capsule type created: ${n.name}`)),console.log(R("ID:"),o.data.resourceId))})),e.command("move").description("Move transactions from one capsule to another").requiredOption("--transactions <ids>","Comma-separated transaction resourceIds to move").requiredOption("--to <capsuleResourceId>","Destination capsule resourceId").requiredOption("--from <capsuleResourceId>","Source capsule resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","JSON output").action(r=>F(async n=>{let i=r.transactions.split(",").map(o=>o.trim()).filter(Boolean);if(await LF(n,{businessTransactionResourceIds:i,newCapsuleResourceId:r.to,oldCapsuleResourceId:r.from}),r.json){console.log(JSON.stringify({moved:i.length,resourceIds:i,capsuleResourceId:r.to}));return}console.log(Y(`Moved ${i.length} transaction(s) to capsule ${r.to}.`))})(r))}Fe();GX();At();Ut();_t();dr();Mt();fr();var eat=[{key:"resourceId",header:"ID",format:Be},{key:"catalogName",header:"Name"},{key:"status",header:"Status"}];function tat(t){let e=be({input:t.input})??{};return{catalogName:t.name??e.catalogName,...e.description!==void 0||t.description!==void 0?{description:t.description??e.description}:{},...e.status!==void 0||t.status!==void 0?{status:t.status??e.status}:{},...e.contactGroupResourceIds?{contactGroupResourceIds:e.contactGroupResourceIds}:{},...e.items?{items:e.items}:{}}}function rat(t){let e=t.command("catalogs").description("Manage catalogs (product/service groupings)");e.command("list").description("List catalogs").option("--limit <n>","Max results (default 100)",de).option("--offset <n>","Page number offset (0-indexed)",Ye).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(F(async(r,n)=>{let i=await He(n,o=>q2(r,o),{label:"Fetching catalogs"});$e(i,eat,n,"Catalogs")})),Ve({parent:e,fields:vS,defaults:wS,fetcher:Y2,columns:eat,label:"Searching catalogs"}),e.command("get <resourceId>").description("Get a catalog (with its items)").option("--api-key <key>","API key (overrides stored/env)").option("--json","JSON output").action((r,n)=>F(async i=>{let o=await j2(i,r);console.log(JSON.stringify(o.data,null,2))})(n)),e.command("create").description("Create a catalog").requiredOption("--name <name>","Catalog name").option("--description <text>","Catalog description").option("--status <status>","Record status (ACTIVE / INACTIVE \u2014 defaults INACTIVE)").option("--input <file>","JSON file with the full catalog body; items[] is mandatory (a create with no items is rejected), contactGroupResourceIds[] is optional; flags override its scalars").option("--api-key <key>","API key (overrides stored/env)").option("--json","JSON output").action(r=>F(async n=>{let i=await H2(n,tat(r));if(r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(Y(`Catalog created: ${i.data.resourceId}`))})(r)),e.command("update <resourceId>").description("Update a catalog. FULL REPLACEMENT \u2014 pass --input with the complete body (get it first); omitting items / contactGroupResourceIds drops them").option("--name <name>","Catalog name").option("--description <text>","Catalog description").option("--status <status>","Record status (ACTIVE / INACTIVE)").option("--input <file>","JSON file with the full catalog body; flags override its scalars").option("--api-key <key>","API key (overrides stored/env)").option("--json","JSON output").action((r,n)=>F(async i=>{let o=await z2(i,r,tat(n));if(n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Y(`Catalog ${r} updated.`))})(n)),e.command("delete <resourceId>").description("Delete a catalog").option("--api-key <key>","API key (overrides stored/env)").option("--json","JSON output").action((r,n)=>F(async i=>{if(await G2(i,r),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Y(`Catalog ${r} deleted.`))})(n))}Fe();mn();ac();Mt();fr();eU();mm();At();_t();dr();Ut();var nat=[{key:"resourceId",header:"ID",format:Be},{key:"reference",header:"Reference",format:zn},{key:"status",header:"Status",format:t=>En(String(t))},{key:"totalAmount",header:"Amount",align:"right",format:bn},{key:"valueDate",header:"Date",format:t=>Pt(String(t))??"-"}];function iat(t){let e=t.command("customer-credit-notes").description("Manage customer credit notes");e.command("list").description("List customer credit notes").option("--limit <n>","Max results (default 100)",de).option("--offset <n>","Page number offset (0-indexed)",Ye).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").addOption(new ri("--view <tier>","Payload tier: lean (summary rows) or full (default)").choices(["lean","full"])).option("--json","Output as JSON").action(F(async(n,i)=>{let o=await He(i,s=>J2(n,{...s,view:i.view}),{label:"Fetching customer credit notes"});$e(o,nat,i,"Customer Credit Notes")})),e.command("get <resourceId>").description("Get a customer credit note by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let a=(await Ol(o,n)).data;if(i.json)console.log(JSON.stringify(a,null,2));else{if(console.log(R("Reference:"),a.reference||"(none)"),console.log(R("ID:"),a.resourceId),console.log(R("Status:"),a.status),console.log(R("Date:"),Pt(a.valueDate)),a.totalAmount!==void 0&&console.log(R("Total:"),a.totalAmount.toFixed(2)),a.lineItems?.length){console.log(R("Line Items:"));for(let c of a.lineItems){let u=c.quantity??1,d=c.unitPrice??0;console.log(` - ${c.name} qty: ${u} price: ${d.toFixed(2)}`)}}a.invoiceNotes&&console.log(R("Notes:"),a.invoiceNotes)}})(i)),Ve({parent:e,fields:$p,defaults:vC,fetcher:pR,columns:nat,label:"Searching customer credit notes"}),e.command("create").description("Create a customer credit note (saves as draft by default)").option("--jot <text>",we).option("--contact <resourceId>","Contact name or resourceId").option("--lines <json>","Line items as JSON array",$n).option("--date <YYYY-MM-DD>","Credit note date (valueDate)").option("--ref <reference>","Credit note reference/number").option("--notes <text>","Notes").option("--tag <tag>","Tag").option("--custom-fields <json>",'Custom field values as JSON array: [{"customFieldName":"PO Number","actualValue":"PO-123"}]').option(mc,Ac).option(gc,yc,Ko).option(Wi,Ts,Zi).option("--finalize","Finalize instead of saving as draft").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o=be(i),s;if(o)s=await hR(n,{...o,saveAsDraft:o.saveAsDraft??!i.finalize});else{Le(i,[{flag:"--contact",key:"contact"},{flag:"--lines",key:"lines"},{flag:"--date",key:"date"}]);let a=await Ci(n,i.contact,{silent:i.json});i.contact=a.resourceId;let c=Ec(i);bc(c,i);let u=i.customFields?un(i.customFields):void 0;s=await hR(n,{contactResourceId:i.contact,lineItems:i.lines,valueDate:i.date,reference:i.ref,invoiceNotes:i.notes,tags:i.tag?[i.tag]:void 0,customFields:u,currency:c,saveAsDraft:!i.finalize})}if(tp(s,i),i.json)console.log(JSON.stringify(s.appliedRate?{...s.data,appliedRate:s.appliedRate}:s.data,null,2));else{let a=i.finalize?"finalized":"draft";console.log(Y(`Customer credit note created (${a}): ${s.data.reference||s.data.resourceId}`)),console.log(R("ID:"),s.data.resourceId)}ve(n,"create_customer_credit_note",i,s.data)})),e.command("update <resourceId>").description("Update a draft customer credit note").option("--jot <text>",we).option("--ref <reference>","New reference").option("--date <YYYY-MM-DD>","New credit note date").option("--lines <json>","New line items as JSON array",$n).option("--notes <text>","New notes").option("--tag <tag>","New tag").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full update body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let s=be(i),a;s?a=s:(a={},i.ref!==void 0&&(a.reference=i.ref),i.date!==void 0&&(a.valueDate=i.date),i.lines!==void 0&&(a.lineItems=i.lines),i.notes!==void 0&&(a.notes=i.notes),i.tag!==void 0&&(a.tag=i.tag),i.customFields!==void 0&&(a.customFields=un(i.customFields)));let c=await V2(o,n,a);i.json?console.log(JSON.stringify(c.data,null,2)):console.log(Y(`Customer credit note updated: ${c.data.reference||c.data.resourceId}`)),ve(o,"update_customer_credit_note",i,c.data)})(i)),e.command("delete <resourceId>").description("Delete/void a customer credit note").option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{await W2(o,n),i.json?console.log(JSON.stringify({deleted:!0,resourceId:n})):console.log(Y(`Customer credit note ${n} deleted.`)),ve(o,"delete_customer_credit_note",i,{resourceId:n})})(i)),e.command("refund <resourceId>").description("Record a refund against a customer credit note").option("--jot <text>",we).option("--amount <n>","Refund amount (bank currency)",ar).option("--account <resourceId>","Refund account name or resourceId (any chart-of-accounts account)").option("--date <YYYY-MM-DD>","Refund date (valueDate)").option("--transaction-amount <n>","Transaction amount (CN currency, if different from bank)",ar).option("--method <method>","Refund method (BANK_TRANSFER, CASH, CHEQUE, etc.)","BANK_TRANSFER").option("--ref <reference>","Refund reference").option("--draft","Save as draft instead of finalizing").option("--input <file>","Read full refund body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let s=be(i),a;if(s)a=await AR(o,n,{...s,saveAsDraft:s.saveAsDraft??i.draft??!1});else{Le(i,[{flag:"--amount",key:"amount"},{flag:"--account",key:"account"},{flag:"--date",key:"date"}]);let u=new Set(["BANK_TRANSFER","CASH","CHEQUE"]).has(i.method)?"bank":"any",d=await oi(o,i.account,{filter:u,silent:i.json});i.account=d.resourceId,a=await AR(o,n,{paymentAmount:i.amount,transactionAmount:i.transactionAmount??i.amount,accountResourceId:i.account,valueDate:i.date,dueDate:i.date,paymentMethod:i.method,reference:i.ref??"",saveAsDraft:i.draft??!1})}i.json?console.log(JSON.stringify(a.data,null,2)):console.log(Y(`Refund recorded for customer credit note ${n}`)),ve(o,"create_customer_credit_note_refund",i,a.data)})(i)),e.command("refunds <resourceId>").description("List refunds for a customer credit note").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let a=(await Z2(o,n)).data;if(i.json)console.log(JSON.stringify(a,null,2));else{if(!a?.length){console.log("No refunds found.");return}console.log(R(`Refunds (${a.length}):
|
|
1054
1054
|
`));for(let c of a)console.log(` ${Se(c.resourceId)} ${c.reference||"(no ref)"} ${c.status} ${c.refundAmount} ${Pt(c.valueDate)}`)}})(i)),e.command("download <resourceId>").description("Download a customer credit note as PDF (returns URL)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>F(async o=>{let s=await X2(o,n);i.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Y("PDF download ready:")),console.log(H(s.data.fileUrl)))})(i));let r=e.command("draft").description("Manage draft customer credit notes (inspect, finalize, attachments)");r.command("list").description("List all draft customer credit notes with per-field validation status").option("--ids <ids>","Comma-separated IDs to inspect (instead of all drafts)").option("--max-rows <n>","Max drafts to fetch (default 1000)",de).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(F(async(n,i)=>{let o;if(i.ids){let c=i.ids.split(",").map(u=>u.trim()).filter(Boolean);o=await Promise.all(c.map(async u=>(await Ol(n,u)).data)),o=o.filter(u=>u.status==="DRAFT")}else o=(await He({all:!0,json:!0,maxRows:i.maxRows},({limit:u,offset:d})=>pR(n,{filter:{status:{eq:"DRAFT"}},limit:u,offset:d,sort:{sortBy:["valueDate"],order:"DESC"}}),{label:"Fetching draft customer credit notes"})).data;let s=5,a=[];for(let c=0;c<o.length;c+=s){let u=o.slice(c,c+s),d=await Promise.all(u.map(async f=>{let p=0;try{p=(await li(n,"customer-credit-notes",f.resourceId)).data.length}catch{}return $o(f,oo,p)}));a.push(...d)}if(i.json){let c=a.filter(u=>u.ready).length;console.log(JSON.stringify({totalDrafts:a.length,readyCount:c,needsAttentionCount:a.length-c,drafts:a},null,2))}else sd("Customer Credit Notes",a)})),ym(r.command("finalize <resourceId>").description("Fill missing fields and convert a draft customer credit note to APPROVED").option("--jot <text>",we)).action((n,i)=>F(async o=>{let s=be(i),c=(await Ol(o,n)).data;if(c.status!=="DRAFT"){let E=`Customer credit note ${n} is ${c.status}, not DRAFT.`;i.json?console.log(JSON.stringify({finalized:!1,error:E})):console.error(ne(E)),process.exit(1)}let u={...i};if(i.contact){let E=await Ci(o,i.contact,{silent:i.json});u.contact=E.resourceId}if(i.account){let E=await oi(o,i.account,{filter:"line-item",silent:i.json});u.account=E.resourceId}if(i.taxProfile){let E=await xu(o,i.taxProfile,{silent:i.json});u.taxProfile=E.resourceId}let d;s?d=s:d=td(c,u);let f=Object.keys(d),p={...c,...d};d.lineItems&&(p.lineItems=d.lineItems);let{missingFields:h,missingCount:m,ready:A}=Ys(p,oo);if(!s){let E={reference:p.reference||void 0,contactResourceId:p.contactResourceId,valueDate:Pt(d.valueDate)||Pt(c.valueDate)},I=d.lineItems??c.lineItems??[];E.lineItems=I.map(v=>Wc(v)),(d.isTaxVatApplicable!=null||c.isTaxVATApplicable!=null)&&(E.isTaxVATApplicable=d.isTaxVatApplicable??c.isTaxVATApplicable),(d.taxInclusion!=null||c.taxInclusion!=null)&&(E.taxInclusion=d.taxInclusion??c.taxInclusion),d.notes&&(E.notes=d.notes),d.tag&&(E.tag=d.tag),d=E}if(i.dryRun){let E=Co(p,oo);if(i.json)console.log(JSON.stringify({finalized:!1,dryRun:!0,resourceId:n,reference:p.reference||null,ready:A,missingCount:m,missingFields:h,validation:E},null,2));else if(A)console.log(Y(`\u2713 ${p.reference||n} is ready to finalize.`));else{console.error(ke(`\u2717 ${p.reference||n} \u2014 ${m} issue${m>1?"s":""} remaining:`));for(let I of h){let v=oo.find(x=>I===x.field||I.endsWith(`.${x.field}`));console.log(` ${I}: ${ne("MISSING")} \u2014 ${v?.hint??""}`)}}return}if(!A){let E=Co(p,oo);if(i.json)console.log(JSON.stringify({finalized:!1,resourceId:n,reference:p.reference||null,ready:!1,missingCount:m,missingFields:h,validation:E},null,2));else{console.error(ne(`
|