jaz-clio 9.8.4 → 9.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +1 -1
  2. package/assets/skills/api/SKILL.md +31 -433
  3. package/assets/skills/api/references/dependencies.md +1 -2
  4. package/assets/skills/api/references/errors.md +7 -10
  5. package/assets/skills/api/references/feature-glossary.md +2 -2
  6. package/assets/skills/api/references/field-map.md +3 -1
  7. package/assets/skills/api/references/orders.md +2 -2
  8. package/assets/skills/api/references/rules-bulk-recon-drafts.md +108 -0
  9. package/assets/skills/api/references/rules-entities-quick-fix.md +108 -0
  10. package/assets/skills/api/references/rules-fundamentals.md +131 -0
  11. package/assets/skills/api/references/rules-search-magic-shapes.md +108 -0
  12. package/assets/skills/cli/SKILL.md +5 -3
  13. package/assets/skills/cli/references/agent-gotchas.md +1 -1
  14. package/assets/skills/cli/references/common-workflows.md +1 -1
  15. package/assets/skills/conversion/SKILL.md +5 -3
  16. package/assets/skills/jaz-api-reference/SKILL.md +51 -0
  17. package/assets/skills/jaz-api-reference/references/endpoints-assets-payroll.md +367 -0
  18. package/assets/skills/jaz-api-reference/references/endpoints-banking-magic.md +500 -0
  19. package/assets/skills/jaz-api-reference/references/endpoints-bulk-edits.md +362 -0
  20. package/assets/skills/jaz-api-reference/references/endpoints-master-data.md +776 -0
  21. package/assets/skills/jaz-api-reference/references/endpoints-schedules-reports.md +442 -0
  22. package/assets/skills/jaz-api-reference/references/endpoints-transactions.md +831 -0
  23. package/assets/skills/jaz-api-reference/references/endpoints.md +164 -0
  24. package/assets/skills/{api → jaz-api-reference}/references/full-api-surface.md +13 -111
  25. package/assets/skills/{api → jaz-api-reference}/references/search-enums.md +1 -1
  26. package/assets/skills/{api → jaz-api-reference}/references/search-reference.md +1 -9
  27. package/assets/skills/jaz-kit/SKILL.md +2 -1
  28. package/assets/skills/jaz-pseudo-sql/SKILL.md +2 -1
  29. package/assets/skills/jobs/SKILL.md +2 -1
  30. package/assets/skills/jobs/references/building-blocks.md +1 -1
  31. package/assets/skills/jobs/references/credit-control.md +1 -1
  32. package/assets/skills/transaction-recipes/SKILL.md +4 -3
  33. package/cli.mjs +444 -442
  34. package/package.json +1 -1
  35. package/assets/skills/api/references/endpoints.md +0 -3407
  36. /package/assets/skills/{api → jaz-api-reference}/references/search-syntax.md +0 -0
@@ -128,10 +128,9 @@ Pre-existing accounts may have different codes than your templates:
128
128
  - "Cost of Goods Sold" = code 310 in the API, code 5000 in template
129
129
  - "Accounts Receivable" can have `code: null` in the API
130
130
 
131
- **Always map by NAME, not code**. When building lookup maps, key by both:
131
+ **Always map by NAME, not code**. Key lookup maps by name only; a template code can belong to a different account in the organization:
132
132
  ```javascript
133
133
  coaIds[acct.name] = acct.resourceId;
134
- if (acct.code) coaIds[acct.code] = acct.resourceId;
135
134
  ```
136
135
 
137
136
  Resource IDs are the universal identifier, not codes.
@@ -49,7 +49,7 @@ Or call `list_account_classifications`, authoritative for that organisation.
49
49
 
50
50
  ### "ORGANIZATION_CHART_OF_ACCOUNT_DUPLICATED" (400)
51
51
  **Cause**: Sending an account `name` that already exists in the org.
52
- **Fix**: Fetch existing accounts first (`GET /chart-of-accounts`), skip names already present. Upsert matches by name; if you want to update an existing account, the name match handles it automatically.
52
+ **Fix**: Fetch existing accounts first (`GET /chart-of-accounts`), skip names already present. A name match never updates: to change an existing account, send its `resourceId` in the bulk upsert row, or use `PUT /chart-of-accounts/:resourceId`. In `chart-of-accounts/bulk-upsert` this error is per row, in `failedRows[]`, and the other rows still commit (rule 141).
53
53
 
54
54
  ### Wrong wrapper field
55
55
  **Cause**: Using `{ chartOfAccounts: [...] }` instead of `{ accounts: [...] }`.
@@ -272,9 +272,8 @@ hyphenated `/organization-currencies/...` rate paths still resolve but are
272
272
  - "Accounts Receivable" = `code: null` in the API
273
273
  **Fix**: Map template accounts to resource IDs via **name matching**, not code matching. Resource IDs are the universal identifier.
274
274
  ```typescript
275
- // Build map keyed by BOTH name and code:
275
+ // Key the map by name only: a template code can belong to a different account here.
276
276
  ctx.coaIds[acct.name] = acct.resourceId;
277
- if (acct.code) ctx.coaIds[acct.code] = acct.resourceId;
278
277
  ```
279
278
 
280
279
  ---
@@ -436,10 +435,9 @@ Same pattern for purchase side: `appliesToPurchase: true` + `purchaseItemName` r
436
435
 
437
436
  ### "CoA ref 'XXXX' not found"
438
437
  **Cause**: Template references CoA account by code (e.g., `"4000"`) but the lookup map only has entries keyed by name.
439
- **Fix**: When building CoA ID maps, key by BOTH `name` AND `code`:
438
+ **Fix**: Reference accounts in the template by name (or resourceId), and key the CoA ID map by `name` only. Do not add code-keyed entries: a template code can belong to a different account in this organization, so the lookup resolves to the wrong ledger account.
440
439
  ```typescript
441
440
  ctx.coaIds[acct.name] = acct.resourceId;
442
- if (acct.code) ctx.coaIds[acct.code] = acct.resourceId;
443
441
  ```
444
442
 
445
443
  ---
@@ -546,9 +544,8 @@ if (acct.code) ctx.coaIds[acct.code] = acct.resourceId;
546
544
 
547
545
  ## Contact Group PUT Errors
548
546
 
549
- ### 500 Internal Server Error on PUT (known bug)
550
- **Cause**: `PUT /contact-groups/:id` returns 500 regardless of payload structure.
551
- **Workaround**: Cannot update contact groups via API. Delete and recreate instead.
547
+ ### PUT updates in place (no longer a 500)
548
+ `PUT /contact-groups/:id` used to answer 500. Re-probed live 2026-09-02, it answered 200 and applied the change (rule 46). Update the group with PUT; deleting and recreating it gives it a new `resourceId`.
552
549
 
553
550
  ---
554
551
 
@@ -611,7 +608,7 @@ transaction on it.
611
608
  **The flag is set with `PUT /deposit-accounts`** and listed with
612
609
  `GET /deposit-accounts?depositContactType=CUSTOMER|SUPPLIER`. `depositContactType` is not on any
613
610
  chart-of-accounts model, so `POST /chart-of-accounts` cannot create a deposit account: create the
614
- account, then flag it. Full model: SKILL.md Rule 47a, `endpoints.md` → Deposits, `feature-glossary.md` → Deposits.
611
+ account, then flag it. Full model: SKILL.md Rule 47a, jaz-api-reference `endpoints-banking-magic.md` → Deposits, `feature-glossary.md` → Deposits.
615
612
 
616
613
  ### 422 on `PUT /deposit-accounts`
617
614
  The request is applied as one change, so one bad entry refuses all of them and the error names
@@ -632,7 +629,7 @@ asset). A missing `depositContactType` key, or a flag without `restrictPaymentOv
632
629
 
633
630
  ### 404: Endpoint does not exist
634
631
  **Cause**: `POST /inventory/adjustments` returns 404. Also tested: `/inventory-adjustments`, `/inventory-items/:id/adjustments`, `/items/:id/inventory-adjustments`; all 404. None of the four is registered; there is no stock-adjustment write path at any spelling.
635
- **Note**: The whole inventory surface is `POST|GET /inventory-items`, `GET /inventory-item-balance/:resourceId` and `GET /inventory-balances/:balanceStatus` (balances across items: `ALL`, `AVAILABLE` or `FULLY_DRAWN`, Rule 97). Inventory items can be created, and stock moves as a side effect of a transaction carrying the item, but quantity cannot be written directly. See `endpoints.md` → Inventory.
632
+ **Note**: The whole inventory surface is `POST|GET /inventory-items`, `GET /inventory-item-balance/:resourceId` and `GET /inventory-balances/:balanceStatus` (balances across items: `ALL`, `AVAILABLE` or `FULLY_DRAWN`, Rule 97). Inventory items can be created, and stock moves as a side effect of a transaction carrying the item, but quantity cannot be written directly. See jaz-api-reference `endpoints-master-data.md` → Inventory.
636
633
 
637
634
  ---
638
635
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Business context for Jaz platform features: what they are, when to use them, and which API endpoints correspond. This supplements the API-focused reference files with product knowledge that helps AI agents understand the *purpose* behind API calls.
4
4
 
5
- For full help center content split by section, see [help-center-mirror/](../help-center-mirror/) or [help.jaz.ai](https://help.jaz.ai). For the complete endpoint catalog (80+), see [full-api-surface.md](./full-api-surface.md).
5
+ For full help center content, see [help.jaz.ai](https://help.jaz.ai) or search it with `clio help-center` (the `search_help_center` tool). For the complete endpoint catalog (80+), see `full-api-surface.md` in the jaz-api-reference skill.
6
6
 
7
7
  ---
8
8
 
@@ -181,7 +181,7 @@ Statement amounts are recorded in the bank account's currency, no auto-conversio
181
181
 
182
182
  Workflow for draft invoices and bills requiring admin sign-off before activation. Three user roles: Admins (approve + create active), Preparers (submit drafts for approval), Members (submit own drafts only). Status progression: Draft → For Approval → Approved (active). Approval PDFs capture Submitted By / Approved By audit trail.
183
183
 
184
- **API**: `POST /{invoices|bills|customer-credit-notes|supplier-credit-notes}/:id/approve` and `/bulk-approve` (irreversible: posts the ledger), `POST /{entity}/:id/request-changes` (endpoints.md sections 19c, 19d)
184
+ **API**: `POST /{invoices|bills|customer-credit-notes|supplier-credit-notes}/:id/approve` and `/bulk-approve` (irreversible: posts the ledger), `POST /{entity}/:id/request-changes` (jaz-api-reference `endpoints-transactions.md` sections 19c, 19d)
185
185
 
186
186
  ---
187
187
 
@@ -74,6 +74,8 @@ These aliases are applied by middleware on POST/PUT endpoints. The alias is only
74
74
  | `accountType` | `classificationType` | Code-level alias | POST/PUT: chart-of-accounts, bulk-upsert |
75
75
  | `currencyCode` | `currency` | Code-level alias | POST: chart-of-accounts bulk-upsert |
76
76
 
77
+ Aliases apply only to POST/PUT request bodies. Search filter fields use their canonical names (e.g., `tagName` not `name` in `POST /tags/search`).
78
+
77
79
  ---
78
80
 
79
81
  ## Organization & Auth
@@ -712,4 +714,4 @@ Battle-tested patterns from production Jaz API clients:
712
714
 
713
715
  ---
714
716
 
715
- *Hand-maintained and not regenerated; nothing detects it going stale; provenance and precedence rules: `search-enums.md` → Provenance and staleness. Last updated: 2026-04-09. Added: Background Jobs (resourceId vs jobId critical trap, startedAt broken), Export Records (fileUrl, filterDescription, previewRows keying). Previous: 2026-03-13. Payment record fields, scheduler field asymmetry, nano-classifier fields.*
717
+ *Hand-maintained and not regenerated; nothing detects it going stale; provenance and precedence rules: jaz-api-reference `search-enums.md` → Provenance and staleness. Last updated: 2026-04-09. Added: Background Jobs (resourceId vs jobId critical trap, startedAt broken), Export Records (fileUrl, filterDescription, previewRows keying). Previous: 2026-03-13. Payment record fields, scheduler field asymmetry, nano-classifier fields.*
@@ -81,7 +81,7 @@ To change lines:
81
81
 
82
82
  The update tools (and `clio … update --lines`) pre-flight this against the stored document: lines with no `resourceId` at all on a document that already has lines are refused locally (nothing is written) unless `appendLines: true` (CLI `--append-lines`) says adding is the intent; naming some stored lines but not all is refused locally with the missing ids.
83
83
 
84
- To change a few fields on some lines without resending the document, use `quick_fix_line_items` (`clio quick-fix <entity> --line-items`) with entity `sale-orders`, `sale-quotes`, `purchase-orders` or `purchase-requests`: `{ lineItemResourceIds, attributes }`, only the fields sent change, and the lines not named are untouched. Attributes: name, quantity, unit, unitPrice, discount, itemResourceId, organizationAccountResourceId, taxProfileResourceId, classifierConfig, plus withholdingTax on purchase orders and requests. `discount` and `withholdingTax` take the quick fix shapes, not the ones this page's create/update use (`discount: { rateType, rateValue }`, `withholdingTax: { code, rate, rateType, type }`): see endpoints.md section 17. Orders have line-item quick fix only: `quick_fix_transactions` refuses them.
84
+ To change a few fields on some lines without resending the document, use `quick_fix_line_items` (`clio quick-fix <entity> --line-items`) with entity `sale-orders`, `sale-quotes`, `purchase-orders` or `purchase-requests`: `{ lineItemResourceIds, attributes }`, only the fields sent change, and the lines not named are untouched. Attributes: name, quantity, unit, unitPrice, discount, itemResourceId, organizationAccountResourceId, taxProfileResourceId, classifierConfig, plus withholdingTax on purchase orders and requests. `discount` and `withholdingTax` take the quick fix shapes, not the ones this page's create/update use (`discount: { rateType, rateValue }`, `withholdingTax: { code, rate, rateType, type }`): see jaz-api-reference `endpoints-bulk-edits.md` section 17. Orders have line-item quick fix only: `quick_fix_transactions` refuses them.
85
85
 
86
86
  ## Delete vs Void
87
87
 
@@ -129,7 +129,7 @@ Purchase side is symmetric: `create -t request --finalize` (→ ACTIVE) → (opt
129
129
 
130
130
  ## Search
131
131
 
132
- `search_sale_orders` / `search_purchase_orders` take `documentType` plus the standard filter set (reference, status, contact, contactResourceId, currencyCode, date range, amount range, tag). The `status` enum is the per-side union (sales: DRAFT/PENDING/CREATED/ACCEPTED/CONFIRMED/VOID; purchases: DRAFT/PENDING/ACTIVE/ACCEPTED/CONFIRMED/VOID). For advanced/nested queries, pass the raw `filter` object. See `search-reference.md` §24-25 and `search-enums.md` §25-26.
132
+ `search_sale_orders` / `search_purchase_orders` take `documentType` plus the standard filter set (reference, status, contact, contactResourceId, currencyCode, date range, amount range, tag). The `status` enum is the per-side union (sales: DRAFT/PENDING/CREATED/ACCEPTED/CONFIRMED/VOID; purchases: DRAFT/PENDING/ACTIVE/ACCEPTED/CONFIRMED/VOID). For advanced/nested queries, pass the raw `filter` object. See jaz-api-reference `search-reference.md` §24-25 and `search-enums.md` §25-26.
133
133
 
134
134
  **Linked documents.** Each search reads the documents created from another by their link: `search_sale_orders` `saleQuoteId` (the orders made from a quote, documentType `SALE_ORDER`), `search_purchase_orders` `purchaseRequestId` (the orders made from a request, documentType `PURCHASE_ORDER`), `search_invoices` `saleOrderId` (the invoices made from a sales order) and `search_bills` `purchaseOrderId` (the bills made from a purchase order). Asked what covers or fulfils a document, read its linked documents first, and match look-alikes (contact, amount, date) only for documents with no link.
135
135
 
@@ -0,0 +1,108 @@
1
+ # Jaz API Rules 118-161: Bulk Upserts, Reconciliation, Drafts Lifecycle, Pseudo-SQL, Payment Adjustments, Report Templates
2
+
3
+ Part of the jaz-api skill. [SKILL.md](../SKILL.md) holds the reading order and the index of all four rule files. Rule numbers are stable: tool descriptions, `errors.md` and other skills cite them by number, and a missing number is a retired rule.
4
+
5
+ ### Bulk Upserts (transactions)
6
+
7
+ 118. **8 bulk-upsert endpoints for transactions**: `POST /api/v1/{invoices,bills,customer-credit-notes,supplier-credit-notes,journals,fixed-assets}/bulk-upsert` plus line-item variants for invoices and bills (`/invoices/line-items/bulk-upsert`, `/bills/line-items/bulk-upsert`). Max **500 rows per call**. All async: return `{data: {jobId, subscriptionFBPath, status, totalRecords}}`. Poll `search_background_jobs` with `filter: {resourceId: {eq: jobId}}` until terminal status. **Natural keys**: invoices = `invoiceReference`, bills = `billReference`, credit notes = `creditNoteReference`, **journals = `journalReference` (NOT `reference`, asymmetric vs other entities)**, fixed assets = `reference`. **`currencyCode` is REQUIRED** on every transaction row (invoices, bills, CCN, SCN); missing it returns errorCode `IMPORT_CURRENCY_REQUIRED`. **Journals are the exception**: the bulk journal row has no currency field and any `currencyCode` sent is discarded, and the public request model exposes no per-leg currency field either. **Journals legs use `journalEntries[]`** (NOT `entries[]`; different from `journals create` which uses entries), and **a journal leg is `organizationAccountResourceId` + exactly one of `debitAmount`/`creditAmount`**, NOT the `accountResourceId`+`amount`+`type` shape `journals create` takes, and omit the unused side rather than sending 0. **On the six TRANSACTION bulk tools the natural key is the only upsert key; `resourceId` does not override it.** Probed live 2026-09-02 on invoices, bills, customer credit notes and invoice line items: sending an existing record's `resourceId` together with a DIFFERENT natural key left the original untouched and created a second record. (Supplier credit notes and bill line items were not probed; they were changed on their twin's evidence plus spec absence.) `resourceId` has been removed from all six. It remains valid, and spec-backed, on `bulk_upsert_contacts`, `bulk_upsert_items` and `bulk_upsert_chart_of_accounts`; see rule 137. Journals upsert by `journalReference` only. **Currency and due date split by shape, so pick the tool by what you need:** the FLAT pair (`bulk_upsert_invoices` / `bulk_upsert_bills`) IGNORES both: a row sent `currencyCode: EUR` against a USD-base org stored USD, omitting `currencyCode` entirely still succeeds, and `dueDate` comes back equal to `valueDate` with `terms: 0`. The NESTED pair (`bulk_upsert_invoice_line_items` / `bulk_upsert_bill_line_items`) honours `dueDate` (it is in fact REQUIRED there; omitting it fails the row with `DUE_DATE_REQUIRED`) and requires `currencyCode`. **So a bulk import that needs a real due date or a non-base currency must use the NESTED tools.** `tags` is on no transaction bulk wire definition and has been removed from these tools. `rowIndex` is optional caller-supplied for error reporting; on journals it sits on the leg, not the row.
8
+
9
+ 118b. **Credit-note rows carry two extra requirements** (customer and supplier alike, and nothing here applies to journals). The tools speak `currencyCode`, but these two contracts (like the two line-item ones) name the wire field `transactionCurrency`; the client renames it for you via `toWireCurrencyRow`. They also require **`transactionRateType`** (`ORGANIZATION_RATE` | `TRANSACTION_RATE`): omit it and the row fails `IMPORT_TRANSACTION_RATE_TYPE_INVALID` even when the currency is right. `TRANSACTION_RATE` reads `rateFunctionToSource` (1 base unit = N transaction currency); `ORGANIZATION_RATE` uses the org rate. Neither endpoint carries `tags` on its wire definition, so do not report tags "applied" through this route. (The two line-item endpoints were probed the same way on 2026-09-02 and do NOT need `transactionRateType`.)
10
+
11
+ 119. **PARTIAL_SUCCESS handling**: When `search_background_jobs` returns `PARTIAL_SUCCESS` for a bulk-upsert job, the per-row failures are in `data[0].errorDetails` on the SAME response (an array of per-row error objects). Top-level counts (`processedCount`, `failedCount`, `totalRecords`) tell you *how many* failed; `errorDetails` tells you *which rows and why*. Don't pretend the operation succeeded; surface the failed rows to the user. The rule of thumb: poll with `search_background_jobs` filtered by `resourceId: { eq: jobId }`, then read `data[0].errorDetails` for terminal states.
12
+
13
+ 120. **`dateFormat` field was removed from bulk-upsert**: the API now requires ISO 8601 (`YYYY-MM-DD`) for ALL date fields on `POST /{invoices,bills,journals}/bulk-upsert`. Sending `dateFormat: "MM/DD/YYYY"` (or any other value) is silently ignored. Reject any datetime strings (anything with `T` or `:`) client-side before submitting.
14
+
15
+ 121. **Intra-batch reference dedup is MERGE, not REJECT**: Two rows in the same bulk-upsert call sharing the same natural key (`invoiceReference`/`billReference`/etc.) are MERGED by the API (last row wins). If the user wants strict-uniqueness, dedup client-side first.
16
+
17
+ 122. **Fixed asset bulk upsert: dates are EPOCH MILLISECONDS**. The bulk-upsert REQUEST takes `purchaseDate` and `depreciationStartDate` as **epoch milliseconds** (numbers), unlike every other bulk-upsert (which takes `YYYY-MM-DD`). A date string returns a generic 400 "Invalid request body" with no detail. There is no `valueDate`, `cost`, `usefulLifeMonths`, `currencyCode`, `tags` or `resourceId` field on this endpoint: those are silently discarded; the wire names are `purchaseDate`, `purchaseAmount` and `effectiveLife`, and the natural key is `reference`. Required: `reference`, `registrationType` ("NEW" | "TRANSFER"). `NEW` also requires `purchaseBusinessTransactionType` ("PURCHASE" | "SALE" | "JOURNAL_MANUAL") + `purchaseBusinessTransactionResourceId` (the purchase LINE ITEM, not the bill/journal id); `TRANSFER` instead takes `accumulatedDepreciationAtTransferDate` + `bookValueAtTransferDate`. Recommended: `typeCode` (e.g. `FURNITURE_AND_FIXTURE`), `typeName`, `category` ("TANGIBLE" | "INTANGIBLE"), `purchaseAmount`, `purchaseDate`, `effectiveLife`, `depreciationMethod` (`STRAIGHT_LINE` | `NO_DEPRECIATION`), `purchaseAssetAccountResourceId` (UUIDv4), `depreciationExpenseAccountResourceId` (UUIDv4), `accumulatedDepreciationAccountResourceId`. Omit `depreciationStartDate` to default it to `purchaseDate`.
18
+
19
+ ### Reconciliation actions (write-side)
20
+
21
+ 123. **13 reconciliation action endpoints under `/api/v1/reconciliations/*`**. These *commit* a reconciliation decision against a bank statement entry, distinct from `view_auto_reconciliation` (which queries `/search-magic-reconciliation` for *suggestions*):
22
+ - **Async (jobId):** `quick_reconcile` (bulk match entries to journals, max 500), `apply_bank_rule` (bulk apply a rule to entries, max 500). Poll `search_background_jobs` filtered by `resourceId`; on `PARTIAL_SUCCESS` read `data[0].errorDetails` for per-row failures.
23
+ - **Sync (single bank entry):** `reconcile_direct_cash_entry`, `reconcile_cash_journal`, `reconcile_manual_journal`, `reconcile_cash_transfer`, `reconcile_invoice_receipt`, `reconcile_bill_receipt`, `reconcile_with_payments` (match EXISTING; see Rule 158), `reconcile_learned_prediction`. Each returns `{bankStatementEntryResourceId, status, reference, valueDate}`.
24
+ - **Sync, several entries to one document:** `reconcile_match_to_transaction` (1-100 entries against ONE open invoice/bill/credit note, all or nothing; see Rule 158) returns `{reconciled[], paymentResourceIds[], businessTransactionResourceId, businessTransactionType, businessTransactionStatus, balanceAmount}`.
25
+ - **Sync bulk:** `reconcile_magic_match` (bulk-accept MAGIC_MATCH and MAGIC_RECONCILE_WITH_CASH_IN_OUT suggestions, max 500) returns `{reconciled[], failed[]}`; `undo_reconciliations` (unlink, 1-500) returns `{resetReconciliationResponse[], linkedRecords[]}`; see Rule 125.
26
+
27
+ 124. **Recon prefill from the bank statement entry**: when caller omits `valueDate`, `dueDate`, payment `amount`, or direction (cash-in vs cash-out), the API fills these from the bank entry. Best-effort: a missing entry lookup logs a warning and forwards the payload as-is. Caller can always override by passing the field explicitly.
28
+
29
+ 125. **The 6 sync recon endpoints are NOT idempotent**: calling twice on the same `bankStatementEntryResourceId` creates duplicate journals. Before retrying, confirm the entry's reconciled state via `view_auto_reconciliation` or `search_bank_records` filtered by `status`. Concurrent calls on the same entry race: last-write-wins. **`undo_reconciliations` is the reverse and behaves differently**: it UNLINKS but does NOT delete the record that was matched, so undoing any of the 6 CREATE endpoints (`direct_cash_entry`, `cash_journal`, `manual_journal`, `cash_transfer`, `invoice_receipt`, `bill_receipt`) leaves that record on the books against an unmatched bank line, a discrepancy the undo introduced. Delete it via `linkedRecords[]` (captured BEFORE the unlink, since the unlink is what makes it unfindable by bank entry): cash in/out/transfer by `parentEntityResourceId`, everything else by `businessTransactionResourceId`. Never just re-reconcile after undoing; that creates a SECOND record. Undo never double-applies (a repeat returns per-entry `FAILED`/`INVALID_BANK_STATEMENT_ENTRY_STATUS`), and unresolved ids are OMITTED from the response, so compare returned ids against what you sent.
30
+
31
+ 126. **Sync recon → AR/AP via `invoice_receipt` / `bill_receipt`**: these endpoints CREATE a transaction (invoice for AR, bill for AP) and immediately reconcile it to the bank entry. The two endpoints stay separate (not unified) because the invoice side carries `billTo` / `billFrom` that bills don't have. Cash-in vs cash-out, by contrast, IS unified into `reconcile_direct_cash_entry`; direction is encoded in the bank entry sign.
32
+
33
+ 127. **Cash transfer `amount` is conditional**: for `reconcile_cash_transfer`, `amount` is required only when the counterparty account is in a non-functional currency. Same-currency transfers omit it; the API derives the amount from the bank entry.
34
+
35
+ ### Drafts lifecycle (server-side, BULK-friendly)
36
+
37
+ 128. **3 BULK-action server-side draft lifecycle endpoints under `/api/v1/drafts/*`**, distinct from the local-only `src/core/drafts/` payload helpers. All three accept a single mixed-type batch (max 500 items per call); there are NO per-entity variants. ONE call covers any combination of invoices, bills, customer credit notes, and supplier credit notes.
38
+ - `POST /api/v1/drafts/validate` (sync) → `validate_drafts`. Returns per-item validation errors + display data inline. No state change. Use to pre-flight before convert/submit.
39
+ - `POST /api/v1/drafts/convert-to-active` (async, jobId) → `convert_drafts_to_active`. Promotes drafts to ACTIVE. Poll `search_background_jobs` filtered by `resourceId`; on PARTIAL_SUCCESS read `data[0].errorDetails`.
40
+ - `POST /api/v1/drafts/submit-for-approval` (async, jobId) → `submit_drafts_for_approval`. Routes drafts into the approval workflow.
41
+
42
+ 129. **Drafts lifecycle request shape (mix-friendly)**. All 3 endpoints accept the same body: `{ items: [{btResourceId, btType}] }` with `btType ∈ {SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE}`. **Max 500 items per call. ONE batch can mix any combination of types**: no need to group by btType client-side, no need to make multiple calls per entity type. **Mapping**: `SALE` → invoice, `PURCHASE` → bill, `SALE_CREDIT_NOTE` → customer credit note, `PURCHASE_CREDIT_NOTE` → supplier credit note. Journals are NOT in the enum: they have no approval state (ACTIVE | VOID | DRAFT), so they never entered this lifecycle. Promote a DRAFT journal with `bulk_update_journals` (`saveAsDraft: false`) or `update_journal`; that IS the supported path, not a workaround.
43
+
44
+ 130. **Drafts lifecycle is NOT idempotent**: a second `convert_drafts_to_active` on already-ACTIVE drafts returns 422; a second `submit_drafts_for_approval` on drafts with an in-flight approval returns 422. Filter the draft list by `status: DRAFT` before submitting (the entity-specific search tools, `search_invoices`, `search_bills`, etc., accept `status` filters). `validate_drafts` IS safe to call repeatedly (read-only, no state change).
45
+
46
+ 131. **Drafts must be COMPLETE before convert/submit**: `convert_drafts_to_active` and `submit_drafts_for_approval` reject INCOMPLETE drafts (drafts missing required fields like `accountResourceId` on every line item, contactResourceId, etc.) with 422. The `bills draft list` / `invoices draft list` etc. commands return per-draft `ready: bool` + `missingCount` + `missingFields[]`; call `validate_drafts` first to surface missing fields per row, fix client-side, then convert/submit.
47
+
48
+ ### Reconciliation and bulk-upsert details
49
+
50
+ 132. **Manual-journal recon: caller provides ONLY the offset side(s)**: `reconcile_manual_journal` AUTO-ADDS the bank-side leg from the bank statement entry. If the caller sends both debit AND credit legs covering the bank side, the API doubles-up after auto-add → 422 "sum of debit and credit amounts are not equal in a journal". Send only the offset journal entries (the non-bank side); the API balances them against the bank entry.
51
+
52
+ 133. **`reconcile_invoice_receipt` and `reconcile_bill_receipt` gate on `paymentDirection`, not BSE entry type**: error code `INVALID_BUSINESS_TRANSACTION_TYPE_ERROR` ("Invalid business transaction type", 422) is misleadingly named. The actual gate is the BSE's `paymentDirection`. **`invoice_receipt` requires `PAYIN`** (AR, money in, positive amount in `bank add-records`, producing `credit_amount > 0`). **`bill_receipt` requires `PAYOUT`** (AP, money out, NEGATIVE amount, producing `debit_amount > 0`). `bank add-records` produces both directions based on amount sign. Statement-imported BSEs (`bank import`) also work; direction is set from the CSV. No need for the async magic-OCR `bank import` path; sync `bank add-records` with the correct sign is sufficient.
53
+
54
+ 134. **Bulk-upsert FLAT vs NESTED variants**: for invoices and bills, there are TWO bulk-upsert endpoints. **FLAT** (`bulk_upsert_invoices` / `bulk_upsert_bills`): one line per row, set at row level via `itemDescription` + `totalAmount` + `invoiceAccountResourceId` (or `billAccountResourceId`). **NESTED** (`bulk_upsert_invoice_line_items` / `bulk_upsert_bill_line_items`): multi-line per row via nested `lineItems[]`, each with `itemDescription` + `quantity` + `unitPrice` + `accountResourceId`. Use FLAT when one line per transaction is fine (CSV import, simple bills); use NESTED when each transaction needs multiple lines. Sending `lineItems[]` to the FLAT endpoint silently ignores them and creates a $0 invoice.
55
+
56
+ 135. **Reconciliation `lineItems[]` use a DIFFERENT field naming convention**: for `reconcile_invoice_receipt.invoiceDetails.lineItems[]` and `reconcile_bill_receipt.billDetails.lineItems[]`, each line uses `name` (NOT `itemDescription`) for the description and `organizationAccountResourceId` (NOT `accountResourceId`) for the revenue/expense account. The bulk-upsert-line-items variants use `itemDescription` + `accountResourceId`. Memorize this: bulk = `itemDescription`+`accountResourceId`; recon-create = `name`+`organizationAccountResourceId`.
57
+
58
+ ### Bulk-upsert responses and contacts
59
+
60
+ 136. **Sync bulk-upsert response carries per-row failures**: `bulk_upsert_currency_rates` and `bulk_upsert_chart_of_accounts` return `{ resourceIds: string[], failedRows: ImportedRowError[], failedCount: number }` synchronously (no jobId polling needed). Each `failedRows` entry: `{ rowIndex, columnName, columnValue, errorCode, errorMessage }`. Empty `failedRows: []` + `failedCount: 0` on full success. For `bulk_upsert_currency_rates` specifically: omitting `rateApplicableTo` defaults it to `rateApplicableFrom - 0.999ms` (prevents temporal gaps in rate lookups). Contrast with async bulk-upserts (contacts, invoices, journals, etc.) which return `{ jobId }` and need `search_background_jobs` polling; there, per-row failures live in the job's `errorDetails` field instead.
61
+
62
+ 137. **`bulk_upsert_contacts` request-level validation**: fails the WHOLE batch with HTTP 422 (no per-row partial success at this layer). Five rules to satisfy before submitting: (a) every contact must have `customer: true` OR `supplier: true` after defaults+backfill; for updates, the API backfills omitted flags from the existing contact; for creates, you must explicitly set at least one. (b) email entries within a contact must be case-insensitively unique (the tool takes `emails: string[]` and expands them to `emailList[{email,label}]`). (c) a payment term whose `name` is `CUSTOM` must carry `value` (rule 137c). (d) `name` must be unique within the batch (after whitespace+case normalize). (e) When `billingAddress` or `shippingAddress` is provided, BOTH `addressLine1` and `country` are required (the tool calls the first one `address` and renames it for you). Pre-validate client-side before calling; one bad row rejects the entire batch and the agent loses any successful work-in-progress.
63
+
64
+ 137a. **`bulk_upsert_contacts`: the tool speaks its own vocabulary and the client renames six keys at the wire boundary** (`toWireContactRows`): `billingName`→`contactBillingName`, `currencyCode`→`currency`, `registrationNumber`→`registrationId`, `notes`→`customerInvoiceNotes`, `shippingAddress`→`deliveryAddress`, `emails: string[]`→`emailList: [{email,label}]`, plus `address`→`addressLine1` inside either address. **Send the TOOL names.** Both addresses require `address` AND `country`; omit either and the API 422s the WHOLE batch, so the client rejects it first with the field named. Note `notes` maps to the customer's DEFAULT INVOICE notes, not an internal memo. **`taxIdType` is not supported**; it appears on no contact definition. All verified live 2026-09-02 with a `taxId` control that stored correctly.
65
+
66
+ 137c. **Payment terms on contacts.** `bulk_upsert_contacts` takes `customerPaymentTerms` / `supplierPaymentTerms` as `{name, value?}`: `name` is `ON_DELIVERY`, `NET_7`, `NET_15`, `NET_30`, `NET_45`, `NET_60` or `CUSTOM` (any case). `value` is the number of days as a string: required for `CUSTOM` as a positive whole number (the client refuses anything else before the call). With any other name the name carries its days, and a `value` that is not a positive whole number fails the WHOLE batch with 422, so the client drops it. A term is stored only for a side the contact is on: a customer term on a supplier-only contact is dropped with a 200. Verified live 2026-09-23: `{name: "NET_30"}` stored `paymentDetail.customerPaymentTerms [{name: "Net 30", value: "30"}]`, the same as a single create. **Bulk UPDATE trap:** a row that omits a term makes the API back-fill it from the stored display name, which is no term name, so Net 30 is re-stored as `Custom`/"30" (measured 2026-09-24). The client re-sends each stored term the row omits under its real name (one contact search per 100 ids). The single-contact create and update take a bare name and store `CUSTOM` with no days, so a term of any other length (21 days) is reachable only through bulk upsert. `clio contacts create|update --payment-terms` / `--supplier-payment-terms` accept a name in any case (not `CUSTOM`) or days 0/7/15/30/45/60; `create` makes the contact that side, `update` refuses a term for a side the contact is not on. This replaces the earlier warning that the bulk shape silently dropped the row, which the API has since fixed. **A contact's status cannot be changed through the API either.** The update (`PUT /contacts/{id}`) has no `status` field and, per the API source, always writes ACTIVE. `bulk_upsert_contacts` with `status: "INACTIVE"` returns job SUCCESS with processedCount 1 and applies nothing: an update's other fields in that row were dropped too, and a create with it left no contact findable (measured 2026-09-24). The client refuses INACTIVE on bulk rows and `clio contacts update --status`. Change status in the Jaz app.
67
+
68
+ ### Contact signals and draft validation
69
+
70
+ 138. **`get_contact_signals`: a contact's usual values, read-only**. `GET /api/v1/contacts/{resourceId}/signals?btType=…` (`btType` required: `SALE` | `PURCHASE` | `SALE_CREDIT_NOTE` | `PURCHASE_CREDIT_NOTE`) reads the contact's posted transactions of that type (value date in the last 12 months, most recent 50) and returns: `patterns[]`, the usual currency, payment terms, tax inclusion, tax presence, account and item, each with `matchCount` / `totalCount` (a value is usual only above half, 70% for the two tax fields; account and item counts are lines); `outstanding`, the open balance across all dates and currencies in the base currency, split past due / not yet due, up to 12 hours behind recent payments, absent when nothing is open; and `cadence` (median interval, `lastDate`, `nextExpectedDate`), present only when the contact transacts regularly (10+ distinct dates, steady interval). No draft is compared, so there are no flags. `sampleSize: 0` with `severitySummary.dominantLabel: NEW` means no history of the type; `NO_ALERTS` means it could not be computed. A user without the Sales (SALE, SALE_CREDIT_NOTE) or Purchases (PURCHASE, PURCHASE_CREDIT_NOTE) module gets 403 `NOT_HAVE_ENOUGH_PERMISSION`. Use it for "what does this contact normally look like?" before drafting; use `validate_drafts` to check a draft.
71
+
72
+ 139. **`validate_drafts` per-result signals and breakdown**. Every `results[]` entry carries, beside `eligible` / `errors[]` / `displayData[]`: (a) **`contactSignals`**, the draft compared with the contact's recent posted transactions of the same type. `severitySummary` holds the check result: `dominantLabel` (ranked RED before YELLOW, then POSSIBLE_DUPLICATE, NEW_CURRENCY, ABOVE_USUAL, BELOW_USUAL, NEW_TERMS, TAX_TYPE, NEW_GST, NEW_COA, NEW_ITEM; nothing found = NEW under 5 compared, else NORMAL; NO_ALERTS = could not check), `tone` (RED / YELLOW / BLUE / GRAY), `high` / `medium` counts, `checkedFields` + `amountChecked` (what a clean result checked). The evidence: `duplicateFlags[]` (at most one: the twin's id, reference, status, date, total, `inBatch`; RED for the same supplier reference on bills and supplier credit notes, YELLOW for the same amount, currency and date), `outlierFlags[]` (total outside 1.5x the contact's range: `previousMin`, `previousMax`, `comparedCount`; RED in the direction that costs money), `revealedDivergences[]` (new currency, terms, tax, or a line on an account or item the contact has not used: `lineNumber`, `draftLabel`, `modalLabel`). A contact with no history gets `sampleSize: 0` and NEW, never null. `contactSignals` is null only for an ineligible draft, a draft with no contact, or when `contactSignalsMeta.unavailable` is true. (b) **`breakdown`**: `items[]` in document order with `lineNumber`, and `meta` with subtotal (net of line discounts), shipping (invoices), tax, total, paymentRecorded, balance, exchangeRate and `totalInFunctional`. Wire names are `contactInsight` (per result) and `contactInsightsMeta`; the client renames them `contactSignals` / `contactSignalsMeta`.
73
+
74
+ ### Chart of accounts: IFRS 18 and bulk upsert
75
+
76
+ 140. **IFRS 18 accountType values (effective 2027)**. `create_account` / `update_account` / `bulk_upsert_chart_of_accounts` accept the 9 IFRS 18 classification types alongside the 14 pre-IFRS-18 types (23 in total, listed in rule 21): **Discontinued Expense**, **Discontinued Income**, **Finance Cost**, **Financing Income**, **Goodwill**, **Income Tax Expense**, **Investing Expense**, **Investing Income**, **Investment**. `normalizeAccountType` (in `core/api/guards.ts`) maps unambiguous variants client-side: "income tax" / "tax expense" → "Income Tax Expense", "finance costs" → "Finance Cost", "investments" → "Investment". **Ambiguous variants are intentionally NOT auto-mapped**: under IFRS 18, "interest expense" can land in EITHER Finance Cost (financing activities) OR Operating / Investing Expense depending on the entity's main business activity, and "interest income" can land in EITHER Financing Income OR Investing Income. The agent must pick the explicit canonical string for those cases instead of relying on a guess that could misclassify the account. Pass any value to `accountType` (POST/PUT will receive it as `classificationType` per rule 21). The classic types still work; IFRS 18 is purely additive.
77
+
78
+ 141. **`bulk_upsert_chart_of_accounts`: sync bulk-upsert with PARTIAL_SUCCESS**. Wraps `POST /api/v1/chart-of-accounts/bulk-upsert` (max 500 per call). Returns synchronously (no jobId polling): `{ resourceIds: string[], failedRows: ImportedRowError[], failedCount: number }` per rule 136. Each successful row contributes one `resourceId`; each failure surfaces a `failedRows[]` entry with `rowIndex` (1-based per the API), `columnName`, `columnValue`, `errorCode`, `errorMessage`. **Dedup is by NAME, not code**; collisions emit `ORGANIZATION_CHART_OF_ACCOUNT_DUPLICATED` per row (other rows in the batch still succeed). Provide `resourceId` per account to update; omit to create. Accepts the all 23 `accountType` values per rules 21 and 140 (variants normalized client-side). For one-off creates with auto-dedup-on-name (returns existing if found), use `create_account` instead. CLI counterpart: `clio accounts bulk-upsert --input <file.json>`.
79
+
80
+ ### Pseudo-SQL and the cashflow report
81
+
82
+ 145. **Pseudo-SQL `truncated:true` does NOT mean "you hit the cap"**; it means "more rows matched than were returned in this preview". Inspect `rowCount` vs preview cap (100) or your LIMIT to interpret. If you need every row, switch to `export_pseudo_sql`.
83
+
84
+ 146. **Pseudo-SQL export `downloadUrl` is S3 pre-signed with ~15min expiry** (`X-Amz-Expires=900`). Fetch immediately; don't store the URL. If a fetch returns 403 (expired), call `get_pseudo_sql_export(jobId)` again for a fresh URL.
85
+
86
+ 147. **Cashflow report** (`download_export(exportType='cashflow')`) returns the org's CASHFLOW template (IAS 7). If no template configured, returns 404 `template_not_found`. Configure via Jaz settings before invoking.
87
+
88
+ 153. **Pseudo-SQL `Idempotency-Key` dedup is server-side primary key**: same key + DIFFERENT query body returns the prior job's result (the server does NOT cross-check the new query body). For agent reliability, `run_pseudo_sql_and_download` auto-keys from `sha256(query).slice(0,16)` so dedup is query-tied automatically. If you call `export_pseudo_sql` directly with a manual key, treat it as a per-intent token; don't reuse across different queries.
89
+
90
+ 155. **Pseudo-SQL schema is canonical; call `get_pseudo_sql_schema` before any query.** The response returns the live curated catalog (tables / columns / joins / functions) PLUS the canonical `jaz-pseudo-sql.md` skill body in `agentSkillsDoc.content`. Drop the `.md` body into context as the syntax-rules source; treat `tables[] / joins[] / functions[]` as the column-list source. **Cache contract:** the `version` field is a stable 16-char hex hash; within a session, cache by version and don't re-call unless you have reason to believe the schema changed (e.g. a fresh backend deploy mid-session). Don't re-fetch on a wall-clock timer (upstream is `private, no-cache, must-revalidate`). A static curated-schema snapshot used to ship with the `jaz-pseudo-sql` skill before v5.6.0; it was dropped because it was structurally guaranteed to drift. Never write a query from a memorized column list.
91
+
92
+ ### Reconciliation: match to existing records, and suggestions
93
+
94
+ 158. **Match-to-EXISTING reconciliation: `reconcile_with_payments` / `reconcile_match_to_transaction` / `reconcile_magic_match` / `reconcile_learned_prediction`.** These reconcile a bank entry against transactions/payments the org ALREADY has, vs `invoice_receipt`/`bill_receipt` which CREATE new ones. Prefer match-to-existing to avoid duplicates.
95
+ - **`reconcile_with_payments`**: the headline. `businessTransactionPayments[]` each carry an open bill/invoice's `cashflowTransactionResourceId` (from `search_cashflow_transactions` or a suggestion's `cftBtResourceId`) + `transactionAmount`; the endpoint CREATES the payment AND reconciles in one call; **no `pay_bill`/`pay_invoice` first.** Also accepts `matchedPayments[]` (existing payments) / `matchedBatchPayments[]` / `adjustment` (over/under-payment + FX write-off). Guard: ≥1 match array non-empty. **FX is auto-resolved server-side; pass NO `currencySettings`/rate for the common case.** Only the rare bill-currency ≠ bank-currency case needs explicit `paymentAmount` (bank ccy) + `currencySettings`. FX gain/loss is NOT auto-posted; post it via `adjustment.cashAdjustmentEntries[]` to an FX account. Errors: `PAYMENT_AMOUNT_REQUIRED_IN_BUSINESS_TRANSACTION_SOURCE_CURRENCY` (cross-ccy missing paymentAmount), `INVALID_EXCHANGE_RATE_ERROR` (adjustment leg in non-functional ccy missing rate), `TOTAL_RECONCILIATION_AMOUNT_MISMATCHED_WITH_STATEMENT_ENTRY_AMOUNT` (sum ≠ entry → add adjustment leg). **NOT idempotent, no client key: a blind retry double-creates a payment; re-check `search_bank_records(status:'RECONCILED')` before retry.**
96
+ - **`reconcile_match_to_transaction`**: SEVERAL bank entries (1-100, unique, same bank account, all money in or all money out) against ONE open invoice, bill or credit note (instalments, a payment split across bank lines). For one entry against an invoice or bill use `reconcile_with_payments`; one entry against a credit note takes this tool too. Body: `bankAccountResourceId` (also the payment account), `bankStatementEntryResourceIds[]`, `cashflowTransactionResourceId` (the document's cashflow id from `search_cashflow_transactions`; never a payment, batch payment, cash entry or journal) and `paymentAmount`: gross, in bank currency, >0, equal to the entries' sum plus a fee charged or minus a fee collected on money in, minus a fee charged on money out. When the document currency differs from the bank account's, or the bank account is not in the base currency, also send `transactionAmount` (document currency) and `currencySettings`: `sourceCurrencyCode` plus `rateFunctionalToSource` or `exchangeToken`, one rate for the whole match (no live rate is fetched; `transactionAmount` without `currencySettings`, or `currencySettings` with neither rate nor token, is refused with 422). Same-currency in the base currency: omit both. Optional `transactionFee` / `transactionFeeCollected` (collected: invoices only; `feeAccountResourceId`, `feeType` FLAT|PERCENTAGE, `feeValue`, `feeTaxVatApplicable` required), split pro-rata across the payments. One payment per entry, dated and sized from the entry, in one transaction: every entry reconciles or nothing is written. The document may stay partly open; an amount over its open balance is refused, never adjusted, and a zero or negative payment is refused. Not idempotent, but a retry after success is refused because the entries are already reconciled.
97
+ - **`reconcile_magic_match`**: bulk-accept suggestions (max 500 entries, at most 100 of them `MAGIC_RECONCILE_WITH_CASH_IN_OUT`; each bank entry once per call). A `MAGIC_MATCH` entry matches existing transactions/payments; a `MAGIC_RECONCILE_WITH_CASH_IN_OUT` entry carries `learnedPredictionResourceId` + `predictedPayload` + `predictedPayloadSchemaVersion` verbatim from the suggestion (optional `retryToken`), exactly as `reconcile_learned_prediction` takes them for one entry. Pass each suggestion's `recommendationId` on its entry (and on `reconcile_learned_prediction`) so the accept is credited to it. Returns `{reconciled[], failed[]}` (either may be absent or empty); a 200 with non-empty `failed[]` is a PARTIAL success (per-entry `errorCode`); when nothing reconciled the call fails with 422. An entry carries only its own workflow's fields (no matches on a CASH_IN_OUT entry, no learned-prediction fields on MAGIC_MATCH). A `failed[]` entry may still have posted (an unexpected failure reports the whole group failed), so re-read each line's state before any retry. `MAGIC_MATCH` entries are NOT idempotent: never blind-retry a timed-out batch; re-read the line state (`search_bank_records`) first. A `MAGIC_RECONCILE_WITH_CASH_IN_OUT` entry is keyed on bank entry + prediction + `retryToken`, so resending it unchanged never books a second journal.
98
+ - **`reconcile_learned_prediction`**: accept an ML prediction. `predictedPayload` + `predictedPayloadSchemaVersion` come VERBATIM from a `view_auto_reconciliation` (MAGIC_RECONCILE_WITH_CASH_IN_OUT) suggestion; never hand-construct. `retryToken` forces a fresh journal on edit-retry; omit for idempotent replay. On failure (stale payload), fall back to `reconcile_with_payments`; don't retry the blob.
99
+
100
+ 159. **`view_auto_reconciliation` returns execution-ready `suggestions[]`, the suggestion→commit seam.** **`bankStatementEntryResourceIds` is REQUIRED: the endpoint is per-entry and has no account-wide mode; source ids from `search_bank_records` (status `UNRECONCILED`).** Each suggestion carries `recommendedTool` (the commit tool to call), `execute` (ready-to-pass args, including the suggestion's `recommendationId` when the platform sent one; merge `bankAccountResourceId` for `reconcile_magic_match`), `confidenceTier` (high/medium/low, code-derived), and `autoCommitEligible` (true ⇒ high confidence + executable plan + under any `autoCommitMaxAmount` cap + for a learned prediction (`MAGIC_RECONCILE_WITH_CASH_IN_OUT`) a `lifecycleStatus` of `ACTIVE`; a `PROBATIONARY` one is still learning and checkpoints at any confidence), plus `checkpointReason` whenever it is false. **Decision gate:** `autoCommitEligible===true` → auto-commit via `recommendedTool`+`execute`; everything else → surface for confirmation. **Amount threshold is a HARD VETO over confidence** (pass `autoCommitMaxAmount`). Field mapping under the hood: `cftBtResourceId`→`cashflowTransactionResourceId` (single → `reconcile_with_payments`), `cftBtResourceIds[]`/`isBatch`→`matchedBusinessTransactions` (batch → `reconcile_magic_match`), `recommendationType`→tool, `confidenceScore`→tier. **Request vs response vocabulary:** the `recommendationType` you SEND selects what to compute and additionally accepts `RECOMMENDATIONS` (every type except `MAGIC_MATCH`, ranked together, and the cheaper call; `MAGIC_MATCH` scans open transactions so it is requested on its own; nothing returns everything at once). The `recommendationType` you RECEIVE on a suggestion is always a concrete type and is never `RECOMMENDATIONS`, so the `recommendationType`→tool mapping above is unaffected by which selector you sent. Pass `includeRaw:true` for the unmapped payload. Cost tracks the entries you pass; batch large backlogs. On a 500, or no answer in time (25 s in chat and on hosted MCP, 55 s on stdio MCP, 60 s from the CLI and `clio mcp-call`), it returns `{degraded:true}` with a `reason` naming the wait; use the `clio jobs bank-recon match` cascade. NOT idempotent applies to every commit; see Rules 125 + 158.
101
+
102
+ ### Payment adjustments
103
+
104
+ 160. **Payment `adjustment` is a CASH-LEG-only correction; it never moves the document balance.** Records an overpayment or a rounding difference on the bank side of a payment: `netCash = paymentAmount -/+ fees +/- adjustmentValue` (fees are deducted from cash received on an invoice and added to cash spent on a bill). AR/AP is untouched, so an overpaid invoice stays PAID with the excess sitting on the account you chose and NO credit note is created. Shape: `adjustment: { adjustmentValue, adjustmentAccountResourceId, adjustmentDescription? }`, signed, non-zero, max 2dp, always FLAT (never a percentage), never taxed. Accepted on `pay_invoice` / `pay_bill` / both credit-note refunds / `update_payment` / both receipt reconciliations. **NOT** on batch payments, and not for `DEBT_WRITE_OFF` / `CLEARING_SETTLEMENT` / `INTER_COMPANY` / `WITHHOLDING_TAX_CERTIFICATE` (those record a settlement, so there is no cash leg). The account must be non-controlled: not AR/AP, not the VAT or FX accounts, not bank/cash, not deposit-linked. **Write/read asymmetry:** you WRITE the nested `adjustment.adjustmentValue` but READ a flat `adjustmentAmount` on the payment record, alongside `adjustmentOrganizationAccountResourceId`. Don't confuse either with `lineItems[].taxVatAdjustment.adjustmentAmount`, which is line-item tax and unrelated. **On `update_payment`, adding an adjustment and changing an existing one both APPLY.** Verified against production on arap `v10.7.21` (2026-08-11): an amount move and an account-plus-description move both returned 200 and applied. `paymentAmount` and `transactionAmount` are untouched. **Removing one does NOT work.** `adjustmentValue: 0` is rejected at the edge with a 422, and `"adjustment": null` is indistinguishable from omitting the field, so both leave the stored value unchanged. To remove an adjustment, delete the payment record and record it again without one. An explicit clear flag is being added upstream; zero stays rejected, so omit-to-clear will never be the answer. Anything describing this field as inert on update is stale. **arap `v10.7.21` put both guards behind one comparator, and a CHANGE now has two rejection conditions.** `PaymentAmountCalculator.adjustmentChanged` answers "did the adjustment change?" for the reconciled check AND for lock-date validation, which previously disagreed: the reconciled check compared the amount alone, and lock-date validation did not look at the adjustment at all. It compares **amount, account AND description** (amount by `compareTo`, so `5.0` and `5.00` are equal). Two conditions reject a change: **(a) the payment is RECONCILED** to a bank statement entry, giving `PAYMENT_ADJUSTMENT_CANNOT_CHANGE_WHEN_RECONCILED` (moving it to a different account trips this now, where the amount-only check let it through); **(b) an account on the payment's LEDGER ROWS carries a lock date later than the `valueDate`**, giving `DELETE_TRANSACTION_VALUE_DATE_CANNOT_BE_EARLIER_THAN_LOCK_DATE` -- an update deletes and recreates the ledger rows, so the delete half trips first and the code names a delete for a call that was an update. **The escape hatch:** resending the same adjustment, or omitting the field, compares equal and is NOT a change, so it does not by itself trip either guard. **But that is not a general exemption, and this is the trap.** `adjustmentDescription` is optional, so resending only `adjustmentValue` + `adjustmentAccountResourceId` against a payment that HAS a description compares unequal and counts as a change. Resend all three, or omit the object entirely. And lock-date validation gates on seven other fields independently: changing `reference`, `valueDate`, `paymentMethod`, `organizationAccountResourceId`, `paymentAmount`, `transactionAmount`, or converting a draft to active is lock-date validated on its own. Only edits that move no ledger row survive a lock. **Measured on production 2026-08-11**, throwaway account locked at 2026-07-31 over a payment dated 2026-06-15: change the adjustment -> 422; change ONLY `reference` -> 422; resend all three values unchanged -> 200; resend WITHOUT the description -> 422; then unlock and repeat the first call -> 200 and applied. That last row is the control. Condition (a) is read from the deployed source, not triggered: it needs a bank statement entry, which has no delete, so proving it costs permanent state on a shared org.
105
+
106
+ ### Report templates
107
+
108
+ 161. **Report templates: the saved layout of a report, one default per report type, and packs.** Eight verbs on MCP and CLI (list, get, search, default-configuration, create, update, set-default, delete), each taking a template by **resourceId or exact name**; render one with `download_export` / `clio exports download --template <name>`. `templateConfiguration` is a JSON-encoded string on the wire; Clio hands it over as an object, never shows the server-owned `coaSnapshot` (a copy of the whole chart of accounts, up to 324 KB), and returns a large layout as a key map plus a row outline. Change part of one with `edits` (set / insert / remove by path; updateRow / addRow / removeRow / moveRow by row id), applied all or nothing and refused when they introduce a silent fault (an unknown enum value, a formula naming a missing row, a removed engine total). **Set default changes every export and dashboard view** of that report for the whole organization; the answer carries `previousDefault` to undo it. A pack's reports come from `packTemplates` (names or ids, in order), written to both places the server reads them from. Measured upstream quirks (2026-09-24): an export given a template it cannot use (unknown, or of another report type) answers **HTTP 200 with an empty body**, so Clio checks the template first; for P&L and cashflow only `IAS_1` and `IFRS_18` have a default layout (`GAAP` / `IND_AS` / `IFRS_SME` answer 422 `NO_TEMPLATE_FOUND` without one); profit-and-loss and balance-sheet saves drop keys the server does not model with no error (Clio reports them as `notSaved`); deleting a pack's last report leaves an empty pack whenever the pack has any other component (Clio refuses it); upstream search refuses `and` / `or` and name sort (Clio filters the list). Full reference: `references/report-templates.md`.
@@ -0,0 +1,108 @@
1
+ # Jaz API Rules 89-117: Bank Rules, Assets, Schedules, Quick Fix, Payments
2
+
3
+ Part of the jaz-api skill. [SKILL.md](../SKILL.md) holds the reading order and the index of all four rule files. Rule numbers are stable: tool descriptions, `errors.md` and other skills cite them by number, and a missing number is a retired rule.
4
+
5
+ ### Bank Rules
6
+ 89. **Bank rules GET by ID has double-nested response**: `GET /bank-rules/:id` returns `{ data: { data: [...], totalElements, totalPages } }` (double `data` wrapper). Unlike standard `GET /:type/:id` which returns `{ data: {...} }`. The inner `data` is an array containing the single rule. Unwrap with `response.data.data[0]`. **Field asymmetry**: Request uses `appliesToReconciliationAccount` (string UUID), response returns it as an object `{ code, currencyCode, name }`.
7
+ 90. **Bank rules search uses `/bank-rules/search`**: Standard search pattern with filter/sort/limit/offset. Filter fields: `appliesToReconciliationAccount`, `name`, `reference`, `resourceId`, `actionType`, `businessTransactionType`. Sort fields: `resourceId`, `name`, `actionType`, `businessTransactionType`, `reference`, `appliesToReconciliationAccount`, `createdAt`.
8
+ 90a. **Bank rules create field is `appliesToReconciliationAccount`** (NOT `appliesToReconciliationAccountResourceId`), the bank account UUID. `configuration` must nest under `reconcileWithDirectCashEntry` key. `configuration.reconcileWithDirectCashEntry.reference` is REQUIRED (omitting causes GENERAL_ERROR). `amountAllocationType`: use `"PERCENTAGE"` or `"FIXED"`; `"FIXED_AND_PERCENTAGE"` is read-only (include both `fixedAllocation` + `percentageAllocation` arrays and the server infers it). Optional config fields: `contactResourceId`, `internalNotes`, `tags`, `currencySettings`, `taxCurrencySettings`, `classifierConfig` on allocation lines. **Send `searchFilter` too**, see 90d; a rule without one is never suggested.
9
+ 90b. **Bank rules PUT is FULL REPLACEMENT**: `PUT /bank-rules/:id` replaces the entire rule. Must send `resourceId`, `appliesToReconciliationAccount`, and full `configuration` every time. Omitting any required field causes GENERAL_ERROR. Use read-modify-write pattern: GET current rule, merge changes, PUT full payload. Same pattern as items PUT (Rule 72) and capsules PUT (Rule 73). **`searchFilter` is the one exception**: omit it and the API keeps the stored condition, send `null` to remove it, send an object to replace it.
10
+ 90c. **Bank rule POST canonical create payload** (verified live 2026-04, NOT obvious from any single field error):
11
+ ```json
12
+ {
13
+ "name": "My Rule",
14
+ "appliesToReconciliationAccount": "<bank-account-uuid>",
15
+ "configuration": {
16
+ "reconcileWithDirectCashEntry": {
17
+ "amountAllocationType": "PERCENTAGE",
18
+ "reference": "AUTO-{{bankReference}}",
19
+ "percentageAllocation": [
20
+ { "organizationAccountResourceId": "<acct-uuid>", "amount": 100 }
21
+ ]
22
+ }
23
+ }
24
+ }
25
+ ```
26
+ **Required nested keys** (each missing one returns a different cryptic error):
27
+ - `configuration` MUST nest under `reconcileWithDirectCashEntry` key (the action type, even though there's only one type today)
28
+ - `amountAllocationType`: `"PERCENTAGE"` or `"FIXED"` only (NOT `FULL_AMOUNT` despite that sounding right)
29
+ - For `PERCENTAGE`: `percentageAllocation: [{organizationAccountResourceId, amount}]` (ARRAY of allocations summing to 100)
30
+ - For `FIXED`: `fixedAllocation: [{organizationAccountResourceId, amount}]` (ARRAY of fixed amounts)
31
+ - `reference` is **required** in the action config (omitting → cryptic 422)
32
+
33
+ **Dynamic strings**: `name` and `reference` support `{{bankReference}}`, `{{bankPayee}}`, `{{bankDescription}}` placeholders, replaced with bank record values during reconciliation.
34
+
35
+ **actionShortcutResourceId** for `apply_bank_rule` IS the rule's own `resourceId` from create response (no separate "action shortcut" entity).
36
+
37
+ 90d. **Bank rules support column-value mapping**. `reconcileWithDirectCashEntry` can resolve fields per row from a custom bank-statement column: `amountSourceColumnKey` (set amount by a column; mutually exclusive with `amount`), `organizationAccountResourceIdMap`/`taxProfileResourceIdMap`/`classifierConfigMap` on each `fixedAllocation` line, and `contactResourceIdMap`/`tagsMap` on the shortcut. Each `*Map` is a `ColumnValueMapConfig` (`columnKey` + ordered `mappings[]`, first match wins, blank `matchValue` = catch-all); `targetResourceId` is a UUID (tag NAME for `tagsMap`). `reference` also takes `{{column:<key>}}` / `{{column_abs:<key>}}` tokens. Full shape: `references/bank-rule-column-mapping.md`. **The rule's WHEN side is the inline `searchFilter`, and without one the rule is never suggested.** Auto-reconciliation only considers rules whose stored condition is non-null, so a rule created without it exists, lists, and applies manually, but is never offered. Shape: `{"version": 1, "raw": "description:grab", "parsed": {"description": {"contains": "grab"}}}`; `raw` is the one-line form shown in the app and **may be blank**; `parsed` is what the matcher compiles. Condition fields: `description`, `extReference`, `extContactName`, `netAmount`, `valueDate`, plus the account's active custom Bank Fields. Operators (15, from the matcher's own map): TEXT `eq`/`contains`/`notContains`/`startWith`/`notStartWith`/`isBlank`/`isNotBlank`, compared case-insensitively, the blank pair taking no value; NUMERIC `eq`/`gt`/`gte`/`lt`/`lte`/`inRange`/`notInRange`; DATE `eq`/`gt`/`gte`/`lt`/`lte`/`between`/`notBetween`. Combine with `{"and": {...}}` or `{"orGroup": [{"and": {...}}]}`. **An unsupported field path does not error**: the rule saves, lists, and then never fires, because the matcher logs a warning server-side and skips it; use only the fields above. `relatedSearchShortcutResourceIds` (the retired saved-search path) is not exposed by this API at all; the platform rejects a request that sets both.
38
+
39
+ ### Fixed Assets
40
+ 91. **Fixed asset search does NOT support `createdAt` sort**. Valid sort fields: `resourceId`, `name`, `purchaseDate`, `typeName`, `purchaseAmount`, `bookValueNetBookValueAmount`, `depreciationMethod`, `status`. Using `createdAt` returns 422. Default to `purchaseDate` DESC.
41
+ 92. **Fixed asset disposal/sale/transfer use different endpoint patterns**. Discard: `POST /discard-fixed-assets/:id` (body includes `resourceId` + dates). Mark sold: `POST /mark-as-sold/fixed-assets` (body-only, no path param). Transfer: `POST /transfer-fixed-assets` (body-only). Undo: `POST /undo-disposal/fixed-assets/:id`.
42
+ 92a. **Two ways to register fixed assets**. (1) **Create** (`POST /fixed-assets`): for assets purchased via a bill or journal already in the system. ACTIVE assets require `purchaseBusinessTransactionType` (`PURCHASE` or `JOURNAL_MANUAL`) and `purchaseBusinessTransactionResourceId`, **the resourceId of the purchase LINE ITEM (or the manual-journal entry), NOT the bill or journal document**. Passing the document id fails. The line item must also be UNLINKED: reusing one already attached to another asset fails with `ITEM_ALREADY_LINKED_WITH_ANOTHER_FIXED_ASSET`. (2) **Transfer** (`POST /transfer-fixed-assets`): for pre-existing assets purchased before using Jaz or outside the system. Accepts `bookValueAccumulatedDepreciationAmount` for depreciation already incurred. No linked transaction needed.
43
+ 92b. **`saveAsDraft` defaults to `true`**. To create an ACTIVE fixed asset, pass `saveAsDraft: false` with ALL required fields: `name`, `category`, `typeCode`, `purchaseAmount`, `purchaseDate`, `purchaseAssetAccountResourceId`, `depreciationMethod`, `effectiveLife`, and for `STRAIGHT_LINE`: `depreciationStartDate`, `accumulatedDepreciationAccountResourceId`, `depreciationExpenseAccountResourceId`. Omitting any returns 422.
44
+ 92c. **Valid enums**. `depreciationMethod`: `STRAIGHT_LINE`, `NO_DEPRECIATION`. `category`: `TANGIBLE`, `INTANGIBLE`. `accumulatedDepreciationAccountResourceId` and `capsuleResourceId` can be safely omitted; the API ignores empty values. **`purchaseBusinessTransactionResourceId` is omittable ON DRAFTS ONLY**, and because `saveAsDraft` defaults to `true` here (Rule 92b: fixed assets are the one transaction type that drafts by default), omitting it looks like it worked right up until you set `saveAsDraft: false` and the create is rejected. On an ACTIVE asset it is required, and it is the purchase LINE ITEM's id (Rule 92a).
45
+
46
+ ### Subscriptions & Scheduled Transactions
47
+ 93. **Subscription endpoints are under `/scheduled/subscriptions`**: List, GET, POST, PUT, DELETE all at `/api/v1/scheduled/subscriptions[/:id]`. Cancel is **PUT** (not POST) at `/api/v1/scheduled/cancel-subscriptions/:id` (different path pattern). **Subscriptions are invoices only** (SALE), no bills. Different from scheduled invoices: subscriptions auto-prorate partial periods (generate credit notes for mid-period changes), but currency/tax/account are immutable after creation. Use scheduled invoices for fixed-amount recurring invoices where you need per-occurrence flexibility. **Create requires `proratedConfig: { proratedAdjustmentLineText: string }`**: Clio injects it on create; do not add it manually. Update does not need it (an update without `proratedConfig` succeeded, measured 2026-09-24); send it only to amend proration. **`repeat` is required on POST** (valid: `ONE_TIME`, `DAILY`, `WEEKLY`, `MONTHLY`, `YEARLY`); Clio maps from the `interval` parameter. Cancel requires `cancelDateType` (`END_OF_CURRENT_PERIOD`, `END_OF_LAST_PERIOD`, `CUSTOM_DATE`) + `proratedAdjustmentLineText` + `resourceId` in body. Must cancel before delete. `businessTransactionType` is NOT in the OAS; the API ignores it. **Update needs the `invoice` template every time** (create shape; without it the PUT is a 422 `GENERAL_ERROR`), and **an update without `status` activates a paused subscription**: Clio restates the stored status when you omit it (see errors.md, Subscriptions).
48
+ 94. **Scheduled transaction search does NOT support `createdAt` sort**. `POST /scheduled-transaction/search` sort fields: `startDate`, `nextScheduleDate`, etc. Default to `startDate` DESC. This is a cross-entity search across all scheduled types (invoices, bills, journals, subscriptions). Filter by `businessTransactionType` (SALE, PURCHASE, JOURNAL) and/or `schedulerType` (RECURRING, SUBSCRIPTION) to narrow results.
49
+
50
+ ### Contact Groups
51
+ 96. **Contact groups have `associatedContacts` array**: each group contains `{ name, resourceId, associatedContacts: [{ name, resourceId }] }`. Search via `POST /contact-groups/search`.
52
+
53
+ ### Inventory
54
+ 97. **Inventory balances: one item or all.** One item: `GET /inventory-item-balance/:itemResourceId` (`get_inventory_balance`) returns `{ itemResourceId, latestAverageCostAmount, baseQty, baseUnit }`; the id is the ITEM resourceId, not an inventory-specific ID. All items: `GET /inventory-balances/:balanceStatus` (`list_inventory_balances`, `clio inventory balances --status`) with `balanceStatus` one of `ALL`, `AVAILABLE`, `FULLY_DRAWN` (anything else is 422); rows carry `itemCode`, `internalName`, `totalQuantity`, `baseUnit`, `averageCostAmount`, `balanceAmount`. The API answers an empty result with 404; the tool and CLI return it as `data: []`. `offset` is a page number here, though the spec says row (probed live 2026-09-23).
55
+
56
+ ### Withholding Tax
57
+ 98. **Withholding codes are `GET /withholding-codes`** (`list_withholding_codes`, `clio tax-profiles withholding-codes`): the BIR ATCs with `code`, `rate`, `rateType`, `type` (corp, ind, final, wvat), `description` and `resourceId`; filters `countryCode`, `code` (contains, space included) and `type`; `limit` max 100, `offset` is a page. `GET /withholding-tax-codes` is a different list (MSIC/PSIC industry codes) that no withholding field accepts. A customer's 2307 is a sale batch payment with method `WITHHOLDING_TAX_CERTIFICATE` (`record_withholding_tax_certificate`): PH orgs only, sales only, account = the system "Creditable Withholding Tax" account, one allocation per code by `resourceId`, and each allocation's `baseAmount` is the TAX WITHHELD (the dashboard's "Withholding" column; `amount` is the income); the `baseAmount`s must add up to the payment total within 0.01. The certificate lands on the invoice as `recordedWithholding_ph` (`get_invoice`), not among its payments, so an empty payment list does not mean it failed; `delete_payment` with the record's `resourceId` removes it (verified live 2026-10-07).
58
+ 99. **Duplicate detection fields**. API rejects duplicates with 422: Contacts on `name` (NOT `billingName`), Items on `itemCode`, Accounts on `name`, Tax Profiles on `name`. Agent tools auto-search before creating; if a match is found, the existing entity is returned instead of hitting a 422.
59
+
60
+ ### Tax Profile Scoping
61
+ 100. **Tax profiles have `appliesToSale`/`appliesToPurchase` scope**: A sales-only tax profile used on a bill causes 422. Always filter by transaction type when selecting: `search_tax_profiles` accepts `appliesTo` param (`sale`, `purchase`, `sale_credit_note`, `purchase_credit_note`). Invoices → `sale`, Bills → `purchase`.
62
+
63
+ ### Cash Entry PUT Requirements
64
+ 101. **Cash entry PUT requires `accountResourceId` + `resourceId`**: `PUT /cash-in-entries/:id` and `PUT /cash-out-entries/:id` require both `accountResourceId` (bank account) and `resourceId` in the body. Omitting `accountResourceId` causes 500. `accountEntryResourceId` is optional (auto-populated).
65
+
66
+ ### Cash Entry Account Type
67
+ 102. **Cash-in/out `accountResourceId` must be a Bank Accounts type**: Using expense, revenue, or other non-bank accounts causes 422 `CASH_OUT_ACCOUNT_TYPE_NOT_ALLOWED` (or equivalent for cash-in). Use `list_bank_accounts` or `search_accounts` with `accountType: "Bank Accounts"` to find valid accounts.
68
+
69
+ ### Journals
70
+ 103. **Journal entries must balance**: Sum of all DEBIT amounts must exactly equal sum of all CREDIT amounts. Unbalanced journals are rejected with 422. Agent tools pre-flight check this client-side before hitting the API.
71
+
72
+ ### Transaction References
73
+ 104. **References must be unique per org; NEVER invent one**: On invoices, customer credit notes, quotes and orders a duplicate `reference` causes 422 `Sale Reference already exists`. Bills, supplier credit notes and manual journals accept a duplicate silently, so both documents keep the same number and nobody is told: search by reference before creating one again after an unconfirmed result. Ask whose number it is. **Purchase side (bills, supplier credit notes): use the SUPPLIER'S own document number**, read off the document; only if it genuinely has none, set `autoReference: true`. **Everything we issue (invoices, customer credit notes, quotes, sale orders, purchase requests, purchase orders, journals, expense claims): set `autoReference: true`** to take the next number from the organization's own series, or call `get_next_reference` to preview it first. Never a timestamp, never a guess, never a pattern inferred from other documents. This covers the business transaction families only; payments, cash entries, transfers, employee payouts, scheduled invoices, scheduled bills, scheduled journals and subscriptions have no series here and keep their own references. The scheduled bodies additionally REQUIRE a literal reference: they mint per occurrence upstream, so `autoReference` is rejected there even though the published schema shows the field. Sending both `reference` and `autoReference` is not an error here: the client resolves the number before the request and your explicit `reference` wins, costing one wasted series read. Send one. The assigned number always carries today's date even on a back-dated document, and reading the series does not reserve it.
74
+
75
+ ### Currency Rates
76
+ 105. **`add_currency_rate` for new rates, `update_currency_rate` only for editing existing records**: When a user says "update the rate" or "set the rate", use `add_currency_rate` (POST, creates a new rate entry for a date). Only use `update_currency_rate` (PUT) when explicitly modifying an existing rate record by its resourceId.
77
+ 106. **Contact PUT uses `email` (string), not `emails` (array)**: GET returns `emails: [{email, label}]` (array) but PUT accepts `email: "user@example.com"` (string). Sending the `emails` array in PUT body causes 400 "Invalid request body". The CLI and tool executor handle this automatically via read-modify-write with the correct field.
78
+
79
+ ### Quick Fix (Bulk Update)
80
+ 107. **24 Quick Fix endpoints for bulk-updating transactions and line items**: `POST /api/v1/quick-fix/{entity}` with `{ resourceIds: [...], attributes: {...} }`. Only included fields are changed; omitted fields are left unchanged. Response: `{ updated: string[], failed: [{ resourceId, error, errorCode }] }`. **HTTP status codes**: 200 = complete success (`failed` always empty). **207 Multi-Status** = partial or total failure with per-item detail (same response shape as 200, so check the `failed` array). 422 = total failure with no per-item breakdown (rare). On 207, retry only `failed` resourceIds. Entities: **ARAP**: invoices, bills, customer-credit-notes, supplier-credit-notes. **Accounting**: journals, cash-entries. **Schedulers**: sale-schedules, purchase-schedules, subscription-schedules, journal-schedules. **Orders (line items only, no transaction-level route)**: sale-orders, sale-quotes, purchase-orders, purchase-requests. **Line-item request patterns**: ARAP, accounting and orders use `{ lineItemResourceIds, attributes }` (purchase side adds `withholdingTax`). **Line-item `discount` and `withholdingTax` use the quick fix shapes, not the create/update ones**: `discount: { rateType: "PERCENTAGE"|"FLAT", rateValue }` (not a bare number) and `withholdingTax: { code, rate, rateType, type, description? }` (code, rate, rateType and type all required), on bills, supplier CNs and purchase orders/requests alike. Schedulers (sale/purchase/subscription) use Pattern C: `{ schedulerUpdates: [{ schedulerResourceId, lineItemUpdates: [{ arrayIndex, attributes: {...} }] }] }` (fields INSIDE `attributes`; beside `arrayIndex` they are unknown keys). **Journal-schedules use Pattern D**: `lineItemResourceId` (UUID) instead of `arrayIndex`. **Field gotchas**: an unknown field is a 400 that names it, and clio refuses it before sending (per-entity list: jaz-api-reference `endpoints-bulk-edits.md`, generated from the spec). A change to a paid document's currency or rate, a line's quantity, price, discount or tax, or the date of a foreign-currency document (its rate is fetched again) deletes its payments as in Rule 8a. Currency change: `currencySettings: { sourceCurrencyCode }` (not the create shape `currency: { sourceCurrency }`); lines and tax profiles stay. `sourceCurrencyCode` is required even when only `rateFunctionalToSource` changes (422 without it), and schedules also need the rate. `billFrom`/`billTo`/`creditFrom`/`creditTo` need `name` and `billingAddress` (plus `shippingAddress` on `billTo`/`creditTo`), each address with `addressLine1`; the address is replaced, not merged, so resend stored values you are not changing. Cash entries use `currencySetting` (singular: `{ rateFunctionalToSource, exchangeToken }`), NOT `currencySettings`. Journal schedules take `endDate`/`interval`, not `startDate` (a schedule's start date cannot change). Sale and subscription schedule lines refuse `withholdingTax`. Tags: string array, max 50 items, max 50 chars each; on invoices, bills and credit notes they total at most 1000 characters joined with `|`, else 422. **Line-item `classifierConfig`** sets or removes one classifier per entry: set = `{ resourceId, type, printable, selectedClasses }` with at least one class; remove = `{ resourceId, deleted: true }`; classifiers not named stay; `[]` changes nothing. A 207 `failed` entry can carry an empty `resourceId` when the failure matched no record.
81
+ 107a. **Ledger Find & Fix: find and fix (recode) records across types with one filter, preview one change, apply it once.** Use it when a user asks to find & fix, recode, reclassify, retag, re-date or move records to another account across many records or several types. `POST /api/v1/ledger/find-fix/transactions/preview` (sets contact, date, capsule, tags) or `POST /api/v1/ledger/find-fix/line-items/preview` (sets account, classifiers), each with `{ filter, change }`, then `POST /api/v1/ledger/find-fix/apply` with `{ previewId }`; conditions, bodies and every code are in jaz-api-reference `endpoints-bulk-edits.md` section 17a. `JOURNAL` covers manual and cashflow journals only: transfer and trial-balance journals and cash transfers never match, so their ids come back `NOT_FOUND`. **A filter with no condition besides `types` is a 422, and a condition with no operator is ignored.** **The API refuses a key it does not take, at any level, with 400 `invalid_filter` naming the key**; the tools and the CLI refuse a field of the other level before the request, naming the level that takes it. `tags` `{ add, remove }` keeps the record's other tags, so setting tags to X means removing the current ones and adding X. A classifier removal needs only `{ resourceId, deleted: true }`, even for a classifier the organization no longer has. **Preview** writes nothing, matches at most 500 records, and returns `previewId` (valid 30 minutes; absent when nothing is eligible). **A blocked field is left as it is while the record's other fields still change.** **Apply** is single use and saves the preview-time values, so a field edited between preview and apply, tags included, is overwritten. Once it has taken the preview it runs to the end even if the caller leaves, and starts no new call 3 minutes after the request arrived. 207 lists the `failed` records with an `errorCode`; `OUTCOME_UNKNOWN` means that record may have changed. 404 `PREVIEW_NOT_FOUND` (expired, used, being applied, or another caller's): preview again, never resend. **Any other 5xx, or a timeout, on apply means the outcome is unknown: if the connection drops, the apply keeps running for up to 4 minutes. Wait that long before previewing or applying again on the same records, then preview again or re-read them. Never apply this previewId again.** Several applies can run at the same time. When two applies change records on one document at once, the one saved last can undo the other's changes, including fields and line items it did not set. Preview again to check the result. Lock dates, filed tax periods and claims-backed documents fail per record, and e-invoice filings may be re-submitted. Rule 107's per-type routes stay for one document, for fields this does not change (due date, tax profile, notes, amounts, custom fields) and for scheduled transactions.
82
+
83
+ ### Transfer Trial Balance
84
+ 108. **Transfer Trial Balance** (`POST /api/v1/transfer-trial-balance`) creates opening balance entries. Uses `journalEntries` (NOT `lines`; this is a journal type). Always ACTIVE (no draft mode), reference auto-generated as "Transfer Trial Balance", minimum 1 entry, entries cannot have 0 amounts, skips lock date validation. **`valueDate` must be today or in the past**; future dates are rejected with "Opening data cannot be future date". Each entry: `{ accountResourceId, type: "DEBIT"|"CREDIT", amount }`.
85
+
86
+ ### Scheduler Dynamic Strings
87
+ 109. **Scheduler placeholder strings**: All scheduled transactions (invoices, bills, journals, subscriptions) support dynamic strings in any free text field (`reference`, line item `name`, `notes`). **Scheduled JOURNALS are the exception**: their line field is `description`, not `name`, and they have no notes field at all: neither `notes` nor `internalNotes` is on the create or update contract. Probed 2026-09-02: both are accepted like any unknown key and never read back, so for journals the only dynamic-string field is `reference`. Strings are replaced with values relative to the **transaction date**: `{{Day}}` → day name (Monday), `{{Date}}` → full date (09 Mar 2026), `{{Date+X}}` → date + X days, `{{DateRange:X}}` → date range spanning X days (min 1, max 999), `{{Month}}` → month name (March), `{{Month+X}}` → month + X months, `{{MonthRange:X}}` → month range spanning X months, `{{Year}}` → year (2026), `{{Year+X}}` → year + X years. Example: `reference: "INV-{{Month}}-{{Year}}"` → `"INV-March-2026"` for a March transaction.
88
+
89
+ ### Bank Rule Dynamic Strings
90
+ 110. **Bank rule placeholder strings**: Bank reconciliation rules support dynamic strings in any free text field (`name`, `reference`, cash entry description). Strings are replaced with actual **bank record** values during reconciliation: `{{bankReference}}` → bank record reference (e.g., INV-03/01/2025-01), `{{bankPayee}}` → payer/payee name (e.g., Fruit Planet), `{{bankDescription}}` → transaction description (e.g., QR Payment). Example: `reference: "{{bankPayee}} - {{bankReference}}"`.
91
+
92
+ ### Quick Fix Tag Field
93
+ 111. **Quick-fix uses `tags` (string array), e.g., `"tags": ["Q1"]`**: The `attributes` object in quick-fix transaction endpoints accepts `tags` as a string array (e.g., `"tags": ["Q1"]`). `tag` (singular) is refused as an unknown key. This matches the `tags` array format used on create/update for all transaction types. The CLI `--tag` flag auto-wraps to `tags: [name]`.
94
+
95
+ ### Sub-Resource Response Shapes
96
+ 112. **Invoice/bill payment & credit sub-resources: two shapes** (read from the API source; payments and the empty-credits case measured raw 2026-09-24). `GET /invoices/:id/payments` and `GET /bills/:id/payments` return `{ data: [{paymentRecord}, ...] }` (Rule 64). `GET /invoices/:id/credits` and `GET /bills/:id/credits` return `{ TotalElements, data: [...] }` when credits are applied but a BARE `[]` when none are. The CLI and tools normalize all of these to `{data: [...]}`. `DELETE /invoices/:id/credits/:creditsAppliedResourceId` reverses a credit application.
97
+
98
+ ### Nano-Classifier API
99
+ 113. **Nano-classifier API gotchas**: CREATE uses `classes: string[]` (NOT `classNames` or `[{className}]`). `printable: boolean` is required, defaults to `false` (most classifiers are not printable). GET single is double-wrapped: `{data: {data: [...], totalElements, totalPages}}`; extract the first element from the inner paginated response. GET/LIST response returns classes as `[{className, resourceId}]` (objects), while CREATE accepts plain `string[]`.
100
+
101
+ ### Scheduler Response Asymmetry
102
+ 114. **Scheduler response uses `interval`, not `repeat`**: POST/PUT uses `repeat` field (values: `ONE_TIME`, `DAILY`, `WEEKLY`, `MONTHLY`, `YEARLY`; `QUARTERLY` is rejected with 422). GET response returns `interval` field (same values; legacy rows may still show `QUARTERLY`). PUT accepts the full transaction template (`invoice`, `bill`, or journal entries at top level), not just schedule metadata; same structure as POST.
103
+
104
+ ### Payment Record CRUD
105
+ 115. **Payment record CRUD**: `GET /payments/:resourceId` returns `{data: PaymentRecord}` (wrapped). Payment resourceIds come from invoice/bill GET response → `paymentRecords[].resourceId`. **Cashflow transaction IDs ≠ payment IDs**; don't mix them. `POST /cashflow-transactions/search` returns cashflow IDs, while payment CRUD uses separate payment IDs from the parent document.
106
+
107
+ 116. **PaymentMethod accepts 11 values**. All payment endpoints (invoices, bills, credit note refunds, payment updates) accept: `CASH`, `BANK_TRANSFER`, `CREDIT_CARD`, `CHEQUE`, `E_WALLET`, `WITHHOLDING_TAX_CERTIFICATE`, `CLEARING_SETTLEMENT`, `DEBT_WRITE_OFF`, `INTER_COMPANY`, `OTHER`, `PAYMENT_GATEWAY`. Default is `BANK_TRANSFER`. The OAS previously listed only 7; the API runtime already accepted all 11.
108
+ 117. **Fixed asset sale accepts PURCHASE type**: `saleBusinessTransactionType` in mark-as-sold accepts `SALE`, `PURCHASE`, or `JOURNAL_MANUAL`. Use `PURCHASE` when the disposal is linked to a purchase-side transaction (e.g., trade-in).