Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(accounting): multi-provider sync engine — Xero, QuickBooks Online, Rillet (#1308)
Brad Barbinfb005bc3bebe
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 39847e16c7..d47a193fbc 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -356,7 +356,7 @@ Format: `Context → Problem → Rule → Applies to`**Rule:** When hand-seeding `journalLine` rows, set the sign to move the account toward its natural balance: `+` increases an Asset/Expense (debit) and increases a Liability/Equity/Revenue (credit). Verify against the `journalEntries` view (`totalDebits == totalCredits` per `journalEntryId`) before relying on the data — an unbalanced entry silently blocks period close. Posted `journal`/`journalLine` rows are immutable (`journal_posted_immutable` / `journalLine_posted_immutable`); to correct seeded mistakes you must disable those triggers on the local DB (superuser), never in a migration.-**Applies to:** any SQL journal fixtures; the `journalEntries` view; the `tb-balanced` close check in `computePeriodReadiness` (`accounting.service.ts`).+**Applies to:** any SQL journal fixtures; the `journalEntries` view; the `tb-balanced` close check in `computePeriodReadiness` (`accounting.ee.service.ts`).## A period snapshot written at close races Locked-period postings unless the posting guard locks the period row@@ -834,6 +834,28 @@ canvas hosting Radix popovers/selects.**Applies to:** `packages/database/supabase/functions/post-shipment/index.ts` (PO vs SO split blocks); any refactor threading a shared record-builder through multiple writers (`post-*`, `issue`, sync handlers).+## Carbon journal amounts are natural-balance-signed, not debit-signed++- **Context:** Wiring Rillet journal posting sync; first live push of a real+ `Purchase Receipt` journal failed UNBALANCED_JOURNAL (+300/+300).+- **Problem:** The accounting sync engine (preflight balance check, netting,+ consolidation, all provider journal mappers) assumed `journalLine.amount`+ is debit-signed (positive = debit, negative = credit, sum = 0). Carbon's+ post-* edge functions actually sign by the account's NATURAL balance+ (`credit("liability", x)` stores +x — functions/lib/utils.ts), so real+ journals balance as debits == credits, not signed-sum-zero. Also:+ Kysely/pg returns DATE columns as JS Date objects — `postingDate.slice`+ crashes; and disabled-config skip results without `localId` make the+ drain report the misleading "No sync result returned for entity".+- **Rule:** Convert to debit-signed at the fetch edge with+ `toDebitSignedAmount(account.class, amount)` (join account.class in the+ journal-line query), normalize dates with `toPostingDateString`, and+ always set `localId`/`remoteId` on every SyncResult, including early+ skips. Never trust the debit-signed assumption against live journal data+ without checking the edge functions' credit()/debit() helpers.+- **Applies to:** packages/ee/src/accounting (journal syncers, posting+ preflight, consolidation), any new accounting provider's journal mapper.+## A conformance check is only as good as its source glob — route modules are server AND client in one file**Context:** The timezone audit (branch `sid/timezone-tz-audit`, PR #1339) added the `no-local-timezone` conformance check to ban process-timezone day derivation in server code. Self-review then found 26 surviving violations in route files, plus more in files the check DID scan using idioms it didn't match.@@ -924,6 +946,15 @@ canvas hosting Radix popovers/selects.**Applies to:** `apps/erp/app/modules/sales/sales.service.ts` (`upsertQuoteLinePrices`), any `Kysely<KyselyDatabase>` service in `apps/erp/app/modules/**` or `packages/database/supabase/functions/**`, and the `getPostgresClient` pool in `packages/database/supabase/functions/lib/postgres/index.ts`.+## A VERIFY-flagged provider endpoint in a cron loop is an outage, not a TODO++**Context:** The Rillet AP payment pull assumed an org-wide `GET /bill-payments` feed mirroring `/invoice-payments`. The method carried a VERIFY comment ("assumed to mirror… not confirmed") and even named its own fallback, but shipped unguarded inside `listChanges`. The endpoint does not exist (404).++**Problem:** Every `accounting-pull-sweep` run threw at the AP step, killing the whole Rillet pull — including the AR invoice-payment changes collected earlier in the same call — every 30 minutes, silently. Payments recorded in Rillet never flowed back to Carbon, so a bill paid remotely stayed open locally, got paid a second time in Carbon, and the outbound push then failed forever on Rillet's over-pay guard. One unverified assumption at the bottom of a sweep became a permanent, compounding data gap that surfaced two layers away from its cause.++**Rule:** An API call that only runs inside a cron/sweep is exercised for the first time in production — verify VERIFY-flagged endpoints against the live sandbox *before* wiring them into a loop (one curl answers it), and never let one entity family's listing failure discard another family's already-collected changes. When an assumed endpoint is missing, compose from verified ones instead: Rillet AP payments = `GET /bills?updated.gt` (payment activity bumps the bill's `updated_at`) + `GET /bills/{id}/payments` per changed bill.++**Applies to:** `packages/ee/src/accounting/providers/rillet/provider.ts` (`listChanges`, `listBillPaymentsUpdatedSince`), any `SupportsIncrementalPull.listChanges` implementation, VERIFY-flagged calls anywhere under `packages/ee/src/accounting/providers/**`.## react-aria's blur commit makes the input formatter part of arithmetic**Context:** The numeric-precision standard's motivating bug — a user typed 6.25% tax, saved, reopened, and read 6.22%.diff --git a/.ai/plans/2026-08-13-accounting-sync-automated-postings-only.md b/.ai/plans/2026-08-13-accounting-sync-automated-postings-only.mdnew file mode 100644index 0000000000..690072db17--- /dev/null+++ b/.ai/plans/2026-08-13-accounting-sync-automated-postings-only.md@@ -0,0 +1,175 @@+# Plan: Accounting sync = Carbon's automated postings only (always-on, no manual journals)++Date: 2026-08-13+Branch: feat/rillet+Status: Tasks 1-6 + 8 implemented 2026-08-13 (working tree; Task 1 was pre-existing WIP). Tasks 7 (reversal/void propagation audit) and 9 (lock families to documents) remain open.++## Goal / principle++The accounting sync mirrors **exactly** Carbon's automated GL postings — every+`journalEntrySourceType` **except `Manual`** — plus their reversals/voids, using the+mapped accounts. This is the **definition** of the sync, not a configurable option:++- **Automated postings always sync** when an accounting integration is connected. No+ master "posting sync enabled" toggle, no per-source-type on/off, no `journalEntry`+ entity gate. If an account isn't mapped the op warns `UNMAPPED_ACCOUNTS` (correct —+ the user maps it); it is never silently dropped.+- **`Manual` journals never sync**, in any engine. They are the only path to+ non-mapped/arbitrary accounts, and the external GL owns things Carbon doesn't+ (payroll, etc.). Carbon is a *subset* of the external GL.+- **AR/AP keep native-document representation** (bill → ACCPAY Bill, invoice → ACCREC+ Invoice). GR/IR clears because the coupled receipt journal now always syncs, and the+ bill's own `Purchase Invoice` journal stays `DOC_BACKED` (no double-post).+- Provider-agnostic: lands identically on Xero, QBO, Rillet.+- **No existing-company remediation / backfill** — building + testing only.++Grounded against the edit map in this branch's investigation. Verified current shapes:+`POSTING_POLICY` (models.ts:290-413), the `journalEntryPushEnabled` gate+(reconcile-executor.ts:123-124 + reconcile.ts:186-188), `DEFAULT_SYNC_CONFIG.entities.journalEntry`+(models.ts:242-246), the three `build*SyncConfig`, and `getPeriodExternalGlSyncReadiness`+(apps/erp accounting.service.ts:~2431-2444).++## Design decisions (resolved)++- **D1 — Manual marker.** `POSTING_POLICY` is `Record<JournalEntrySourceType, …>`, so+ `Manual` can't be deleted. Add `syncable: boolean` to `PostingPolicyEntry`; `Manual`+ is the only `syncable: false`. The policy resolver returns `MANUAL_DISABLED` for+ `Manual` **permanently**, regardless of stored config.+- **D2 — Config fields: keep-but-ignore, don't delete.** To avoid a stored-config parse+ break (`resolvePostingSyncSettings` swallows parse errors → silently disables sync —+ posting.ts:56-63), keep `PostingSyncStoredSchema.enabled` and per-type `enabled` in the+ schema for backward-compatible parsing, but **stop reading them** in the decision core.+ Force `enabled` default to `true`. The decision core treats every non-Manual+ journal-represented type as always-push.+- **D3 — Native docs, always.** AR/AP families default to `documents`. See Task 9+ (recommended, separable) for removing the `none`/`journals` options so the config+ can't express "don't sync AR/AP".+- **D4 — Granularity stays.** Per-type `individual` vs `daily-summary` is a real volume+ control (Production Event, Job Consumption default daily); keep it.++## Tasks++### Task 1 — `Manual` permanently non-syncable (core policy)+Files: `packages/ee/src/accounting/core/models.ts`, `packages/ee/src/accounting/core/posting.ts`+- [x] Add `syncable: boolean` to `PostingPolicyEntry` (models.ts:269-282). Set `syncable: false`+ on `Manual` (models.ts:294-298), `true` on every other entry.+- [x] In `getJournalPostingPolicyDecision` (posting.ts:186-204): replace the+ `!config.enabled` gate. If `!policy.syncable` → return+ `{ kind:"exclude", reason:"MANUAL_DISABLED", … }`. Otherwise for+ `representation:"journal"` → `{ kind:"push", granularity: POSTING_POLICY[st].defaultGranularity }`+ (no per-type enable read). Keep the null/unknown-source-type exclude (posting.ts:153-171).+- [x] Keep the Inventory-Adjustment DOC_BACKED branch (posting.ts:173-184) and+ `decideDocumentFamily` (posting.ts:236-295) unchanged.+- Verify: `pnpm --filter @carbon/ee test -t "getJournalPostingPolicyDecision"` — Manual+ excludes MANUAL_DISABLED; every other journal type pushes.++### Task 2 — Always-on: remove the master + journalEntry-entity gate+Files: `packages/ee/src/accounting/core/models.ts`,+`packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts`,+`packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts`+- [x] `DEFAULT_SYNC_CONFIG.entities.journalEntry.enabled` → `true` (models.ts:242-246);+ update the "opt-in per company" comment.+- [x] `PostingSyncStoredSchema.enabled` default → `true` (models.ts:537).+- [x] `reconcile-executor.ts:123-124`: `journalEntryPushEnabled` → drop `&& settings.enabled`;+ reduces to `isJournalEntryPostingEnabled(...)` (now always true) — or hardcode `true`+ and delete the field. Update `ReconcileContext.journalEntryPushEnabled` doc (reconcile.ts:104-105).+- [x] `isJournalEntryPostingEnabled` (accounting-sync-operations.ts:231-235) doc → always-on.+- Verify: `pnpm --filter @carbon/jobs typecheck`.++### Task 3 — Downstream consumers of the removed gate+Files: `packages/jobs/src/inngest/functions/integrations/{accounting-backfill,accounting-consolidation,accounting-outbound-sweep,accounting-reconciliation}.ts`,+`packages/ee/src/accounting/providers/{rillet,xero,quickbooks-online}/entities/journal-entry.ts`+- [x] Remove the `settings.enabled` / `isJournalEntryPostingEnabled` skip guards:+ accounting-backfill.ts:212 + 218-219; accounting-consolidation.ts:173 + 736;+ accounting-outbound-sweep.ts:197; accounting-reconciliation.ts:754.+- [x] Remove the per-provider backstop `if (!settings.enabled) return "Posting sync is not enabled"`:+ Rillet journal-entry.ts:414, Xero journal-entry.ts:544, QBO journal-entry.ts:561.+- Verify: grep shows no remaining `settings.enabled` reads in the sync engine except the+ backward-compat schema field.++### Task 4 — Providers force `journalEntry` enabled (defense-in-depth)+Files: `packages/ee/src/accounting/providers/{xero,quickbooks-online,rillet}/provider.ts`+- [x] The `DEFAULT_SYNC_CONFIG` flip (Task 2) already makes it always-on. Additionally, in+ each `build*SyncConfig`, ensure `journalEntry` is forced `enabled:true` so a stale+ stored `enabled:false` can't turn it off (Rillet already forces direction/owner at+ provider.ts:292-297 — add `enabled:true` there; add journalEntry forcing to Xero+ 129-135 / QBO 334-349 loops or a dedicated line).+- Verify: provider `build*SyncConfig` tests assert `journalEntry.enabled === true`.++### Task 5 — Tie-out / period-close readiness (stop auto-passing)+File: `apps/erp/app/modules/accounting/accounting.service.ts`+- [x] `getPeriodExternalGlSyncReadiness` (~2431-2444): gate on **presence of an active+ accounting integration**, not `settings.postingSync.enabled`. Return+ `postingSyncEnabled: true` whenever an active integration exists; auto-pass only when+ **no** integration is connected. Update the "Auto-pass when posting sync is off"+ comment (~2724).+- Verify: `pnpm exec turbo run typecheck --filter=@carbon/erp` (scoped) + read the readiness test if one exists.++### Task 6 — UI: remove the toggles that no longer exist+Files: `apps/erp/app/modules/settings/ui/Integrations/PostingSyncSettings.tsx`,+`apps/erp/app/modules/settings/settings.models.ts`,+`apps/erp/app/routes/x+/settings+/integrations.$id.tsx`+- [x] Remove the master enable `<BooleanField name="enabled">` (PostingSyncSettings.tsx:205-210)+ + its defaultValue (174).+- [x] Remove the per-source-type enable checkbox (255-262); keep the daily-summary control+ (271-287) but show it for all non-Manual journal types (decouple from `state.enabled`).+- [x] Exclude `Manual` from `journalRows` entirely (never render it).+- [x] Validator `postingSyncSettingsValidator` (settings.models.ts:508-525): drop `enabled`;+ `sourceTypeConfigs` carries granularity-per-non-Manual-type only.+- [x] Route action (integrations.$id.tsx): remove the dual-gate mirror block (1305-1340)+ and the `enabled` destructure (1240-1246); hard-exclude `Manual` in the sourceTypes+ build loop (1264-1273); the loader `policy` map (787-792) filters out `Manual`.+- Verify: scoped ERP typecheck; load the Posting tab in the browser — no master toggle, no+ per-type enable, no Manual row.++### Task 7 — Reversals / voids propagate (comprehensive requirement)+Files: reconcile core + provider entity syncers (investigate during execution)+- [ ] Confirm a voided/reversed automated posting propagates: (a) a reversal journal+ (`reversalOfId` set) pushes its reversing entry — the reconciler tracks `:reversal`+ twins; (b) a voided native document (ACCPAY bill / ACCREC invoice) voids/reverses the+ remote document, not just leaves it. Add coverage where missing.+- Verify: unit coverage for a reversal journal + a document void → remote void/reverse.++### Task 8 — Tests+Files: the tests the edit map flagged.+- [x] Rewrite the gating tests to the always-on model:+ `posting-policy.test.ts` (Manual→MANUAL_DISABLED always; drop SOURCE_TYPE_DISABLED for+ known types; add a `syncable` assertion + non-syncable-Manual);+ `posting.test.ts` / `journal-entry.test.ts` ("pushes Manual only when includeManual" →+ "never pushes Manual"; "defaults to disabled posting sync" → "always-on");+ `accounting-sync-operations.test.ts` `isJournalEntryPostingEnabled` (default true);+ `reconcile-golden.test.ts` (remove/repurpose the "posting sync disabled" scenario+ 231-249; `journalEntryPushEnabled` stays true);+ provider `provider.test.ts` buildSyncConfig assertions (journalEntry.enabled true).+- [x] Add a golden case: PO → receipt (Purchase Receipt journal pushes) → bill (ACCPAY doc,+ PI journal DOC_BACKED) → GR/IR nets to zero; a Manual journal → excluded.+- Verify: `pnpm --filter @carbon/ee test && pnpm --filter @carbon/jobs test`.++### Task 9 — (Recommended, separable) Lock AR/AP to native documents+Files: models.ts (`families`), posting.ts (`decideDocumentFamily`), PostingSyncSettings.tsx,+settings.models.ts, integrations.$id.tsx+- [ ] Remove the `none` and `journals` family options so the config can't express+ "don't sync AR/AP" or "AR/AP as manual journals". Force `families = documents`; delete+ the `familyAr`/`familyAp` selects, validator fields, and the divergent-family payment+ branch (posting.ts:207-226). Keep the read-only document-rows display.+- Rationale: "none" violates always-on; "journals" contradicts the chosen native-doc+ representation. Do NOT block Tasks 1-8 on this — documents is already the default, so the+ core fix is correct without it; this is foot-gun removal.++## Verification (whole change)+```bash+pnpm --filter @carbon/ee typecheck+pnpm --filter @carbon/jobs typecheck+pnpm exec turbo run typecheck --filter=@carbon/erp+pnpm --filter @carbon/ee test+pnpm --filter @carbon/jobs test+```+Then a live smoke test on the Carbon Xero company: post a receipt + bill with accounting on,+confirm GR/IR nets to zero in Xero and a Manual journal does not sync.++## Risks+- Stored-config parse break silently disables sync (posting.ts:56-63 swallows errors) — hence+ D2 keep-but-ignore rather than delete schema fields.+- `consolidation` derived field (models.ts:598-604) reads per-type `enabled` — retarget its+ filter to "journal-represented AND != Manual".+- Removing gates flips several tests green→red by design; Task 8 rewrites them to the new contract.diff --git a/.ai/plans/2026-08-14-xero-qbo-payment-push-parity.md b/.ai/plans/2026-08-14-xero-qbo-payment-push-parity.mdnew file mode 100644index 0000000000..23a0f70a36--- /dev/null+++ b/.ai/plans/2026-08-14-xero-qbo-payment-push-parity.md@@ -0,0 +1,78 @@+# Plan: Xero + QBO outbound payment write-back (Phase G parity)++Date: 2026-08-14+Branch: feat/rillet+Status: Implemented 2026-08-14 — Xero live-verified on sandbox (bill → PAID); QBO code-complete, payload VERIFY-flagged (no QBO sandbox)++## Goal++A Carbon-born payment (e.g. a bill paid in Carbon) pushes to Xero/QBO — marking the+bill PAID and posting the bank/AP GL effect — exactly as Rillet already does (Phase G).+Today Xero/QBO payments are pull-only, so a Carbon payment's GL never reaches them.++The push engine is **already generic** (`PaymentSyncerBase.pushToAccounting`, the+`reconcilePayment` decision core, fan-out, origin/loop-guard, mapping link with+`origin:"carbon"`, the payment event trigger, ledger + drain). Only Rillet flips the+switches. Parity = per-provider adapter + un-hardcode two Rillet-only gates.++Carry over Rillet's v1 limits (enforced in the shared base): single-settlement,+base-currency (`exchangeRate === 1`), no discount/write-off, no void-echo (voided+Carbon payments Skip with a manual-remediation message).++## Edit sites (from the investigation)++### Shared (un-hardcode the Rillet-only gates)+- [ ] `packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts:355` —+ `providerSupportsPaymentPush: args.providerId === "rillet"` → true for rillet/xero/quickbooks+ (derive from a provider capability, not a string literal).+- [ ] `packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts:274-291` —+ page posted payments as candidate refs for Xero/QBO too (critical for Xero: the+ outbound sweep is its only periodic drain).++### Subscriptions+- [ ] `packages/ee/src/accounting/core/subscriptions.ts` — add+ `{ table: "payment", operations: ["INSERT","UPDATE"] }` to the Xero and QBO+ `REQUIRED_SYNC_SUBSCRIPTIONS` arrays. (Invariant test already satisfied — payment→payment+ maps and both have a payment syncer.)++### Xero (`providers/xero/`)+- [ ] `provider.ts` — move `payment` from `XERO_PULL_ONLY_ENTITIES` to a new+ `XERO_TWO_WAY_ENTITIES = ["payment"]` forced `direction:"two-way"`, `owner:"accounting"`,+ `enabled:true` in `buildXeroSyncConfig` (mirror Rillet's `RILLET_TWO_WAY_ENTITIES`).+- [ ] `provider.ts` — add `createPayment(payload)` → `request("PUT","/Payments",{body})`;+ return `Payments[0].PaymentID`.+- [ ] `entities/payment.ts` — `supportsPaymentPush = true`; remove the `direction === "push"`+ rejection in `shouldSync`; implement `pushRemotePayment` (mirror Rillet `payment.ts:375-443`):+ resolve doc remote id via mapping (`invoice` for AR / `bill` for AP), resolve bank code via+ `loadAccountCodesById`, **bank-type pre-check** (fail UNMAPPED_ACCOUNTS if the mapped Xero+ account is not BANK/`EnablePaymentsToAccount`), build `{ Payments:[{ Invoice:{InvoiceID},+ Account:{Code|AccountID}, Amount, Date }] }`, call `createPayment`, return `{ remoteId,+ compositeEntityId }` via `getXeroPaymentSyncEntityId`/`getXeroBillPaymentSyncEntityId`.++### QBO (`providers/quickbooks-online/`)+- [ ] `provider.ts` — `payment` two-way (as Xero); add `createBillPayment`/`createPayment` via the+ generic `writeEntity(...)`.+- [ ] `entities/payment.ts` — `supportsPaymentPush = true`; remove push rejection; implement+ `pushRemotePayment`: AP `BillPayment` `{ VendorRef, TotalAmt, TxnDate, PayType, CheckPayment:{+ BankAccountRef }, Line:[{ Amount, LinkedTxn:[{ TxnId, TxnType:"Bill" }] }] }`; AR `Payment`+ `{ CustomerRef, TotalAmt, TxnDate, DepositToAccountRef, Line:[{ Amount, LinkedTxn:[{ TxnId,+ TxnType:"Invoice" }] }] }`. Use `getQbo*PaymentSyncEntityId` builders + `loadQboAccountRefsById`.++### Tests+- [ ] Provider `provider.test.ts`: `payment` two-way (direction/enabled) for Xero + QBO.+- [ ] `subscriptions` invariant test stays green; add payment-subscription assertions.+- [ ] Payment-syncer tests: Xero/QBO `pushRemotePayment` builds the right payload; bank-type+ pre-check warns; pull-side loop-guard still skips a mapped (provider-known) payment.++## VERIFY on the live Xero sandbox (before trusting the push path)+- Xero create verb/body: `PUT` vs `POST /Payments`; `Account` by `AccountID` vs `Code`.+- Xero rejects a non-BANK payment account → confirm the error, keep the pre-check.+- QBO `BillPayment` required `PayType` + bank sub-object; `Payment.DepositToAccountRef`.++## Verify (gates)+```+pnpm exec turbo run typecheck --filter=@carbon/ee --filter=@carbon/jobs+pnpm --filter @carbon/ee test && pnpm --filter @carbon/jobs test+```+Then a live Xero sandbox round-trip: post a Carbon payment against a synced bill, confirm the+Xero bill flips to PAID and a Xero Payment exists.diff --git a/.ai/runs/2026-08-05-accounting-handoff-run.md b/.ai/runs/2026-08-05-accounting-handoff-run.mdnew file mode 100644index 0000000000..b16fb018ba--- /dev/null+++ b/.ai/runs/2026-08-05-accounting-handoff-run.md@@ -0,0 +1,349 @@+# Run Log: 2026-08-05 Accounting Handoff (Phase F fixes + Document Representation)++> Executing `.ai/plans/archived/2026-08-05-accounting-handoff.md`. Branch `feat/rillet`.+> Ground rules: never commit/push/stash/reset/clean; pnpm only; scoped gates; ENV-GATED+> steps skipped + logged; STOP-and-report on any code mismatch (no improvised workarounds).++## Baseline (before any edit)++- `pnpm exec turbo run typecheck --filter=@carbon/ee` → **green** (1 successful).+- `pnpm --filter @carbon/ee test` → **456 passed (32 files)** — matches handoff baseline.++---++## Part A — Phase F review fixes++### A1 — Xero: make deleted payments visible to the sweep — **done**++- Change: removed the `where=Status=="AUTHORISED"` filter from `XeroProvider.listChanges`+ (`providers/xero/provider.ts`); the poll now returns both AUTHORISED and DELETED+ payments so the void path (`entities/payment.ts` DELETED → `status:'void'`) is+ reachable. Updated the method doc comment. `dependsOnMapping` still emitted for+ DELETED payments (logic doesn't branch on status — confirmed).+- Tests: updated the existing listChanges test's URL assertion (`not.toContain+ "where=Status"`); added a new test asserting one AUTHORISED + one DELETED payment+ page yields two payment changes each with its invoice dependency. DELETED →+ `mapToNormalized` → `status:'void'` already covered by `entities/__tests__/payment.test.ts`.+- Gates: `typecheck @carbon/ee` → **pass (1 successful)**; `test @carbon/ee` →+ **457 passed (32 files)** (baseline 456, +1 new test).++### A2 — QBO: hard-deleted payments become tombstone voids — **done**++- Changes (4 pieces of the design implemented as written):+ 1. `providers/quickbooks-online/provider.ts` `buildPaymentChange`: a CDC+ `Deleted` Payment/BillPayment stub now emits a deleted-flagged change+ carrying the BARE payment id (no refetch, no `dependsOnMapping`) instead of+ logging+returning null.+ 2. NEW `core/payment-tombstone.ts` → `findPaymentCompositesByRemoteId(client,+ {companyId, integration, paymentRemoteId})`: suffix-matches+ `externalIntegrationMapping` (`entityType='payment'`, `externalId LIKE+ '%:<id>'` + exact JS `endsWith` guard) to recover the composite(s). Exported+ from the accounting barrel.+ 3. `accounting-pull-sweep.ts` deleted-stub branch: for `entityType==='payment'`+ it calls the helper and enqueues one pull op per composite (via a new+ shared `enqueueChange` closure); no match → skip as before; non-payment+ deletions unchanged (log+skip).+ 4. `providers/quickbooks-online/entities/payment.ts` `fetchRemote`: a not-found+ (null) refetch returns a bare tombstone marker `{ Id: paymentRemoteId }`;+ `mapToNormalized` maps it (amount 0, no lines) to `status:'void'` →+ `upsertLocalPaymentDraft` `postAction:'void'` → `post-payment {type:'void'}`.+- **DESIGN NOTE (non-blocking):** the handoff said the deleted-flagged change+ should carry "the bare QBO payment id + family". `ProviderChange` (core/types.ts)+ has no `family` field, and the sweep helper resolves the composite by suffix+ regardless of family (`bill:` prefix already encodes it), so family is neither+ representable nor needed. Implemented without it. Not a STOP — the cited+ behavior is satisfied; only the incidental "+ family" is dropped.+- **DESIGN NOTE (non-blocking):** the design said fetchRemote should "catch the+ not-found error"; the actual provider `getPayment`/`getBillPayment` return+ `null` on error (they never throw). Implemented as a null check. A first-ever+ pull that 404s is caught by shouldSync's first-seen-void skip (isFirstSync ++ amount 0), so nothing is voided that was never recorded.+- Tests: (a) CDC test rewritten — a `Deleted` BillPayment stub now yields one+ deleted-flagged bare-id change, still no refetch (1 fetch call). (b) NEW+ `core/payment-tombstone.test.ts` (5 cases): AP + AR suffix resolution, exact+ endsWith guard drops coarse `:xbp-1`/null matches, `[]` on error, `[]` on no+ match. (c) NEW `entities` tombstone test: `fetchRemote` null → `{Id}` marker →+ `mapToNormalized` void (family/doc/amount 0, no linkedDocuments); a found+ payment passes through untouched. Full `functions.invoke({type:'void'})` chain+ is base behavior already covered by base/payment tests + upsertLocalPaymentDraft+ void semantics (not re-driven here — would require standing up the DB tx).+- Gates: `typecheck @carbon/ee` → **pass**; `test @carbon/ee` → **464 passed+ (33 files)** (+7 vs 457); `typecheck @carbon/jobs` → **pass** (sweep touched).++### A3 — Rillet: park FX payments instead of posting at rate 1 — **done**++- Change: `providers/rillet/entities/payment.ts` `shouldSync` now reads the+ company base currency (`loadCompanyBaseCurrency(this.database, this.companyId)`+ from `./shared`, cached per instance via `baseCurrencyPromise` — same pattern+ as the item/journal-entry syncers) and compares it to the payment currency+ (`getRilletPaymentCurrency(remoteEntity)`). Mismatch → skip with reason+ `FX payment (<cur> ≠ base <base>) — not supported v1`. Same currency or no+ currency → proceed unchanged. Placed after the first-seen-FAILED skip, before+ `return true`, using the existing skip-with-reason mechanism.+- Tests: new `shouldSync FX gate` describe (3 cases): EUR≠USD parked with the+ reason; USD proceeds; currency-less payment proceeds. Added a table-aware fake+ db (`makeFxDb`) answering both the metadata and `company.baseCurrencyCode`+ reads. Existing ownership-gate tests unaffected (their fixtures carry no+ currency, so the FX branch is a no-op).+- Gates: `typecheck @carbon/ee` → **pass**; `test @carbon/ee` → **467 passed+ (33 files)** (+3 vs 464).++### A4 — Force-enable pull-only `payment` for QBO and Xero — **done (already forced; added assertions)**++- Finding: BOTH providers ALREADY force-enable `payment` the way Rillet does —+ `buildQboSyncConfig` (`quickbooks-online/provider.ts`, `QBO_PULL_ONLY_ENTITIES`)+ and `buildXeroSyncConfig` (`xero/provider.ts`, `XERO_PULL_ONLY_ENTITIES`) both+ overlay `payment → { enabled: true, direction: 'pull-from-accounting', owner:+ 'accounting' }` in the constructor. No forcing mechanism needed to be added.+- Per the handoff ("If yes, just add the assertion test"), added a direct+ force-enable assertion per provider, mirroring the Rillet `buildRilletSyncConfig`+ test: (1) `build*SyncConfig(stored-with-payment-disabled).entities.payment`+ equals the forced pull-only shape (and asserts `DEFAULT_SYNC_CONFIG` ships it+ disabled), and (2) a constructed provider's `getSyncConfig("payment")` returns+ the forced shape. Added to `quickbooks-online/__tests__/provider.test.ts` and+ `xero/provider.test.ts`.+- Gates: `typecheck @carbon/ee` → **pass**; `test @carbon/ee` → **471 passed+ (33 files)** (+4 vs 467).++### A5 — Settings copy for the families gate — **done (optional, A1–A4 clean)**++- Change: `apps/erp/app/modules/settings/ui/Integrations/PostingSyncSettings.tsx`+ — extended the existing AR/AP representation `<Trans>` helper paragraph (the+ same route's own copy pattern) to also explain that `documents` mode pulls+ provider-recorded payments back into Carbon, closing the matching invoice or+ bill and posting a Carbon GL journal. No new component; no parenthesized+ numbers. (The `familyAr`/`familyAp` Selects share this section's description.)+- Gate: `pnpm exec turbo run typecheck --filter=erp` → **pass (1 successful)**.+- Note: the copy change alters a Lingui message id; the .po catalogs refresh at+ build/extract time (not required by A5's verify, which is erp typecheck only).++## Final report++### Per-task status++| Task | Status | Notes |+|------|--------|-------|+| A1 — Xero deleted payments visible to sweep | done | AUTHORISED-only filter removed |+| A2 — QBO hard-deleted tombstone voids | done | 2 non-blocking design notes (see A2) |+| A3 — Rillet FX payments parked | done | base-currency FX gate in shouldSync |+| A4 — Force-enable pull-only `payment` (QBO+Xero) | done | already forced; added assertions |+| A5 — Settings copy for families gate | done | optional; done since A1–A4 clean & quick |++### Final gate counts++- `pnpm exec turbo run typecheck --filter=@carbon/ee` → **pass**.+- `pnpm --filter @carbon/ee test` → **471 passed (33 files)** vs the **456**+ baseline (+15 tests, all new; 0 regressions).+- `pnpm exec turbo run typecheck --filter=@carbon/jobs` → **pass** (A2 sweep edit).+- `pnpm exec turbo run typecheck --filter=erp` → **pass** (A5 copy edit).++### ENV-GATED skips (Part A)++- None. No Part A task required a provider sandbox or a running stack; all four+ fixes were unit-verifiable. (Part B and its VERIFY gates were NOT executed —+ out of scope for this run.)++### STOP-and-report mismatches++- None that blocked. Two **non-blocking** cited-vs-actual deviations, both in A2,+ adapted faithfully (details in the A2 section):+ 1. Handoff: deleted-flagged change carries "bare payment id + family".+ Actual: `ProviderChange` (core/types.ts) has no `family` field, and the+ suffix helper resolves the composite without it. Implemented without family.+ 2. Handoff: fetchRemote should "catch the not-found error". Actual: QBO+ `getPayment`/`getBillPayment` return `null` on error (never throw).+ Implemented as a null-check → tombstone; shouldSync's first-seen-void skip+ protects a never-recorded payment.++Nothing committed (per ground rules).++## Part B — Document representation++> Baseline re-confirmed before starting Part B: `typecheck @carbon/ee` → **pass**;+> `test @carbon/ee` → **471 passed (33 files)** (matches the Part A end state).++### B-0.1 — Extract `core/document-costing.ts` — **done**++- NEW `packages/ee/src/accounting/core/document-costing.ts`:+ - `loadBillCostingLines(db, { companyId, billId, payablesAccountId })` →+ `{ lines: CostingLine[], currencyCode, exchangeRate }`. Reads the bill's+ `purchaseInvoice` currency/rate, then its posted "Purchase Invoice"+ journal lines (base-currency, debit-signed via `toDebitSignedAmount`);+ excludes the AP control line (`accountId === null || !== payablesAccountId`,+ verbatim from Rillet's filter); carries `journalLineDimension` refs; and+ joins item labels via `documentLineReference` (`purchase-invoice:<poLineId>`+ → `purchaseOrderLine.itemId` → `item.readableId`/`name`). Direct/variance+ lines resolve to `sourceItem: undefined`. Empty `lines` = no posted journal.+ - `toTransactionCurrencyLines(lines, exchangeRate)` — ÷ rate, 2dp, residue+ into the largest-|amount| line; rate 1 = pass-through; negatives preserved.+ - Added to the accounting barrel (`index.ts`).+- **Pre-verified facts confirmed against code** (no mismatch): `journalLine.+ documentLineReference` column exists (`20230705033432_ledgers.sql:112`);+ stamped `purchase-invoice:<id>` by `journalReference.to.purchaseInvoice`+ (`functions/lib/utils.ts:113`); `purchaseOrderLine.itemId` FK → `item`+ (`20230510035345_purchasing.sql:353`); `item.readableId`/`item.name` exist;+ `Rillet.BillSchema.exchange_rate` present.+- Tests: NEW `core/document-costing.test.ts` (8 cases): AP-line exclusion ++ debit-sign, PO-backed sourceItem vs bare variance line, dimension carry,+ no-posted-journal → `[]`, and `toTransactionCurrencyLines` rate-1+ pass-through / residue balancing / negative preservation / empty input.+- Gates: `typecheck @carbon/ee` → **pass**; `test document-costing` →+ **8 passed (1 file)**.++### B-0.2 — Refactor Rillet bill onto the core (parity + FX fix + shouldSync) — **done**++- `providers/rillet/entities/bill.ts`:+ - Removed `fetchPostingJournalLines` + `filterBillCostingLines` (no other+ importers — grep clean); `mapToRemote` now calls the shared+ `loadBillCostingLines`.+ - `BillPostingJournalLine` is now an alias of the core `CostingLine`+ (stable name for the mapper's tests).+ - `mapBillToRilletBill`: prepends the item label+ (`describeCostingLine`: `"<code> <name> — <desc>"`, or the label alone+ when the line has no description) when `sourceItem` is present; runs+ `toTransactionCurrencyLines(costingLines, bill.exchangeRate)` and pins+ `exchange_rate` on the payload when the rate ≠ 1. **FX bug fixed**:+ previously pushed base-currency amounts under the transaction currency+ with no rate; now pushes transaction-currency amounts + `exchange_rate`.+ - Kept the defensive AP re-filter + the unmapped-account Warning so raw+ journal-line callers (tests) still work.+ - Added a posted-status `shouldSync` (`SYNCABLE_STATUSES` = the 7 posted+ bill statuses; Draft + Voided excluded) mirroring the Rillet invoice+ syncer.+- **Parity gate (gate for all of Part B) — PASSED:** the 7 pre-existing+ Rillet bill tests (base-currency, no sourceItem) are byte-identical (green+ unchanged). Added 3 tests: item-label prepend (account/amount unchanged,+ `exchange_rate` undefined at rate 1), label-only when no description, and+ an FX fixture (EUR @ rate 2) asserting halved transaction-currency amounts+ + `exchange_rate: 2` + preserved negative variance line.+- Gates: `typecheck @carbon/ee` → **pass**; `test @carbon/ee` → **482 passed+ (34 files)** (471 baseline + 8 B-0.1 + 3 B-0.2; 0 regressions).+- Also added `costingLineItemLabel` to `core/document-costing.ts` (shared+ `"<code> <name>"` label helper) and refactored Rillet's `describeCostingLine`+ onto it (Rillet still *prepends*; QBO/Xero *substitute* — per the plan's+ differing phrasing).++### B-1.1 — QBO bill → account-based journal replay (PO untouched) — **done**++- `providers/quickbooks-online/entities/bill.ts`:+ - NEW pure `buildQboBillLines({ bill, costingLines, accountRefsById })`+ emitting one `AccountBasedExpenseLineDetail` per costing line to the+ journal's mapped account (via the existing `loadQboAccountRefsById`+ resolution); `Description = costingLineItemLabel(line) ?? line.description`;+ no item detail, no tax. Unmapped / account-less / no-journal → structured+ `UNMAPPED_ACCOUNTS` Warning (`warning: true`), mirroring the Rillet bill.+ - `mapToRemote`: dropped `ensureDependencySynced("item")` (labels come from+ Carbon, not the QBO item) and the shared `buildQboExpenseLines` call;+ now loads costing lines via `loadBillCostingLines`, converts with+ `toTransactionCurrencyLines`, and pins `CurrencyRef` + `ExchangeRate`+ (omitted at rate 1). Kept the vendor JIT + DocNumber + Net-30 due date.+ - Added a push-only posted-status `shouldSync` (`SYNCABLE_STATUSES`;+ Draft/Voided excluded) mirroring the QBO invoice syncer.+ - Added `getPayablesAccountId`.+ - **`buildQboExpenseLines` (shared.ts) and `purchase-order.ts` untouched** —+ the PO keeps item-referenced `ItemBasedExpenseLineDetail` lines by design.+- `models.ts`: added `CurrencyRef` (`RefSchema`) + `ExchangeRate` (number) to+ `Qbo.BillSchema` (both optional; set on FX bills).+- Tests (`entities/__tests__/bill.test.ts`, +5): 4 pure `buildQboBillLines`+ (account-based lines to journal accounts + item label + no+ ItemBasedExpenseLineDetail + no tax; negative PPV line survives; unmapped →+ retryable UNMAPPED_ACCOUNTS Warning; no-journal → Warning) and 1+ `mapToRemote` FX drive (table-dispatching Kysely fake): EUR @ rate 2 →+ `CurrencyRef {value:"EUR"}` + `ExchangeRate: 2` + 150 EUR to the mapped+ GR/IR account only (AP excluded). The 4 pre-existing `buildQboExpenseLines`+ PO/bill tests stay green (shared builder unchanged).+- **ENV-GATED (skipped + logged):** VERIFY gate 4 (QBO account-based bill line+ to a clearing account posts + GR-IR nets to zero) and VERIFY gate 5 (QBO+ accepts a negative `Amount` on an `AccountBasedExpenseLineDetail` line) —+ both require the QBO sandbox. Per the handoff, negative lines keep flowing+ through the builder unchanged (a negative-line test asserts this); NO+ per-account netting was preemptively implemented — the sandbox check is+ pending.+- Gates: `typecheck @carbon/ee` → **pass**; `test @carbon/ee` → **487 passed+ (34 files)** (+5 vs 482).++### B-2.1 — Xero items non-tracked (done FIRST) — **done**++- `providers/xero/entities/item.ts` `mapToRemote`:+ - CREATE (no remote mapping) → `IsTrackedAsInventory: false`.+ - UPDATE (remote mapping exists) → **omit** `IsTrackedAsInventory` (Xero+ rejects untracking an item with stock/txns). Fetches the remote; if it is+ still tracked, records a Warning (untrack instructions) and **proceeds**+ with the update (name/price sync is never blocked).+ - `mapToLocal` unchanged (keeps reading the remote flag).+- **DEVIATION NOTE (non-blocking):** the plan says "land a Warning" on+ tracked-remote. `ItemSyncer` extends `BaseEntitySyncer` directly, which has+ **no structured-error preservation** (a thrown `JournalEntrySyncError`+ flattens to a Failed op) — and blocking item sync for every legacy tracked+ item would stop name/price updates. So the tracked-remote warning is a+ recorded `console.warn` (greppable) and the update proceeds. This is the+ "recorded, not silent" degradation; a genuine Warning-op would require a+ pushToAccounting override the plan doesn't call for.+- Tests: NEW `entities/__tests__/item.test.ts` (3): create → false; update+ (non-tracked remote) → field omitted; update (tracked remote) → `console.warn`+ called + field omitted.+- **ENV-GATED (skipped + logged):** VERIFY gate 2 (Xero's exact rejection shape+ for flipping a tracked item with history) — sandbox; the create-only /+ omit-on-update + warning rule ships regardless.++### B-2.2 — Xero bill → account-costed replay — **done**++- Added shared `loadAccountCodesById(db, { companyId, integration })` to+ `core/account-mapping.ts` (account.id → provider account CODE via the+ mapping `externalCode`) — mirrors the Xero journal syncer's private+ `getAccountCodesById` and Rillet's `loadRilletAccountCodesById`.+- `providers/xero/entities/bill.ts`:+ - NEW pure `buildXeroBillLineItems({ bill, costingLines, accountCodesById,+ nonTrackedItemIds })`: `AccountCode` = the journal line's mapped account+ (not `defaultPurchaseAccountCode`); `TaxType: "NONE"` + no `TaxAmount` on+ every line (dropped the old INPUT/TaxAmount); `Description =+ costingLineItemLabel(line) ?? line.description`; `ItemCode` attached ONLY+ for `nonTrackedItemIds`. Unmapped / account-less / no-journal → structured+ UNMAPPED_ACCOUNTS Warning.+ - `mapToRemote`: loads costing lines via `loadBillCostingLines`, converts+ with `toTransactionCurrencyLines`, keeps `CurrencyCode` + pins+ `CurrencyRate` on FX; **omits `SubTotal`/`TotalTax`/`Total`** (Xero+ computes from the NONE-taxed lines — avoids a tax-inclusive conflict).+ Added a `shouldSync` (posted-status; Draft skipped) + a **paid-doc guard**:+ re-pushing a `Paid`/`Partially Paid` bill throws the new `DOC_HAS_PAYMENTS`+ Warning (Xero rejects edits to a bill with payments) instead of a line+ rewrite. Added `getAccountCodesById` + `getPayablesAccountId`.+ - Added `DOC_HAS_PAYMENTS` to `JOURNAL_ENTRY_SYNC_ERROR_CODES` (posting.ts).+- **`ItemCode` decision (v1, documented):** `nonTrackedItemIds` is passed+ `undefined` from the syncer, so no bill line gets `ItemCode` in production —+ proving a Xero item is non-tracked needs a live per-item fetch (env-gated),+ and attaching `ItemCode` for a *tracked* item would double-post inventory.+ The pure builder fully supports the set (tested with a non-empty set), so the+ behavior is future-ready; the account-costed lines carry the item in+ `Description`. Same deviation as B-2.1: a thrown Warning flattens (Xero+ syncers have no structured-error preservation) — greppable message ships.+- Tests: NEW `entities/__tests__/bill.test.ts` (8): 6 pure `buildXeroBillLineItems`+ (journal account codes + TaxType NONE + item label + ItemCode-only-for-+ non-tracked + ItemCode-omitted + negative line + unmapped Warning + no-journal+ Warning) and 3 `mapToRemote`/`shouldSync` drives (FX EUR@2 → `CurrencyRate: 2`+ + 150 EUR to GR/IR only + no totals; paid-doc → DOC_HAS_PAYMENTS Warning;+ Draft → shouldSync skip).+- **ENV-GATED (skipped + logged):** VERIFY gate 3 (Xero ACCPAY honors+ AccountCode + TaxType NONE on a line → GR-IR clears, no tax added) — sandbox.++### B-2.3 — Xero invoice → item's revenue account — **done**++- `providers/xero/entities/invoice.ts`: line `AccountCode` now resolves to the+ item's mapped REVENUE account — `accountDefault.salesAccount` → the+ account-mapping `externalCode` (new `getSalesAccountCode`, cached per+ instance), the same resolution feeding Rillet's product `account_code` /+ QBO's `IncomeAccountRef`. Falls back to `defaultSalesAccountCode` ONLY when+ the sales account is unset or unmapped (AR sync never blocked). `ItemCode` ++ tax handling (`OUTPUT`/`NONE`, `LineAmountTypes: "Exclusive"`) unchanged.+- Tests: NEW `entities/__tests__/invoice.test.ts` (2): mapped sales account+ "4000" used (not the default "9999"), item + tax unchanged; fallback to+ "9999" when `salesAccount` is null.++### Part B running gate++- `typecheck @carbon/ee` → **pass**; `test @carbon/ee` → **500 passed+ (37 files)** (471 baseline + 29 new; 0 regressions).++## Final report++_(filled at end of run)_diff --git a/.ai/runs/2026-08-11-sync-robustness-run.md b/.ai/runs/2026-08-11-sync-robustness-run.mdnew file mode 100644index 0000000000..09f1c51753--- /dev/null+++ b/.ai/runs/2026-08-11-sync-robustness-run.md@@ -0,0 +1,149 @@+# Run record — accounting sync delivery robustness (v4)++Spec: `.ai/specs/implemented/2026-08-11-accounting-sync-delivery-robustness.md` (approved 2026-08-11)+Branch: `feat/rillet` — all work uncommitted, verification per phase below.++## Phase 0 — converged subscriptions + truthful ledger ✅ (code-verified)++- `packages/ee/src/accounting/core/subscriptions.ts` (NEW): `REQUIRED_SYNC_SUBSCRIPTIONS`+ per provider (journal everywhere; payment Rillet-only; address dropped as a dead+ letter) + idempotent `ensureProviderSubscriptions` convergence (create RPC upserts;+ extras deleted). Exported via the accounting barrel.+- Install hooks rewritten to convergence: rillet/xero/quickbooks `hooks.server.ts`+ (QBO's no-op install hook was stale — its syncers shipped); `quickbooksOnUninstall`+ added. New `onUpdate` hook (`packages/ee/src/types.ts`, registry in+ `packages/ee/src/hooks.server.ts`) re-converges on every settings save of an+ installed integration; wired in `apps/erp/app/routes/x+/settings+/integrations.$id.tsx`.+- Truthful ledger: `skipOperation` in `core/operations.ts`; drain closes via new+ `getSyncOperationCloseDecision` (skip+remoteId→Completed; skip w/o→Skipped w/ reason;+ push success w/o remoteId→Failed POSTCONDITION). `Skipped→Pending` transition allowed+ (guard table + operations.test + SyncActivity retry).+- Invariant test `packages/jobs/.../events/subscriptions-mapping.test.ts`: every+ subscribed table ↔ `TABLE_TO_ENTITY_MAP` (moved to import-light `sync-tables.ts`,+ `salesOrder` mapping added — was a dead Xero subscription) ↔ registered syncer.++## Phase 1 — outbound reconciliation sweep ✅ (code-verified; live-heal pending)++- `packages/jobs/.../integrations/accounting-outbound-sweep.ts` (NEW), cron+ `15,45 * * * *` (offset from pull sweep), registered in both indexes. Per active+ integration: subscription convergence → journal completeness diff (I1, same policy+ routing as backfill, 7-day `SWEEP_LOOKBACK_DAYS` window raised by syncFromDate) →+ bill/invoice diff (`shouldEnqueueMissingDocument`: no mapping + no live op + latest+ null/Completed; parked statuses excluded) → payment diff (Rillet, no-op-rows only) →+ re-drive Warning UNMAPPED_ACCOUNTS bills whose posted PI journal now exists+ (`MAX_REDRIVE_ATTEMPTS = 5`) → drain (gives Xero its first periodic drain).+- Pure helpers + tests live in `accounting-sync-operations.ts/.test.ts`.+- **Pending (needs running stack)**: observe the sweep heal `je_9G1UYT9VXmBgMrvqtyTq5t`+ and `pi_RhnzjmMsWURrWC92Ma4ocP` (company `d9oi7og780h02mltro10`), which also+ backfills that company's missing journal/payment subscriptions via convergence.++## Phase 2 — ordering, cooldown, idempotency ✅ (code-verified)++- Status transitions bypass the cooldown: `isStatusTransitionEvent` routes generic+ UPDATE transitions onto the non-cooldown "posting" trigger in `events/sync.ts`.+ **Spec deviation (D.1)**: post-route event emission NOT moved — evidence showed the+ post edge fn already emits the invoice's Pending→Open UPDATE after the journal+ insert; the loss was the false-Completed cooldown swallowing it. Truthful ledger ++ transition bypass + sweep close F5 without touching the posting flow.+- Rillet idempotency keys entity-scoped (payload no longer hashed) —+ `buildRilletIdempotencyKey` + 8 call sites; provider.test updated to pin the new+ contract (payload drift must NOT mint a fresh key).+- `MAX_SYNC_OPERATION_ATTEMPTS = 10` cap in the drain → `ATTEMPTS_EXHAUSTED` Failed.+- Batch/single push preserves structured `JournalEntrySyncError` failures+ (`toSyncResultError` in `core/types.ts`) so Warnings stay Warnings with metadata.+- **Deferred to sweep coverage (F7)**: mid-flight absorption unchanged — the partial+ unique live index forbids a second live row; the sweep re-diffs within 30 min.++## Verification (all green as of this run)++- `pnpm --filter @carbon/ee test` → 530 passed+- `pnpm --filter @carbon/jobs test` → 431 passed+- `turbo typecheck --filter=@carbon/ee --filter=@carbon/jobs --filter=erp` → clean+- `pnpm run lint` → clean++## Phase 3 — tie-out + period-close gate ✅ (live-verified 2026-08-11)++- Migration `20260811223145_accounting-sync-tieout.sql`: `accountingSyncTieOut` table+ (single-col FK to accountingPeriod — its PK is `(id)`, the v3 spec's composite FK was+ invalid), RLS SELECT accounting_view, cell-unique upsert index; + idempotent reconcile+ of the 'External GL sync complete' periodCloseTaskDefinition (Auto/'external-gl-sync'/+ Blocker) for existing companies; seed.data.ts entry for new companies.+- `accounting-reconciliation.ts` rewritten: provider-agnostic (all three providers, was+ Xero-only) via new `core/remote-journal.ts` `fetchRemoteJournalTotals` (per-provider+ debit-signed line sums); presence check kept; monthly-aggregate check replaced by+ per-period × per-account tie-out cells (dispositions bucketed least-delivered-first;+ DOC_BACKED delivered only while the backing document is Completed/mapped; provider+ sums strictly reuse presence fetches).+- ERP: `x+/accounting+/sync-tieout.tsx` + `$cellId` drawer drill-down, SyncTieOutTable,+ nav item (Reports), path helpers; `getPeriodExternalGlSyncReadiness` wired into+ `computePeriodReadiness` as the 'external-gl-sync' Blocker auto-check; SyncActivity+ tie-out summary card + Failed/Warning count badge on the Sync Activity tab.++## Phase 4 — alerting, dead-letter, scoped suppression ✅ (live-verified 2026-08-11)++- Migration `20260811224732_scoped-sync-trigger-suppression.sql`: dispatch_event_batch+ now suppresses only SYNC/WEBHOOK/WORKFLOW during sync writes (loop/echo-prone);+ SEARCH/AUDIT/EMBEDDING observers see sync-written rows (F13).+- Queue drainer: unknown-handlerType messages archive to pgmq's dead-letter+ (`pgmq.a_event_system`) instead of crash-looping the whole drain (F8).+- `NotificationEvent.IntegrationSync`: the outbound sweep notifies the integration's+ configurer (in-app) when a drain fails ops; Topbar rendering links to the+ integration's settings page.++## Live verification (dev stack, company d9oi7og780h02mltro10, 2026-08-11 evening)++The 22:45 sweep cron self-healed the original incident with zero manual intervention:+- Subscriptions converged: `journal` + `payment` added, dead `address` removed.+- `je_9G1…` (fixed-asset Purchase Receipt journal): discovered, enqueued, drained →+ **Warning UNMAPPED_ACCOUNTS** with an actionable message (the Machinery & Equipment+ account has no Rillet mapping — user maps it, retries, done). Silence → visibility.+- `pi_Rhnz…` (phantom-Completed fixed-asset bill): re-detected via the+ Completed-no-mapping signature, re-pushed → **Completed, Rillet external id+ `019ff3db-f318-72ce-bd69-886764cfdaa1`** — the bill now exists in the Rillet sandbox.+- 3 more journals pushed Completed; 5 recorded Excluded DOC_BACKED (spec I1 total).+- The 23:15 sweep enqueued nothing — the diff is convergent.+- Payment push surfaced a REAL latent bug (`.slice` on a pg-driver Date) — fixed via+ `toPostingDateString`; retry then reached Rillet and got a genuine provider response+ (400 Constraint Violation on create bill payment — the VERIFY-flagged endpoint, see+ Follow-ups). The failure fired the **integrationSync in-app notification** ✅.+- Tie-out (invoked via Inngest): 5 cells, **internalDelta = 0 on every cell**,+ **externalDelta = 0** on both provider-fetched cells — I1 + I5 hold live.+- Migrations applied + `generate:types` regenerated (via crbn migrate); full suite+ green after regen: ee 537 + jobs 458 tests, 4 typechecks, lint.++## Follow-ups++- Rillet `create bill payment` returns 400 Constraint Violation (sandbox) — the+ Phase G VERIFY gate; needs payload/endpoint verification against Rillet support docs.+- Map the Machinery & Equipment (and any other asset) account in the Rillet account+ mapping, then Retry the je_9G1 Warning op.+- Consider a Rillet field-mapping for `journalEntry` on the tie-out drill-down (nice-to-have).++## Pre-commit TODO++- Update `.claude/rules/accounting-sync-handlers.md` (+ `packages/ee/AGENTS.md`,+ `packages/jobs/AGENTS.md`) for: subscriptions convergence, Skipped semantics,+ outbound sweep, idempotency-key contract — same PR as the code, per+ keep-sources-in-sync.++## v5 — reconciler unification ✅ (2026-08-12, spec Steps A–D)++Spec: `.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md` (implemented).++- **Step A** — `reconcile-golden.test.ts`: 26-scenario golden matrix pinning the+ legacy→state-shaped translation; FIX-1..4 document every deliberate difference+ (no Draft/mid-posting churn; changed-since-failure retry; updatedAt-vs-+ lastSyncedAt replaces the cooldown; no void-echo enqueue).+- **Step B** — `reconcile.ts` (pure `computeReconcileDecision`; journal policy via+ the extracted shared `planJournalPostingFromState`) + `reconcile-executor.ts`+ (batch-first `reconcileEntities`, one query per concern per type, trigger+ `"reconcile"` — migration `20260812093418` widened the CHECK); the outbound+ sweep now pages candidate refs and delegates every decision.+- **Step C** — `events/sync.ts` is a hint dispatcher: table→ref→`reconcileEntities`+ →drain. No per-table branches, no cooldown on this path, no transition routing.+- **Step D** — deleted `isStatusTransitionEvent` + `getPaymentPushDecision` (+ 11+ legacy tests, superseded by the golden matrix); rule + jobs AGENTS.md updated;+ spec changelog records the two deviations (cooldown survives ONLY on the+ inbound/webhook entry points; changed-since-failure document retry).+- Verification: jobs 473 + ee 537 tests, typecheck jobs/ee/erp clean, migration+ applied to the dev DB (CHECK includes 'reconcile').diff --git a/.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md b/.ai/specs/2026-08-12-accounting-sync-reconciler-unification.mdnew file mode 100644index 0000000000..eb1a11f5cb--- /dev/null+++ b/.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md@@ -0,0 +1,208 @@+# Accounting Sync — Reconciler Unification (v5)++**Status:** implemented (2026-08-12, Steps A–D) — see the changelog at the+bottom for the two implementation deviations.+**Date:** 2026-08-12+**Builds on:** the v4 delivery-robustness work (implemented, live-verified; its spec was+removed 2026-08-13 — the behavior now lives in `.claude/rules/accounting-sync-handlers.md`+and git). AR/AP document representation:+`.ai/specs/implemented/2026-08-05-accounting-document-representation.md`. The AR/AP+journal-families mode (formerly v3 Phase 4) is now owned by+`.ai/plans/2026-08-13-accounting-sync-automated-postings-only.md`.++## Why this spec exists++v4 made outbound sync correct, truthful, and provable. It did so by hardening+**two independent decision systems** that must always agree:++1. **The event path** — per-table enqueue decision trees+ (`planJournalPostingOperation`, `getPaymentPushDecision`, the generic+ INSERT/UPDATE rule), cooldown semantics (`SYNC_OPERATION_COOLDOWN_MS`,+ `isCooldownTrigger`), the transition bypass (`isStatusTransitionEvent` →+ `posting` trigger), live-row absorption rules.+2. **The sweep** — its own diff rules (`shouldEnqueueMissingDocument`,+ `getSweepFloorDate` windows, journal-coverage checks, the capped+ `UNMAPPED_ACCOUNTS` re-drive).++Every v4 failure class was, at root, a gap or disagreement between those two+brains, and every v4 fix added another rule to keep them agreeing. The+agreement is enforced today by care and tests, not by construction. Adding+entity #12 or provider #4 means wiring both paths correctly; a future change+can break the agreement without any single test noticing.++**The unification:** adopt the level-triggered controller model (the+Kubernetes lesson). One idempotent reconcile decision — *"what should exist+remotely for this entity, does it, act once"* — computed by ONE pure function.+Events stop carrying decisions and become wake-up hints ("reconcile this+entity now"); the sweep becomes "reconcile everything in the window"; a UI+retry becomes "reconcile this entity now". The cooldown, transition+detection, absorption semantics, and phantom-repair rules stop being code and+become emergent properties of an idempotent reconcile.++This is a **refactor of transport, not behavior**: the posting policy,+document representation, dimensions, tie-out, and every I1–I5 invariant are+unchanged. The 995-test suite v4 left behind is the safety net that makes it+feasible.++## Goal++- One decision function; the event path, the sweep, backfill, and UI retry+ are four callers of it.+- Net deletion of special-case code (cooldown branching, per-table enqueue+ trees, transition routing, sweep-only diff rules).+- Adding an entity type or provider requires implementing "desired remote+ state" + "push it" — correctness comes from the loop, not from each path.++## Non-goals++- No change to POSTING_POLICY, doc-backed representation, families modes+ (v3 Phase 4 stays parked), dimensions, tie-out, or the close gate.+- No change to the `accountingSyncOperation` ledger schema — it remains the+ durable journal of reconcile outcomes and the UI surface.+- No change to inbound sync (pull sweep/webhooks) — already single-brained.+- No latency regression: event-triggered reconciles still land in seconds.++## Design++### D1 — The pure decision core++```+computeReconcileDecision(input: {+ entityType, entityId,+ entitySnapshot, // status/postingDate/sourceType… (per-type shape)+ mapping, // externalIntegrationMapping row | null+ latestOperation, // newest ledger op for the tuple | null+ liveOperation, // Pending/In Flight op | null+ policy, syncConfig, // POSTING_POLICY + resolved entity config+}): ReconcileDecision+```++`ReconcileDecision` = `enqueue-push` | `record-terminal (Excluded/Warning ++code)` | `re-drive (existing op → Pending)` | `nothing (+ reason)`.++Pure, import-light, exhaustively unit-tested. It subsumes, in one place:+`planJournalPostingOperation`'s policy routing, `getPaymentPushDecision`'s+transition gate (recast as state: "Posted payment with no op"), the generic+push rule, `shouldEnqueueMissingDocument`, and the re-drive conditions.+The v4 rules become table rows in ONE function instead of guards in five+files.++### D2 — The executor++`reconcileEntity(ctx, ref)` loads the inputs (one snapshot query per type —+the loaders already exist across the sweep/backfill), calls the decision,+and applies it through the EXISTING ledger primitives (`enqueueSyncOperation`+with a new trigger `"reconcile"`, `insertTerminalSyncOperation`,+`transitionOperation`). Draining stays batched and unchanged — reconcile+decides *whether* work exists; the drain still executes it in grouped syncer+batches with the truthful close.++### D3 — Events become hints++`events/sync.ts` shrinks to: map table→entityType (`sync-tables.ts`,+unchanged), collect distinct `(entityType, entityId)` refs from the batch,+call `reconcileEntity` for each, drain. Deleted outright:++- the cooldown decision at enqueue time (`shouldSkipForCooldown` and the+ `isCooldownTrigger` split) — burst coalescing is already provided by+ live-row absorption + the event batch's distinct-refs dedupe; a+ just-Completed entity reconciles to `nothing` because state says so,+ and a *changed* entity reconciles to `enqueue` — the F4 class becomes+ unrepresentable instead of specially handled;+- `isStatusTransitionEvent` routing (no cooldown to bypass);+- the journal/payment special-case branches (their logic lives in D1).++### D4 — The sweep becomes a window walk++`accounting-outbound-sweep.ts` keeps its orchestration (subscription+convergence, window paging, end drain, notification) but its per-entity+logic becomes "call `reconcileEntity`". `shouldEnqueueMissingDocument`,+the journal coverage check, and the re-drive block all fold into D1.+`getSweepFloorDate`/`SWEEP_LOOKBACK_DAYS` remain (they scope the walk, not+the decision).++### D5 — What is explicitly kept++- The ledger + truthful close (`getSyncOperationCloseDecision`) — reconcile+ decides intake; close stays the outcome recorder.+- Consolidation hold (daily-summary journal ops for the cron).+- `MAX_SYNC_OPERATION_ATTEMPTS`, `MAX_REDRIVE_ATTEMPTS` (inputs to D1).+- Idempotency keys, entity-scoped Rillet Idempotency-Key, JIT+ `ensureDependencySynced`.++## Migration plan (each step independently shippable, tests green throughout)++- **Step A — Golden decisions.** Before touching anything, capture the+ CURRENT behavior as a golden test matrix: for a grid of (entity state ×+ ledger state × mapping state × config), record what today's event path and+ sweep each decide. This pins parity and is the refactor's contract.+- **Step B — Extract D1.** Implement `computeReconcileDecision` against the+ golden matrix. The sweep adopts it first (lower blast radius; the sweep+ already runs after the event path and is convergent by design).+- **Step C — Event path adopts it.** `events/sync.ts` delegates; delete the+ per-table branches and cooldown/transition special-casing. The `posting`+ vs `event` trigger distinction collapses into `reconcile`.+- **Step D — Delete dead code + docs.** Remove the superseded helpers, their+ tests migrate to D1's suite; update `accounting-sync-handlers.md` and both+ AGENTS.md files in the same PR.++## Companion quick wins (separate work items, not gated on the refactor)++1. **Nightly provider contract tests (env-gated).** Rillet publishes no+ OpenAPI; several endpoints were built from inference, and the+ `payment_date`→`date` 400 proved the risk class. A small vitest suite+ (skipped unless `RILLET_SANDBOX_API_KEY` is set) that creates and reads+ back each document type against the sandbox nightly, asserting shapes,+ catches provider drift before customers' books do.+2. **One sync-lag number.** Per integration: age of the oldest+ Posted/posted-document entry with no terminal disposition. Surface it on+ the integration card and the Sync Activity tab; alert past a threshold+ (reuse `NotificationEvent.IntegrationSync`). The tie-out proves+ correctness after the fact; this says *right now* whether the engine is+ keeping up.++## Decisions taken (surface for veto)++1. **Level-triggered core with events as hints** — vs. keeping two hardened+ paths. Rationale: every v4 failure class was a two-brain disagreement;+ one brain makes the class unrepresentable and shrinks the code.+2. **Delete the completed-row cooldown outright** (D3) rather than porting+ it — an idempotent reconcile makes it redundant; live-row absorption and+ batch dedupe already bound provider-call volume.+3. **Golden-matrix parity testing before refactor** (Step A) — the refactor+ ships only behind proof that decisions are unchanged (modulo classes we+ deliberately fix, each called out in the matrix).+4. **Drain stays batched** — reconcile is per-entity, execution is batched;+ we do not trade away syncer batch efficiency.+5. **New trigger value `"reconcile"`** on ledger rows (additive enum-free —+ `trigger` is a zod enum in code; widen it) so provenance stays visible in+ Sync Activity.++## Verification++- Step A golden matrix green before and after each step.+- Full existing suites (ee 537 / jobs 458 at time of writing) stay green.+- Chaos check on the dev stack: drop a subscription, post an invoice, kill+ an event mid-flight — assert convergence within one sweep, as v4's run+ record demonstrated (`.ai/runs/2026-08-11-sync-robustness-run.md`).+- Latency check: event→remote push still completes in seconds on the dev+ stack.++## Changelog++- **2026-08-12 — implemented (Steps A–D).** `reconcile.ts` (decision core) ++ `reconcile-executor.ts` (batch executor) + `reconcile-golden.test.ts` (26+ scenarios incl. FIX-1..4); the sweep and `events/sync.ts` both delegate;+ `isStatusTransitionEvent` and `getPaymentPushDecision` deleted; journal+ policy extracted to the shared `planJournalPostingFromState`; trigger+ `"reconcile"` added (migration `20260812093418`). Deviations from the+ draft:+ 1. **D3/Decision 2 (cooldown):** deleted from the outbound path as+ specced (reconcile is never cooldown-gated), but the completed-row+ cooldown REMAINS on the inbound/webhook entry points+ (`sync-external-accounting`, pull-sweep enqueues) — inbound is a+ non-goal here and doesn't route through the reconciler.+ 2. **D1 refinement:** a parked Failed/Warning document re-enqueues when+ the row changed after the failure (`updatedAt > op.createdAt`) —+ preserves the event path's fix-the-data-and-save retry without its+ retry-on-any-touch churn (golden FIX-2).diff --git a/.ai/specs/implemented/2026-08-05-accounting-document-representation.md b/.ai/specs/implemented/2026-08-05-accounting-document-representation.mdnew file mode 100644index 0000000000..ac4b3096e8--- /dev/null+++ b/.ai/specs/implemented/2026-08-05-accounting-document-representation.md@@ -0,0 +1,411 @@+# Accounting Document Representation — Journal-Replay Bills, Item-Referenced Invoices, Non-Tracked Provider Items++> Status: implemented — executed 2026-08-05 as **Part B** of the accounting handoff run+> (execution plans removed 2026-08-13; see git history). Sandbox-gated acceptance items remain+> env-gated; the tie-out acceptance criterion shipped with the delivery-robustness work (see the+> note in Acceptance Criteria).+> Author: Brad Barbin + Claude+> Date: 2026-08-05+> Research: provider-capability survey (2026-08-05, this session) + codebase audit of all+> transaction syncers; provider GL-behavior facts flagged VERIFY where inferred from API docs+> rather than observed on a sandbox.+> Related: the posting policy + journal push are documented in+> `.claude/rules/accounting-sync-handlers.md` (the v2 engine and v3 journal-policy specs were+> removed 2026-08-13; see git). This spec fixes how AR/AP **documents** represent their lines;+> it does not change the posting policy or the journal push.++## TLDR++When Carbon pushes a bill or invoice to an external accounting system (QuickBooks Online,+Xero, Rillet), the document's **lines must post to exactly the accounts Carbon's own posting+journal for that document already computed** — nothing more. Today only Rillet's bill syncer+does this (it account-costs from the posted Purchase Invoice journal, hitting GR/IR clearing);+QBO and Xero bills instead reference the **item**, which posts to the item's own account+(COGS / Inventory), leaving GR/IR uncleared and **double-counting cost** against the separately+pushed receipt journal. This spec establishes one principle across all providers —+**a provider document reproduces its Carbon posting journal (document GL ≡ Carbon journal, by+construction)** — with a deliberate AR/AP asymmetry: **AP bills are account-costed journal+replays** (the item is a line label, never a GL driver), **AR invoices are item-referenced**+(the item's revenue account *is* what the invoice should post; COGS stays with the shipment+journal), and **provider items are pushed Non-Inventory / non-tracked everywhere** so the+provider never does inventory or COGS — Carbon owns those. Rillet is already the reference+implementation for both halves; the work is generalizing its bill-costing into a shared core+and bringing QBO and Xero (and Xero's item sync) into line.++## Problem Statement++### The bug: item-referenced bills double-count cost and never clear GR/IR++Carbon is a manufacturing ERP: **Carbon owns inventory and manufacturing costing**, the+external system is the financial books of record. An inventory purchase is a two-step GL flow:++| Event | Carbon journal | Reaches provider via |+|---|---|---|+| **Receipt** (goods arrive) | Dr Inventory / Cr GR-IR | pushed journal (`Purchase Receipt`, `representation: journal`, `defaultEnabled: true`) |+| **Bill** (invoice arrives) | Dr GR-IR (+ PPV, tax) / Cr AP | the **bill document** (`Purchase Invoice`, `representation: document`, DOC_BACKED — the journal is *not* pushed) |++The bill's job is to **clear GR-IR** against the receipt. That only happens if the bill's+lines post to **GR-IR** (and PPV/tax) — i.e. reproduce the Purchase Invoice journal. Current+state (audited 2026-08-05):++| Provider · doc | Line representation today | Correct? |+|---|---|---|+| **Rillet · bill** | account-costed replay of the posting journal → GR-IR | ✅ correct (this is the model) |+| **Rillet · invoice** | item-referenced (`product_id`, product's `account_code` = sales) | ✅ correct |+| **QBO · bill / PO** | `ItemBasedExpenseLineDetail{ItemRef}` for item lines → posts to the item's expense/asset account | ❌ posts to COGS/inventory, GR-IR never clears, **cost double-counted** vs the receipt journal |+| **QBO · invoice** | `SalesItemLineDetail{ItemRef}` → item's income (revenue) account | ✅ correct (revenue is the invoice's job) |+| **Xero · bill** | `ItemCode` + blunt `defaultPurchaseAccountCode`; for **tracked** items Xero force-posts the item's Inventory Asset account and ignores `AccountCode` | ❌ GR-IR uncleared + **inventory double-counted** for tracked items |+| **Xero · invoice** | `ItemCode` + always `defaultSalesAccountCode` | ⚠️ posts to a single default, not the item's real revenue account; tracked items also double-count COGS |++### Provider capability facts that force the design (2026-08-05 survey)++| | Item ref on a line? | Item + independent GL-account override on the same line? |+|---|---|---|+| **QBO** | yes | **no** — an item line's account is the item's config; no per-line override |+| **Xero** | yes (`ItemCode`) | **yes for non-tracked**; for **tracked** items Xero ignores `AccountCode` and posts to Inventory Asset |+| **Rillet** | **bills: none** (account_code + amount only); invoices: product-based | bills: n/a; invoices: GL only via nested `revenue.account_code` |++Consequences: you **cannot** attach an item to a QBO bill line and independently direct its GL,+and a **tracked** Xero item hijacks the GL regardless of what you send. So an item reference on+a *purchase* document cannot be made to hit GR-IR — item references and GR-IR clearing are+mutually exclusive on the purchase side.++## Proposed Solution++### The principle++> **A provider document posts to exactly the accounts Carbon's posting journal for that+> document computed.** Then the provider's GL for the document equals Carbon's GL for it *by+> construction* — correct on every provider regardless of item/tax/inventory quirks. Item+> identity rides as a line **label** (description; plus a no-side-effect structured reference+> where a provider supports one), never as a structural driver of the GL account. Provider+> **items are Non-Inventory / non-tracked**, so the provider never posts inventory or COGS —+> Carbon owns those via its pushed journals.++This is tautological correctness: you cannot drift from Carbon's books because the document+*is* a replay of them. It also unifies item lines, G/L-account lines, and variance lines —+the journal already contains all of them, so the document builder never branches on line type.+*(Corrected 2026-08-05 review: tax is NOT a journal line — Carbon's purchase posting folds tax+into line cost, so replay lines already embed it and are pushed tax-neutral; see §1c.)*++### The AR/AP asymmetry (why "just add items" is wrong for bills but fine for invoices)++Purchases are a **two-step** flow with a clearing account (receipt → bill); the bill's job is+to clear GR-IR, which is *not* the item's account. Sales revenue is **single-step**: the+invoice books Dr AR / Cr Revenue, and COGS/inventory come *separately* from the pushed+`Sales Shipment` journal. So the item's natural account aligns with the document's job for AR+(revenue) but not for AP (clearing). Hence:++1. **AP bills → account-costed journal replay** (item as label).+2. **AR invoices → item-referenced** to the item's revenue account (COGS stays with the+ shipment journal).+3. **Non-posting documents (PO, SO, Xero Quote) → item-referenced, unchanged** — they don't+ post to the GL, so there is no correctness constraint and item detail is pure benefit.+4. **Provider items → Non-Inventory / non-tracked everywhere** — the single guard that stops+ the provider from posting inventory (bills) or COGS (invoices) behind our back.++### 1. AP bills — generalize Rillet's journal-replay into a shared core++Rillet's `mapBillToRilletBill` / `fetchPostingJournalLines` / `filterBillCostingLines`+(`providers/rillet/entities/bill.ts`) already implement the correct model: the bill items are+the posted `Purchase Invoice` journal's lines (debit-signed) minus the AP control line, each+mapped to a provider account through the account-mapping. Extract this into a shared+**`core/document-costing.ts`**:++- `loadBillCostingLines(db, { companyId, billId, payablesAccountId }) → CostingLine[]`+ (`{ accountId, amount (debit-signed), description, sourceItemId?, dimensions? }`), reading the+ posted Purchase Invoice journal and excluding AP control lines — one implementation, three+ consumers.+- **Item label enrichment (the visibility win):** *(join corrected 2026-08-05 review)* the+ journal reference is **not** the invoice-line id: `post-purchase-invoice` stamps+ `journalLine.documentLineReference = 'purchase-invoice:<purchaseOrderLineId>'` (prefixed,+ **PO-line**-keyed) and stamps **nothing** for direct no-PO invoice lines. The join is+ strip-prefix → `purchaseOrderLine.id` → `purchaseOrderLine.itemId` → item code/name;+ **direct (no-PO) invoice lines get no label in v1** (`sourceItem: undefined`, description+ falls back to the journal line description; optional out-of-scope follow-up: stamp+ references for direct lines in the edge fn). Journal lines are built per invoice line (one+ GR-IR line each, never aggregated per account), so per-line labels are structurally sound.+ Providers put the label in the line **description** (Rillet, QBO) and, where safe, a+ structured reference (Xero `ItemCode` on a non-tracked item, alongside the GR-IR+ `AccountCode`). Variance/rounding lines have no source item — fine.+- Providers become thin adapters over `CostingLine[]`:+ - **Rillet** — unchanged behavior; refactored onto the shared loader (+ item in description).+ - **QBO bill** — emit **`AccountBasedExpenseLineDetail`** lines (`AccountRef` = mapped GR-IR/PPV account, `Description` = item label). Stop using `ItemBasedExpenseLineDetail` on bills. *(Resolved 2026-08-05 review: the **PO stays on the existing item-referenced `buildQboExpenseLines`** — it is non-posting (§4); do not touch the shared builder.)*+ - **Xero bill** — emit `LineItem{ AccountCode = mapped account, Description, TaxType: "NONE", ItemCode? }`,+ where `ItemCode` is included only when the item is known non-tracked (see §3 rollout rule).++Unmapped/absent account and unposted-journal handling stays exactly as Rillet's today+(structured `UNMAPPED_ACCOUNTS` Warning — park, never guess an account).++**Posted-status gate (added 2026-08-05 review):** none of the three bill syncers has a+`shouldSync` today — Xero even maps Carbon `Draft` → Xero `DRAFT`. Under journal replay a+Draft bill has no posted journal, so every Draft-bill sync would land an `UNMAPPED_ACCOUNTS`+Warning (ledger noise). All three bill syncers gain a posted-status `shouldSync` mirroring the+invoice syncers' `SYNCABLE_STATUSES` (which exclude Draft). Deliberate behavior change:+QBO/Xero stop receiving Draft bills — the provider is the books of record; drafts never+belonged there.++### 1b. Currency — replay in transaction currency with a pinned rate (added 2026-08-05 review)++The journal is always **base currency**, but the bill document must carry the vendor's+transaction currency (Xero sends `CurrencyCode` + `CurrencyRate`; the vendor invoice total is+a transaction-currency number). The shipped Rillet mapper has this latent bug today: it pushes+base-currency journal amounts **labeled with the transaction currency** and omits+`exchange_rate`. Under FX, "document GL ≡ Carbon journal" only holds if the provider's rate is+pinned to Carbon's. Resolution:++- `loadBillCostingLines` returns **base-currency** debit-signed amounts (journal truth) plus+ the invoice's `currencyCode` and `exchangeRate`.+- A shared helper converts to transaction currency: `txnAmount = baseAmount / exchangeRate`,+ 2dp-rounded, rounding residue balanced into the largest-|amount| line so the lines sum+ exactly to the invoice's transaction-currency total.+- Every provider pins the rate: Xero `CurrencyRate = exchangeRate`, QBO `ExchangeRate =+ exchangeRate` + `CurrencyRef` (fields added to the QBO Bill payload schema — today it sends+ neither), Rillet `exchange_rate = exchangeRate` (`BillSchema` already allows it). Provider+ base GL = Carbon GL up to rounding.+- Base-currency bills (`exchangeRate === 1`): behavior identical to today.++### 1c. Tax — replay lines are tax-neutral in v1 (added 2026-08-05 review)++Carbon's purchase-invoice posting creates **no tax journal line** — tax is folded into line+cost. Replay lines therefore already embed tax in their amounts, and the provider's tax engine+must not run on top of them: Xero bill lines get `TaxType: "NONE"` (today the Xero bill sends+`TaxType: "INPUT"` + `TaxAmount`, which would double-tax replayed amounts), QBO bills stay+tax-free (no `TxnTaxDetail` — unchanged), Rillet items never set `tax_rate` (unchanged).++**Documented consequence:** input VAT/GST on Carbon-pushed bills does **not** appear on the+provider's tax reports — the same stance as pushed manual journals today. Fine for US+sales-tax-as-cost; a real limitation for VAT-reclaim jurisdictions. Tax-aware mapping is an+explicit follow-up, not v1. AR invoices are unaffected (Xero keeps its existing+`TaxType: "OUTPUT"` computation — the invoice is item-referenced, not a replay).++### 2. AR invoices — item-referenced to the item's revenue account++Keep the item-referenced model (Rillet already requires `product_id`; QBO already uses+`SalesItemLineDetail{ItemRef}` → the item's `IncomeAccountRef`). The one gap is **Xero**, whose+invoice lines currently use a single `defaultSalesAccountCode`:++- **Xero invoice** — send `ItemCode` (item label/detail) **+ `AccountCode` = the item's mapped+ revenue account**, instead of the blunt default. *(Source resolved 2026-08-05 review: the+ item's mapped sales account — the same resolution that feeds QBO `IncomeAccountRef` and+ Rillet's product `account_code` — NOT the posted journal line. The two diverge only when+ sales posting groups vary by customer group; that divergence is inherent to the+ item-referenced AR decision, applies equally to QBO/Rillet, and the v3 tie-out flags it if+ material.)* Non-tracked items (§3) mean Xero honors the `AccountCode` and posts only+ Dr AR / Cr Revenue — COGS remains with the pushed shipment journal.+- Rillet / QBO invoices: unchanged.++*(A future option — AR invoices as account-costed journal replays for full uniformity — is+rejected here: Rillet invoices are structurally product-based, item-referenced AR is correct,+and it preserves richer AR subledger detail in the provider.)*++### 3. Provider items — Non-Inventory / non-tracked everywhere++The single guard that makes §1 and §2 safe. QBO already does this (`Type: Service | NonInventory`,+**never Inventory** — the documented double-COGS guard). Bring the others in line:++- **Xero item** — push `IsTrackedAsInventory = false` (today it is+ `itemTrackingType !== "None"`, so most manufacturing parts push as tracked, which is the root+ of the Xero double-count). Carbon owns inventory; Xero must not. **Rollout rule (resolved+ 2026-08-05 review):** send `false` on **create**; on **update** of an existing item, omit+ the field (Xero rejects flipping tracked→non-tracked while the item has transactions/stock),+ and if the remote item is still tracked, land a `Warning` instructing manual untracking+ (zero the stock, untrack in Xero, retry). Bill lines attach `ItemCode` only when the item is+ known non-tracked. *(Still the highest-risk change — it alters how Xero books item+ documents — and is the reason the Xero bill/invoice fixes are safe.)*+- **Rillet** — products are already revenue objects, not inventory; no change.++### 4. Non-posting documents (PO, SO, Quote)++Purchase Orders (QBO, Xero) and Xero Quotes (Carbon `salesOrder`) do **not** post to the GL —+they are commitments. Item references there are safe and desirable (detail), so they stay+item-referenced. No change required for GL correctness; they benefit passively from §3+(non-tracked items) removing any latent posting side effect. Rillet has no PO/SO objects.++### Where inventory valuation lives (design decision, not a limitation)++- **Financial / GL-level inventory valuation → the external system, correct and automatic.**+ Carbon's pushed inventory journals (receipt, shipment, WIP/absorption/variance, adjustments)+ maintain the provider's Inventory asset, COGS, WIP and variance balances; the balance sheet+ and P&L tie out (v3 account×period tie-out proves it).+- **Item-level / per-SKU valuation → Carbon, the inventory subledger — by design.** A+ manufacturing ERP's costing (standard cost, WIP, absorption, variances, lot/serial,+ multi-location, FIFO layers) cannot be replicated by an accounting system; letting the+ provider track item inventory would produce a *divergent* valuation and double-count. This is+ the canonical ERP-owns-detail / accounting-owns-rollup split.+- **Dimensional inventory reporting in the provider** is available for slotted dimensions+ (Location / ItemPostingGroup / CostCenter → provider Class/Dept/Tracking/Field via v3+ dimension sync) — "inventory value by product line / location", just not per individual SKU.++### Design Decisions++| Decision | Choice | Rationale |+|---|---|---|+| Correctness model | Provider document ≡ Carbon posting journal (document GL reproduces the journal) | Tautological correctness; provider-quirk-independent; unifies item/GL/tax/variance lines |+| AP bill representation | Account-costed journal replay to GR-IR (item as label) | Bill's job is to clear GR-IR; item refs post to item accounts → uncleared GR-IR + double cost. Item refs and GR-IR clearing are mutually exclusive on purchases (QBO can't override; Xero-tracked hijacks) |+| AR invoice representation | Item-referenced to the item's revenue account | Revenue *is* the invoice's job; item's income account aligns; COGS handled by the pushed shipment journal; Rillet AR is structurally product-based anyway |+| Provider items | Non-Inventory / non-tracked on every provider | Stops the provider posting inventory (bills) / COGS (invoices) behind Carbon's back; QBO precedent; the guard that makes §1/§2 safe |+| Non-posting docs (PO/SO/Quote) | Keep item-referenced | No GL posting → no correctness constraint → item detail is free |+| Item visibility on bills | Line description (all) + structured ref where side-effect-free (Xero `ItemCode` on non-tracked) | Preserves "what did I buy" without letting the item drive the GL |+| Shared code shape | One `core/document-costing.ts` (`loadBillCostingLines`) + thin provider adapters | Mirrors the payment-application core just shipped; Rillet is the reference; no per-provider costing logic to drift |+| Inventory valuation | Financial in provider (via journals); per-item in Carbon (subledger) | Manufacturing costing can't be replicated in accounting; avoids divergence + double-count |+| Data model | No schema change | Reuses `journal`/`journalLine`/`journalLineDimension`, `accountDefault`, `purchaseOrderLine.itemId` (via the prefixed `documentLineReference`), the account/item mappings, and the item syncers |+| Currency (FX bills) | Replay in transaction currency (base ÷ `exchangeRate`, residue balanced into the largest line) + pin the provider rate (Xero `CurrencyRate`, QBO `ExchangeRate`+`CurrencyRef`, Rillet `exchange_rate`) | Journal is base-currency; unconverted replay misstates FX bills (the shipped Rillet mapper's latent bug); pinning the rate keeps provider base GL = Carbon GL |+| Tax on replayed bills | Tax-neutral v1 (Xero `TaxType: NONE`, QBO no `TxnTaxDetail`, Rillet no `tax_rate`); provider tax reports exclude Carbon bills | Purchase posting folds tax into cost (no tax journal line); running the provider tax engine on tax-inclusive amounts double-taxes; same stance as pushed manual journals |+| Bill sync gating | Posted-status `shouldSync` on all three bill syncers (mirror invoices' `SYNCABLE_STATUSES`) | A Draft bill has no posted journal to replay; avoids Warning noise; drafts don't belong in the books of record |+| Xero tracked-item flip | `false` on create; omit on update + `Warning` if remote still tracked | Xero rejects untracking items with transactions; keeps the rollout unblocked without a sandbox dependency |+| Xero AR revenue source | Item's mapped sales account (same source as QBO `IncomeAccountRef` / Rillet product) | Cross-provider consistency; journal-derived divergence only under customer-group posting variation, caught by tie-out |++## Data Model Changes++**None.** This is a representation change in the syncers. It reuses the posted journal+(`journal`/`journalLine` with `documentLineReference`), `accountDefault.payablesAccount`, the+`externalIntegrationMapping` account + item mappings, and the existing item syncers. No+migration, enum, or table.++## API / Service Changes++All in `packages/ee/src/accounting`:++- **NEW `core/document-costing.ts`** — `loadBillCostingLines(db, args)` (extracted from Rillet+ `fetchPostingJournalLines` + `filterBillCostingLines`), returning base-currency debit-signed+ `CostingLine[]` plus the invoice's `currencyCode`/`exchangeRate`, with the source item+ resolved via `documentLineReference` (strip the `purchase-invoice:` prefix) →+ `purchaseOrderLine.itemId → item`; no label for direct no-PO lines. Plus+ `toTransactionCurrencyLines(lines, exchangeRate)` (÷ rate, 2dp, residue balanced into the+ largest line).+- **`providers/rillet/entities/bill.ts`** — refactor onto `loadBillCostingLines`; add the item+ code/name to the line `description`; **fix the FX labeling bug** (transaction-currency+ amounts + `exchange_rate` instead of base amounts labeled with the transaction currency);+ add the posted-status `shouldSync`. Parity test covers base-currency bills+ (byte-identical); FX bills change deliberately (bug fix).+- **`providers/quickbooks-online/entities/bill.ts`** — build **account-based** lines from+ `CostingLine[]` (GR-IR/PPV), transaction-currency amounts + `CurrencyRef`/`ExchangeRate`+ (fields added to `Qbo.BillSchema`), item name in `Description`, no `TxnTaxDetail`; remove+ item-based expense lines on bills; add the posted-status `shouldSync`.+ **`purchase-order.ts` and `entities/shared.ts` `buildQboExpenseLines` stay untouched** (PO+ is non-posting and remains item-referenced, per §4).+- **`providers/xero/entities/bill.ts`** — build `LineItem`s from `CostingLine[]`+ (`AccountCode` = mapped account, `Description`, `TaxType: "NONE"`, `ItemCode?` only for+ known-non-tracked items), transaction-currency amounts + pinned `CurrencyRate`; journal+ accounts, not the blunt default; posted-status `shouldSync`; pre-flight `Warning` instead of+ a line rewrite when the local document is `Paid`/`Partially Paid` (Xero rejects edits to+ invoices with payments).+- **`providers/xero/entities/invoice.ts`** — `AccountCode` = the item's mapped revenue account+ (decided — same source as QBO `IncomeAccountRef`; not journal-derived), not+ `defaultSalesAccountCode`. Tax handling unchanged (`OUTPUT`, `LineAmountTypes: "Exclusive"`).+- **`providers/xero/entities/item.ts`** — `IsTrackedAsInventory: false` on create; omitted on+ update, with a `Warning` when the remote item is still tracked (drop the+ `itemTrackingType !== "None"` derivation for the outbound push).+- Rillet/QBO invoices and QBO items: unchanged.++## UI Changes++None. (Optionally, a one-line note on the accounting-integration settings page that provider+items sync as non-inventory and per-SKU valuation lives in Carbon — nice-to-have, not required.)++## Acceptance Criteria++> **Note:** the **Tie-out** criterion below (account × period tie-out) shipped as part of the+> delivery-robustness work; it is documented in `.claude/rules/accounting-sync-handlers.md`+> (Reconciliation + tie-out).++- [ ] **AP GR-IR clears (per provider).** In a sandbox: receive an item on a PO (Carbon pushes+ `Dr Inventory / Cr GR-IR`), then post + sync the bill. The provider's **GR-IR account nets+ to zero** and Inventory is debited exactly once. Holds on Rillet, QBO, and Xero.+- [ ] **No double-count.** The item's cost appears once (Inventory, from the receipt journal),+ not also as COGS/expense from the bill. Verified on QBO and Xero (the current failure).+- [ ] **Item still visible.** A PO-backed bill line shows the item code/name (description on+ all; Xero also as `ItemCode`); direct no-PO lines fall back to the journal description+ (known v1 limit — no `documentLineReference` is stamped for them).+- [ ] **FX bill.** A foreign-currency bill pushes transaction-currency lines summing exactly+ to the vendor-invoice total, with the provider rate pinned to Carbon's `exchangeRate`;+ the provider's base-currency GL equals the Carbon journal within rounding.+- [ ] **Tax-neutral replay.** Replayed bill lines carry no provider tax (Xero+ `TaxType: NONE`, QBO no `TxnTaxDetail`); the provider computes no tax on top.+- [ ] **Draft bills don't sync.** A Draft `purchaseInvoice` is skipped by `shouldSync` on all+ three providers (no ledger Warning noise); posting it triggers the sync.+- [ ] **AR posts to revenue.** A sales invoice posts `Dr AR / Cr <item revenue account>` on all+ three providers (Xero no longer uses the blunt default); COGS appears only from the pushed+ shipment journal, once.+- [ ] **Xero items are non-tracked.** A synced Xero item has `IsTrackedAsInventory = false`; a+ bill/invoice referencing it triggers no provider-side inventory/COGS posting.+- [ ] **Rillet AR/AP parity.** Rillet bill (now via the shared core) and invoice produce the+ same GL as before; existing tests stay green.+- [ ] **Tie-out.** After a full receive→bill→ship→invoice cycle, the v3 account×period tie-out+ shows zero external delta on Inventory, GR-IR, COGS, AP, AR, and Revenue.+- [ ] `pnpm --filter @carbon/ee test` + scoped typechecks green; new unit tests cover+ `loadBillCostingLines`, the three bill adapters, the Xero invoice revenue account, and the+ Xero non-tracked item.++## Risks++| Risk | Severity | Mitigation |+|---|---|---|+| QBO/Xero bill GL changes are real posting changes | High | Sandbox receive→bill acceptance (GR-IR nets to zero) before relying on it; tie-out gate; the model is a faithful replay of Carbon's own journal, so correctness is by construction |+| Xero `IsTrackedAsInventory=false` changes existing Xero item behavior | High | It removes a double-count, not adds one; document the change; verify a tracked→non-tracked item still syncs and its documents post only AR/AP + the mapped account |+| Provider GL behavior inferred from API docs, not observed | Med | VERIFY flags on each provider claim (Xero tracked-item account hijack; QBO item-account posting); resolved by the sandbox acceptance runs |+| Existing Xero bills/invoices in the field already posted the "wrong" way | Med | This is forward-only representation; historical documents are untouched (no DELETE sync); note in the changelog that pre-fix documents may carry item accounts |+| Item label enrichment mis-joins a journal line to an item (aggregated/variance lines) | Low | Only `documentLineReference`-linked lines get a label; variance/rounding lines have none; direct no-PO lines have no reference at all (v1 limit) — expected |+| Negative costing lines (credit PPV) rejected by a provider | Med | Xero accepts negative `LineAmount`; QBO negative bill-line `Amount` is a VERIFY gate — fallback: net lines per account in the builder |+| Re-sync of an already-paid provider bill fails (Xero rejects line edits on paid invoices) | Med | Pre-flight `Warning` when the local document is Paid/Partially Paid; otherwise surfaced as a provider error in the ledger — forward-only, documented |++## Open Questions++> Combined spec request — resolutions are **Autonomous** (codebase precedent + provider-capability+> facts), surfaced for Brad's veto. No Ask-First items: no schema change, no auth/RBAC/tenancy,+> no public contract, no new dependency.++- [x] **Where does inventory valuation report?** — **Answer (Brad's question, 2026-08-05):**+ financial/GL-level valuation lives in the provider (correct, via Carbon's pushed inventory+ journals + the tie-out); per-item/SKU valuation stays in Carbon as the inventory subledger;+ dimensional slices (by location/product line) are available in the provider via the v3+ dimension sync. This is the intended ERP-owns-detail / accounting-owns-rollup split, and it+ is *why* non-tracked provider items are correct rather than lossy.+- [x] AR invoices — item-referenced vs journal replay? — **Autonomous: item-referenced.** Revenue+ = the invoice's job = the item's income account; Rillet AR is structurally product-based;+ preserves AR subledger detail. COGS via the shipment journal.+- [x] AP bills — item ref + account override anywhere? — **Autonomous: no, account-costed replay.**+ QBO can't override an item line's account; Xero-tracked hijacks it; Rillet bills have no item+ field. Item refs and GR-IR clearing are mutually exclusive on purchases.+- [x] Keep item visibility how? — **Autonomous: description label everywhere + Xero `ItemCode`+ (non-tracked, no side effect).**+- [x] Do POs/SOs need changing? — **Autonomous: no** — non-posting; item refs are safe there.+- [x] FX bills — base or transaction currency? — **Autonomous (2026-08-05 review):**+ transaction currency (base ÷ rate, residue-balanced) + pinned provider rate (§1b); the+ shipped Rillet base-amounts-with-transaction-label behavior was a latent bug, fixed as+ part of the refactor.+- [x] Tax on replayed bills? — **Autonomous (2026-08-05 review):** tax-neutral v1 (§1c);+ provider tax reports exclude Carbon bills; tax-aware mapping is a follow-up. Also+ corrects the earlier claim that the journal "contains tax lines" — purchase posting+ folds tax into cost.+- [x] Do Draft bills keep syncing? — **Autonomous (2026-08-05 review):** no — posted-status+ `shouldSync` on all bill syncers (deliberate behavior change; drafts have no journal to+ replay).+- [x] Xero AR revenue account — item default or journal line? — **Autonomous (2026-08-05+ review):** the item's mapped sales account, for consistency with QBO `IncomeAccountRef`+ and Rillet's product account; customer-group posting divergence is inherent to+ item-referenced AR and caught by tie-out.++## Changelog++- 2026-08-05: Created. Motivated by a Rillet bill showing `GR/IR Clearing` instead of an item+ (which is actually correct), and Brad's directive to fix line representation across all+ integrations. Provider-capability survey + full transaction-syncer audit this session+ established that the item-referenced bill approach (QBO, Xero) double-counts cost and never+ clears GR-IR, and that account-costed journal replay (Rillet's model) is the correct,+ provider-quirk-independent representation. Design resolved autonomously under the combined+ spec delegation; inventory-valuation question answered inline. Implementation plan to follow+ at `.ai/plans/archived/2026-08-05-accounting-document-representation.md`.+- 2026-08-05 (review): Pre-implementation review amendments, grounded against the working+ tree. Corrected the item-label join (`documentLineReference` =+ `purchase-invoice:<purchaseOrderLineId>` — prefixed, PO-line-keyed, absent on direct no-PO+ lines; not `purchaseInvoiceLine.id`). Added §1b Currency (transaction-currency replay ++ pinned provider rate; fixes Rillet's latent FX labeling bug) and §1c Tax (tax-neutral replay+ v1). Added the posted-status `shouldSync` gate for bills, the Xero tracked-item+ create/update rollout rule, and the Xero AR revenue-account source decision (item's mapped+ sales account). PO / `buildQboExpenseLines` explicitly untouched. New risks: QBO+ negative-line VERIFY; paid-document re-sync. Plan updated in lockstep.+- 2026-08-11: Reconciliation pass — status set to **implemented** (executed 2026-08-05 as+ Part B of the accounting handoff run); the tie-out acceptance criterion was later delivered by+ the delivery-robustness work (see `.claude/rules/accounting-sync-handlers.md`). No design changes.diff --git a/.claude/rules/accounting-sync-handlers.md b/.claude/rules/accounting-sync-handlers.mdindex f82673e63e..baa2651f4a 100644--- a/.claude/rules/accounting-sync-handlers.md+++ b/.claude/rules/accounting-sync-handlers.md@@ -2,42 +2,90 @@paths:- "packages/jobs/src/inngest/functions/integrations/**"- "packages/jobs/src/inngest/functions/events/sync.ts"+ - "packages/jobs/src/inngest/functions/events/sync-tables.ts"- "packages/ee/src/accounting/**"---# Accounting Sync Handlers-Syncs Carbon entities <-> external accounting providers. **Xero is the only live provider** (`ProviderID.XERO = "xero"`; QuickBooks/Sage are commented stubs). Runs on **Inngest** (the old trigger.dev `from-/to-accounting-sync` task design is gone — do not look for `UPSERT_MAP`/`DELETE_MAP` or a `trigger/` dir; neither exists).+Syncs Carbon entities <-> external accounting providers. **Three live providers**: Xero (`ProviderID.XERO`), QuickBooks Online (`ProviderID.QBO`), and Rillet (`ProviderID.RILLET`). (QuickBooks *Desktop* shipped then was removed 2026-08-01; Sage was never built.) `SyncFactory` is a **provider-keyed registry** (`registries[providerId][entityType]`) — each provider's `index.ts` barrel calls `SyncFactory.register(...)`. Runs on **Inngest** (the old trigger.dev `from-/to-accounting-sync` task design is gone — do not look for `UPSERT_MAP`/`DELETE_MAP` or a `trigger/` dir; neither exists).++Design specs: `.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md` (v5 — ONE state-shaped decision core; events are hints; the authoritative design of record) and `.ai/specs/implemented/2026-08-05-accounting-document-representation.md` (AR/AP documents replay their posting journal; provider items non-tracked). The superseded v2/v3/v4 specs (engine + ledger + pull sweep + Phase F/G payment sync-back; journal policy/dimensions/tie-out; delivery robustness — converged subscriptions, truthful ledger, outbound sweep, tie-out enforcement) were removed 2026-08-13 — their shipped behavior is documented in THIS rule; their history is in git. **Always-on (implemented 2026-08-13, plan `.ai/plans/2026-08-13-accounting-sync-automated-postings-only.md` Tasks 1–6+8):** posting sync mirrors Carbon's automated GL postings whenever an accounting integration is connected — no master `postingSync.enabled` toggle, no per-source-type on/off, no `journalEntry` entity gate (defaulted on in `DEFAULT_SYNC_CONFIG` and forced on in every `build*SyncConfig`). `Manual` journals NEVER sync (`POSTING_POLICY.Manual.syncable: false` → permanent `MANUAL_DISABLED`). Legacy `enabled` fields stay in the stored schema for parse-compat but are never read; per-type granularity (individual vs daily-summary) remains the only per-type setting. Plan Tasks 7 (reversal/void propagation audit) and 9 (lock AR/AP families to documents) remain open.## Architecture: class-per-entity syncers, not a handler mapThe sync engine lives in `packages/ee/src/accounting/` (package `@carbon/ee/accounting`):-- `core/sync.ts` — `SyncFactory.getSyncer(context)` returns the right syncer by `entityType`.-- `core/types.ts` — `BaseEntitySyncer<TLocal, TRemote, TOmit>` abstract base (~800 lines). Implements `pushToAccounting` / `pullFromAccounting` (+ `*Batch*`) with: mapping lookup, `shouldSync` gate, fast-bailout on unchanged timestamps, `mapToRemote`/`mapToLocal`, then `withTriggersDisabled` DB write + `linkEntities`.-- `providers/xero/entities/*.ts` — concrete syncers: `ContactSyncer` (handles both `customer` AND `vendor`), `ItemSyncer`, `BillSyncer`, `SalesInvoiceSyncer` (`invoice`), `PurchaseOrderSyncer`, `SalesOrderSyncer`, `InventoryAdjustmentSyncer`. `employee`/`payment` are NOT implemented (Xero dropped the Employees API).+- `core/sync.ts` — `SyncFactory.getSyncer(context)` returns the right syncer by `providerId` + `entityType` from the registry.+- `core/types.ts` — `BaseEntitySyncer<TLocal, TRemote, TOmit>` abstract base (~800 lines). Implements `pushToAccounting` / `pullFromAccounting` (+ `*Batch*`) with: mapping lookup, `shouldSync` gate, fast-bailout on unchanged timestamps, `mapToRemote`/`mapToLocal`, then `withTriggersDisabled` DB write + `linkEntities`. Also `SupportsIncrementalPull` (`listChanges({since}) → ProviderChange[]`) — the pull-sweep contract (QBO CDC, Rillet `updated.gt`, Xero `/Payments` `If-Modified-Since`).+- `providers/{xero,quickbooks-online,rillet}/entities/*.ts` — concrete syncers. Xero `ContactSyncer` backs both `customer` AND `vendor`; QBO/Rillet have separate Customer + Vendor syncers. Each provider has item/bill/invoice(+PO/journalEntry) syncers and a **`PaymentSyncer`** (see Payment sync-back below). `employee` is not implemented.- `core/external-mapping.ts` — `ExternalIntegrationMappingService` / `createMappingService(db, companyId)`: all ID linking goes through the `externalIntegrationMapping` table.-- `core/models.ts` — Zod schemas, `ProviderID`, `AccountingSyncSchema`, `ENTITY_DEFINITIONS`, `DEFAULT_SYNC_CONFIG`.-- `core/service.ts` — `getAccountingIntegration()` (reads `companyIntegration` row) + `getProviderIntegration()` (instantiates `XeroProvider`).+- `core/models.ts` — Zod schemas, `ProviderID`, `AccountingSyncSchema`, `ENTITY_DEFINITIONS`, `DEFAULT_SYNC_CONFIG`, `PostingSyncSettings` (`families.ar`/`families.ap` = `documents|journals|none`).+- `core/service.ts` — `getAccountingIntegration()` (reads `companyIntegration` row) + `getProviderIntegration()` (instantiates the right provider; applies the merged per-company `syncConfig`).## Entity types & directions-`AccountingEntityType` = `customer | vendor | item | employee | purchaseOrder | bill | salesOrder | invoice | payment | inventoryAdjustment`.+`AccountingEntityType` = `customer | vendor | item | employee | purchaseOrder | bill | salesOrder | invoice | payment | inventoryAdjustment | journalEntry`. `payment` is `dependsOn: ['invoice','bill']` and **two-way** (Phase G): provider-recorded payments pull back (Phase F) and Carbon-born Posted payments push out as provider payment documents. Routing is per-record by origin (the `payment` mapping), not a static direction — see Payment sync-back.-`SyncDirection` = `"two-way" | "push-to-accounting" | "pull-from-accounting"` (NOT the old `from-/to-/bi-directional`). Each entity has an `EntityConfig { enabled, direction, owner: "carbon" | "accounting", syncFromDate? }`. Per-entity defaults live in `DEFAULT_SYNC_CONFIG`; `getProviderIntegration()` currently hardcodes `DEFAULT_SYNC_CONFIG` (company-level `syncConfig` from metadata is parsed but not yet applied). `owner` decides the winner on conflict in two-way sync.+`SyncDirection` = `"two-way" | "push-to-accounting" | "pull-from-accounting"` (NOT the old `from-/to-/bi-directional`). Each entity has an `EntityConfig { enabled, direction, owner: "carbon" | "accounting", syncFromDate? }`. Per-entity defaults live in `DEFAULT_SYNC_CONFIG`, deep-merged with the company's stored `syncConfig`; providers then force an entity's config in their `build{Xero,Qbo,Rillet}SyncConfig`. **Carbon owns everything** is the standardized stance: every provider forces the master + document entities `customer`/`vendor`/`item`/`invoice`/`bill` to `push-to-accounting` / `owner: "carbon"` (`XERO_CARBON_OWNED_ENTITIES`, `QBO_CARBON_OWNED_ENTITIES`, Rillet's `RILLET_PUSH_ONLY_ENTITIES`) — the provider is a downstream mirror. `payment` is the one accounting-owned exception (forced `pull-from-accounting` / `owner: "accounting"`; Rillet two-way for Phase G push-back). There is **no** per-entity "Source of Truth" setting — it was removed; `owner` is provider-forced, not user-configurable. `owner` decides the winner on conflict: for a Carbon-owned entity, an inbound provider change to an already-linked record is skipped (`BaseEntitySyncer.pullBatchFromAccounting`, `core/types.ts`). Note the webhook path sends an explicit `pull-from-accounting` that overrides `direction`, so a net-new record created directly in the provider can still be ingested — `owner: "carbon"` only guards *linked* records; QBO's CDC pull-sweep (`listChanges`) does honor `direction` and skips push-only entities entirely.## Inngest functions (entry points)-All three are in `packages/jobs/src/inngest/functions/integrations/` (+ `events/sync.ts`), exported via that dir's `index.ts`, and registered in `packages/jobs/src/inngest/index.ts`. Event-name <-> trigger-key map: `packages/lib/src/trigger.ts` & `packages/lib/src/events.ts`. Fire with `trigger("<key>", payload)`.+These live in `packages/jobs/src/inngest/functions/integrations/` (+ `events/sync.ts`), exported via that dir's `index.ts`, and registered in `packages/jobs/src/inngest/index.ts`. Event-name <-> trigger-key map: `packages/lib/src/trigger.ts` & `packages/lib/src/events.ts`. Fire with `trigger("<key>", payload)`.| Inngest id | event | file | trigger key / fired from ||---|---|---|---|-| `sync-external-accounting` | `carbon/sync-external-accounting` | `sync-external-accounting.ts` | `sync-external-accounting`; fired by the Xero inbound webhook `apps/erp/app/routes/api+/webhook.xero.ts` |-| `accounting-backfill` | `carbon/accounting-backfill` | `accounting-backfill.ts` | `accounting-backfill`; fired by `apps/erp/app/routes/api+/integrations.xero.backfill.ts` |-| `event-handler-sync` | `carbon/event-sync` | `events/sync.ts` | the SYNC event-system handler (see event-system.md) — DB writes -> push to Xero |+| `sync-external-accounting` | `carbon/sync-external-accounting` | `sync-external-accounting.ts` | `sync-external-accounting`; fired by the inbound webhooks — `webhook.xero.ts`, `webhook.rillet.$companyId.ts`, `webhook.quickbooks.$companyId.ts` |+| `accounting-pull-sweep` | — | `accounting-pull-sweep.ts` | cron `*/30 * * * *`; iterates every active integration that implements `SupportsIncrementalPull` (`listChanges`) — the **INBOUND correctness guarantee** behind the webhooks (webhooks are latency, not correctness) |+| `accounting-outbound-sweep` | — | `accounting-outbound-sweep.ts` | cron `15,45 * * * *` (offset from the pull sweep) — the **OUTBOUND correctness guarantee** (v4 Pillar B); see the sweep section below |+| `accounting-backfill` | `carbon/accounting-backfill` | `accounting-backfill.ts` | `accounting-backfill` |+| `accounting-consolidation` | — | `accounting-consolidation.ts` | cron `0 2 * * *`; pushes one aggregated provider journal per posting date for daily-consolidation configs (drains hold those journal ops for it) |+| `accounting-reconciliation` | — | `accounting-reconciliation.ts` | cron `0 3 * * 1` (Mondays 03:00 UTC) — presence drift check + `accountingSyncTieOut` writer; see the tie-out section below |+| `event-handler-sync` | `carbon/event-sync` | `events/sync.ts` | the SYNC event-system handler (see event-system.md) — DB writes -> push to the provider |++### The operation ledger — enqueue, cooldown, truthful close++Every entry point routes through the durable **`accountingSyncOperation`** ledger (`accounting-sync-operations.ts` in jobs + `core/operations.ts` in ee) between enqueue and `SyncFactory.getSyncer(...).pushBatch/pullBatch`:++- **Enqueue.** `enqueueSyncOperations` absorbs re-triggers into the live (Pending/In Flight) row. The v5 reconcile path enqueues with trigger `"reconcile"`, which is **never cooldown-gated** — a state-derived decision is idempotent, so an unchanged entity decides `nothing` instead of needing a window, and a changed one enqueues immediately. The 60s completed-row cooldown (`SYNC_OPERATION_COOLDOWN_MS`, `isCooldownTrigger`: `event`/`webhook`) survives ONLY on the inbound/webhook entry points (`sync-external-accounting`, the pull sweep), which don't route through the reconciler. `isStatusTransitionEvent` and `getPaymentPushDecision` were deleted with v5 (nothing to bypass; payment state lives in the decision core).+- **Drain.** `drainSyncOperations` claims Pending (+ stale In Flight) rows in groups of (entityType, direction); an op claimed more than `MAX_SYNC_OPERATION_ATTEMPTS` (10) times parks as `Failed` `ATTEMPTS_EXHAUSTED` instead of running again (a human Retry resets the loop deliberately).+- **Truthful close (v4 Pillar C).** `getSyncOperationCloseDecision` decides how a claimed op closes: syncer `skipped` WITH a `remoteId` (fast-bailout, already linked) → `Completed` stamping that externalId; `skipped` WITHOUT one (shouldSync gate, disabled entity, parked payment) → `Skipped` via `skipOperation` (reason in `errorMessage`, `errorCode` null so the UI renders it neutrally); push `success` WITHOUT a `remoteId` → `Failed` `POSTCONDITION` (a push success must produce an external id/mapping — recording it green is the phantom-success bug). A no-op is never recorded `Completed`. `Skipped → Pending` is an allowed transition (`SYNC_OPERATION_ALLOWED_TRANSITIONS`, `core/models.ts` — Retry covers the drain's machine no-op closes too). Batch AND single pushes preserve structured `JournalEntrySyncError` failures via `toSyncResultError` (`core/types.ts`), so e.g. `UNMAPPED_ACCOUNTS` lands as a Warning with metadata instead of a flattened Failed string.++`sync-external-accounting.ts` flow: parse `AccountingSyncSchema` → `getAccountingIntegration` → `getProviderIntegration` → enqueue one ledger op per entity + direction (trigger: `webhook` syncs keep `"webhook"`, scheduled/trigger syncs enqueue as `"event"`; both respect the completed-row cooldown) → drain. Returns `{ success, enqueue, drain }` summaries.++`events/sync.ts` (v5) treats events as **hints, not decisions**: it maps DB table → entity type via `TABLE_TO_ENTITY_MAP` in **`events/sync-tables.ts`** (import-light on purpose — no Inngest/env boot — so the subscriptions invariant test can import it): `customer→customer`, `supplier→vendor`, `item→item`, `purchaseOrder→purchaseOrder`, `purchaseInvoice→bill`, `salesInvoice→invoice`, `salesOrder→salesOrder`, `journal→journalEntry`, `payment→payment`; dedupes the batch into `(entityType, entityId)` refs (DELETEs logged/skipped — a deleted row also reconciles to nothing), and calls the same `reconcileEntities` executor the outbound sweep uses, then drains. There are no per-table decision branches here anymore — what happens is decided by `computeReconcileDecision` from CURRENT state, never from the event's old/new delta. Wrapped in `step.run` per company+provider for checkpointing.++## Event subscriptions — code-derived, converged (v4 Pillar A)++`packages/ee/src/accounting/core/subscriptions.ts` (exported from the `./accounting` barrel) is the single source of truth for the SYNC event-system subscriptions each provider's outbound sync needs: `REQUIRED_SYNC_SUBSCRIPTIONS[providerId]` + the idempotent `ensureProviderSubscriptions(client, companyId, providerId)` (the create RPC upserts on `(companyId, name, table)`; rows for tables no longer required are deleted). Subscription name: `${providerId}-sync` (`getSyncSubscriptionName`).-`sync-external-accounting.ts` flow: parse `AccountingSyncSchema` → `getAccountingIntegration` → `getProviderIntegration` → group entities by type → per type `provider.getSyncConfig(type)` (skip if `!enabled`) → `SyncFactory.getSyncer(...)` → resolve `effectiveDirection` (`two-way` uses `entityConfig.direction`) → `pushBatchToAccounting` / `pullBatchFromAccounting` / `handleTwoWaySync`. A **60s per-entity cooldown** (`SYNC_COOLDOWN_MS`, via `mappingService.getByEntity().lastSyncedAt`) skips recently-synced entities. Returns `{ success: BatchSyncResult[], failed[] }`.+- **Converged from three call sites** — the install hook, the `onUpdate` hook (every settings save of an installed integration), and the outbound sweep — so existing installs self-heal at runtime. **No migration ever backfills subscription rows**; migrations only attach table triggers (`20260807152238_payment-event-trigger.sql` is the precedent).+- **The set**: every provider gets `customer`/`supplier`/`item`/`salesInvoice`/`purchaseInvoice` (INSERT/UPDATE/DELETE) + `journal` (INSERT/UPDATE only — journals are immutable once posted and DELETE sync doesn't exist). all three providers add `payment` (INSERT/UPDATE — Phase G outbound push, now Rillet/Xero/QBO); Xero adds `purchaseOrder` + `salesOrder`; QBO adds `purchaseOrder` only. **`address` is deliberately absent everywhere** — address edits reach sync via the parent-row `updatedAt` bump interceptor; a direct address subscription is a dead letter.+- Provider hooks (`packages/ee/src/{rillet,xero,quickbooks}/hooks.server.ts`) are thin wrappers over the convergence. The QBO install hook is **no longer a no-op** (its syncers shipped), and `quickbooksOnUninstall` exists. `onUpdate` is a new `IntegrationServerHooks` member (`packages/ee/src/types.ts`; registry `packages/ee/src/hooks.server.ts`; wired in `apps/erp/app/routes/x+/settings+/integrations.$id.tsx`).+- **Invariant test**: `packages/jobs/src/inngest/functions/events/subscriptions-mapping.test.ts` pins every subscribed table ↔ a `TABLE_TO_ENTITY_MAP` entry (`events/sync-tables.ts`) ↔ a registered syncer for that provider — a subscription that routes nowhere fails CI. (`salesOrder` got its map entry as part of this; it was a dead Xero subscription before.)-`events/sync.ts` maps DB table → entity type via `TABLE_TO_ENTITY_MAP` (`customer→customer`, `supplier→vendor`, `item→item`, `purchaseOrder→purchaseOrder`, `purchaseInvoice→bill`, `salesInvoice→invoice`). INSERT/UPDATE → `pushBatchToAccounting`; **DELETE is logged/skipped (not implemented)**. Wrapped in `step.run` per company+provider for checkpointing; re-throws `RatelimitError` so Inngest retries.+## Outbound reconciliation sweep (v4 Pillar B)++Doctrine, mirroring the inbound pull sweep: **events are latency; the sweep is outbound correctness.** Any lost event (missing subscription, queue loss, cooldown swallow, phantom Completed) becomes ≤30-min staleness, never permanent loss. `accounting-outbound-sweep.ts` (cron `15,45 * * * *`), per company with an active accounting integration:++1. **Subscription convergence** — `ensureProviderSubscriptions` (the self-healing invariant check; runs first so a repaired install's next events flow normally).+2. **Candidate refs (scope, not decisions)** — pages posted journals (Posted/Reversed, `reversalOfId` null), posted documents (`SWEPT_BILL_STATUSES`/`SWEPT_INVOICE_STATUSES` — the posted set minus the transient mid-posting `Pending`), posted payments (Rillet only), and parked `Warning UNMAPPED_ACCOUNTS` bills regardless of window. Window floor: `getSweepFloorDate` = today − `SWEEP_LOOKBACK_DAYS` (7), raised to the entity's `syncFromDate` — deliberately short; history beyond it is the explicit backfill's job.+3. **Reconcile** — every ref goes to `reconcileEntities` (the SAME executor the event path calls); the decisions (missing-remotely enqueue incl. the phantom Completed-without-mapping repair, policy exclusions, the capped `MAX_REDRIVE_ATTEMPTS` re-drive when a bill's posted "Purchase Invoice" journal now exists) all live in `computeReconcileDecision`.+4. **Drain** — including what this run enqueued/re-drove. This is **Xero's only periodic drain** (it has no incremental pull), so UI retries stop rotting as Pending.+5. **Alert (Pillar F)** — failed ops left after the drain fire one in-app `NotificationEvent.IntegrationSync` to the integration's configurer (`integration.updatedBy`), linking to the integration's settings page. A notification failure never fails the sweep.++## The v5 reconciler (one brain)++- **`integrations/reconcile.ts`** — `computeReconcileDecision(input)`: the pure, state-shaped decision for every outbound entity (journals via the shared `planJournalPostingFromState` policy core; documents incl. the re-drive and the changed-since-failure retry; payments; master data via `updatedAt` vs `mapping.lastSyncedAt`). Import-light; exhaustively pinned by **`reconcile-golden.test.ts`** (spec Step A), whose FIX-1..4 entries document every deliberate difference from the legacy paths.+- **`integrations/reconcile-executor.ts`** — `reconcileEntities({refs, …})`: batch-first state loading (one query per concern per entity type — snapshots, ledger rows incl. `:reversal` twins, mappings, the parked-bill backing-journal join), then the pure decision per entity, then application through the existing ledger primitives with trigger `"reconcile"` (migration `20260812093418` widened the CHECK).+- Callers: `events/sync.ts` (hints) and the outbound sweep (window walk). The journal policy core is shared with `planJournalPostingOperation` (still used by the manual backfill), so policy routing cannot diverge between callers.++## Reconciliation + tie-out (v3 §5 / v4 Pillar E)++`accounting-reconciliation.ts` (cron `0 3 * * 1`) is **provider-agnostic** — all three providers, no longer Xero-only:++- **Presence** — pages the last 90 days of Completed journalEntry ops and verifies each distinct externalId still exists remotely via `fetchRemoteJournalTotals` (`core/remote-journal.ts` — dispatches on the concrete provider class: Xero manual journals, Rillet journal entries, QBO journal entries; returns net debit-signed totals per remote account ref, `found: false` for missing/voided/deleted, never throws except `RatelimitError`). Drift entries land at `companyIntegration.metadata.settings.postingSync.lastReconciliation` (the SyncActivity banner's feed).+- **Tie-out** — writes one `accountingSyncTieOut` row per (integration × accountingPeriod × account) (migration `20260811223145`; single-column FK to `accountingPeriod` — its PK is `(id)` alone; RLS is SELECT-only under `accounting_view`, rows written by the cron via service role). Per cell: `carbonPostedAmount` split into `synced/docBacked/excluded/pending/blocked` by each journal's ledger disposition (least-delivered bucket wins across an op + its `:reversal` twin; `DOC_BACKED` counts as delivered only while the backing document really synced), `providerAmount` from the presence fetches (strictly reused, never fetched twice; NULL when uncovered), `internalDelta` (I1: carbonPosted − sum of buckets) and `externalDelta` (I5: synced − provider).+- **ERP surface** — `x+/accounting+/sync-tieout.tsx` (+ `$cellId` drawer drill-down), nav item under Accounting → Reports (`path.to.accountingSyncTieOut`); the SyncActivity tab gets a tie-out summary card + a Failed/Warning count badge. **Period close**: the "External GL sync complete" Blocker auto-check (`autoCheckKey: "external-gl-sync"`, seeded for new companies and reconciled for existing ones in the same migration) is computed by `getPeriodExternalGlSyncReadiness` (apps/erp `accounting.ee.service.ts`) — every journal posted into the period must carry a terminal disposition (Completed/Excluded/Skipped) for every active accounting integration; auto-passes only when NO active accounting integration exists (posting sync is always-on when one is connected).## externalIntegrationMapping table@@ -51,9 +99,151 @@ Constraints:Back-compat views reconstruct the legacy `externalId` JSONB via `jsonb_object_agg`: `suppliers`, `customers`, `parts`, `materials`, `tools`, `consumables`, `services`, `salesOrders` — so view-reading app code keeps working.+## Payment sync-back (inbound AR/AP) — the family-agnostic core++Provider payments (a customer invoice paid, or a **vendor bill paid**) flow back+into Carbon as `payment` + `invoiceSettlement` rows that close the+`salesInvoice`/`purchaseInvoice`. All three providers share one core:++- `core/payment-application.ts` — `NormalizedPayment` (`family: 'ar'|'ap'`,+ `documentRemoteId`, `paymentRemoteId`, amount/currency/date/reference, `status`,+ optional `linkedDocuments` for multi-doc fan-out) + `upsertLocalPaymentDraft`,+ which writes a **Draft** `payment` (AR→`Receipt`/`customerId`; AP→`Disbursement`/+ `supplierId`) + one `invoiceSettlement` per mapped document+ (`targetSalesInvoiceId`/`targetPurchaseInvoiceId`), idempotent by the `payment`+ mapping, dropping unmapped documents. Returns a `postAction` (`post`/`void`/`none`).+- `core/payment-syncer.ts` — `PaymentSyncerBase` (pull, plus the Phase G push below). Providers implement+ `mapToNormalized(remote, entityId)` + `fetchRemote`. The base overrides+ `pullFromAccounting`/`pullBatchFromAccounting`: Draft write in the base tx, then+ **after commit** invokes the native `post-payment` edge fn (`{type:'post'|'void'}`+ via a lazily-imported `getCarbonServiceRole()`), which builds the GL journal,+ sets `payment.journalId`, and derives document status. **Pulled payments DO post+ to Carbon's GL** — no double-count because `documents`-mode `Payment` journals are+ DOC_BACKED-excluded from outbound push (the payment journal never re-posts to the+ provider). `getSettledInvoiceStatus` is retained for tests only (status is+ view-derived).+- Provider syncers: `providers/{rillet,quickbooks-online,xero}/entities/payment.ts`.+ Composite entity-id convention: AR = `<documentRemoteId>:<paymentRemoteId>` (no+ prefix, back-compat), AP = `bill:<billRemoteId>:<paymentRemoteId>`.+ Detection: Rillet AR = `/invoice-payments?updated.gt` (poll). Rillet AP has NO+ org-wide feed — `GET /bill-payments` does not exist (verified 404 on sandbox+ 2026-08-13; the unguarded call used to kill every pull sweep), so+ `listBillPaymentsUpdatedSince` is composed: `GET /bills?updated.gt` (paying a+ bill bumps its `updated_at`) then `GET /bills/{id}/payments` per changed bill,+ each payment stamped with its bill's `updated_at`. QBO `Payment` ++ `BillPayment` (CDC + `webhook.quickbooks.$companyId.ts`); Xero `/Payments` via a+ new `listChanges` (`If-Modified-Since`) + Invoice-update webhook accelerator.+- Gate: `isPaymentSyncbackEnabled(metadata, family)` — pull-back only when the+ family is in `documents` mode (`PostingSyncSettings.families`); `journals`/`none`+ means Carbon owns the payment (v3 Phase 4 pushes it outbound). `shouldSync` also+ benignly skips a payment whose settled document has no local mapping (ownership).++### Outbound payment write-back (Phase G — Rillet, Xero, QBO)++Payments executed OUTSIDE the provider (e.g. a bill paid through Ramp, recorded+in Carbon, or a manual Carbon payment) push back so the provider's bill/invoice+closes. `PaymentSyncerBase` gained a bespoke `pushToAccounting` (not the templated+fetchLocal→mapToRemote flow): it reads the Carbon `payment` + `invoiceSettlement`+directly, gates on the SAME documents-mode families gate as pull, and routes+per-record by the `payment` mapping — a payment that already carries a mapping is+provider-known and skips (the loop guard: a pulled payment links its mapping+BEFORE post-payment flips it to Posted, so its Posted event finds the mapping and+skips). A mapping-less Carbon-born payment is pushed via the provider adapter+`pushRemotePayment` (one provider payment per settled document), then linked under+the composite id with `metadata.origin = "carbon"` so a later void echoes out and+a later pull no-ops. `supportsPaymentPush` gates the whole thing — **Rillet, Xero,+AND QBO all set it true** (2026-08-14 parity). The capability set+`PAYMENT_PUSH_PROVIDERS` (`core/payment-syncer.ts`, must stay in sync with the+syncer flags) is what the reconcile executor and outbound sweep read instead of the+old `providerId === "rillet"` literal. v1 is single-settlement, base-currency, no+discount, no void-echo — everything else parks as Skipped. The paid date goes+through `toPostingDateString` (Kysely's pg driver returns DATE columns as JS+`Date`s; a bare `.slice` crashed the push). Provider adapters (`pushRemotePayment`):+**Rillet** `createInvoicePayment`/`createBillPayment` (`POST /{invoices,bills}/{id}/payments`,+flat body `{ amount, date, account_code }` — `date`, NOT `payment_date`; bill path+VERIFIED sandbox 2026-08-11). **Xero** `createPayment` (`PUT /Payments`+`{ Payments:[{ Invoice:{InvoiceID}, Account:{Code}, Amount, Date }] }` —+**live-VERIFIED sandbox 2026-08-14**: bill flipped to PAID; the Account must be a+Xero `Type:"BANK"` account, and `EnablePaymentsToAccount` is NOT the gate for bank+accounts). **QBO** AP `createBillPayment` / AR `createPayment` via `writeEntity`+(payload VERIFY-flagged — no QBO sandbox; needs `VendorRef`/`CustomerRef` ++`PayType`/`BankAccountRef` (AP) or `DepositToAccountRef` (AR)). Trigger: the+`payment` table has an event trigger (`20260807152238_payment-event-trigger.sql`)++ a `${provider}-sync` `payment` subscription from `REQUIRED_SYNC_SUBSCRIPTIONS`+convergence (now Rillet/Xero/QBO; no migration backfill — see the subscriptions+section); the reconciler enqueues push only on a transition to Posted/Voided. (Phase G design lived in the+removed v2 engine spec; the behavior is documented in this section — see git for history.)++## Document representation model (bills, invoices, items)++Every AR/AP **document** Carbon pushes reproduces its Carbon posting journal, so+the provider's GL for that document equals Carbon's. Spec:+`.ai/specs/implemented/2026-08-05-accounting-document-representation.md`.++- **AP bills = account-costed replay of the posted "Purchase Invoice" journal**,+ NOT the item's account. `core/document-costing.ts` is the shared core:+ `loadBillCostingLines(db, { companyId, billId, payablesAccountId })` reads the+ posted journal (`journal.sourceType='Purchase Invoice'`, `status='Posted'`),+ drops the AP control line, and returns base-currency debit-signed+ `CostingLine[]` (+ `currencyCode`/`exchangeRate`). Item labels are joined via+ `journalLine.documentLineReference` (`purchase-invoice:<purchaseOrderLineId>`+ → `purchaseOrderLine.itemId` → `item`); direct no-PO / variance lines have+ `sourceItem: undefined`. `toTransactionCurrencyLines(lines, exchangeRate)`+ converts to the invoice's transaction currency (÷ rate, residue into the+ largest-|amount| line; rate 1 = pass-through). The item is a **description+ label only** (`costingLineItemLabel`). Bill lines are **tax-neutral** (the+ purchase posting folds tax into cost): Rillet no `tax_rate`, QBO no+ `TxnTaxDetail`, Xero `TaxType: "NONE"`. FX bills pin the provider rate+ (Rillet `exchange_rate`, QBO `CurrencyRef`+`ExchangeRate`, Xero `CurrencyRate`).+ Every bill syncer has a posted-status `shouldSync` (Draft excluded — no+ journal to replay). Unmapped/account-less/no-journal lines throw the+ structured `UNMAPPED_ACCOUNTS` Warning.+ - QBO bill emits `AccountBasedExpenseLineDetail` from a NEW bill-only builder+ (`buildQboBillLines`); it no longer uses the shared `buildQboExpenseLines`+ or `ensureDependencySynced("item")`. Xero bill uses `buildXeroBillLineItems`.+ Rillet bill (`mapBillToRilletBill`) is the reference (prepends the label;+ QBO/Xero substitute it). Account codes resolve through the shared+ `loadAccountCodesById` (Xero) / `loadQboAccountRefsById` (QBO) /+ `loadRilletAccountCodesById` (Rillet).+- **AR invoices = item-referenced to the item's REVENUE account**+ (`accountDefault.salesAccount` → the account-mapping code/ref — the same+ resolution for Rillet product `account_code`, QBO `IncomeAccountRef`, Xero+ invoice `AccountCode`), NOT the journal line and NOT the blunt+ `defaultSalesAccountCode`. COGS stays on the pushed `Sales Shipment` journal.+- **Provider items are non-tracked** so the provider never posts inventory+ (bills) or COGS (invoices): Xero pushes `IsTrackedAsInventory: false` on+ create and OMITS the flag on update (Xero rejects untracking an item with+ stock/txns; a still-tracked remote logs a recorded warning to untrack+ manually). QBO items are Service/NonInventory (never Inventory).+- **PO / SO / Quote are unchanged** — item-referenced, no GL constraint (QBO PO+ keeps `buildQboExpenseLines` / `ItemBasedExpenseLineDetail`).++## Dimensions (journal / bill analytics)++Journal-entry and bill line dimensions (`journalLineDimension`) map to provider+analytics fields. **Rillet sends ALL dimensions on every line and auto-provisions+what's missing** — there is no per-company slot/cap (Rillet Fields are unlimited).+`RilletTransactionSyncer.resolveLineDimensions(lines)` (`providers/rillet/entities/shared.ts`)+resolves each distinct dimension to a Rillet Field id (reuse an existing Field by+name, else `createField(name, "EXPENSES")` — journal entries + bills are+expense-side) and each value to a Field-value id (`upsertFieldValue` by the+value's readable label), persisting both in `externalIntegrationMapping`+(`entityType` `"dimension"` for the Field via `upsertDimensionMapping`,+`"dimensionValue"` for the value). The Rillet mappers iterate `line.dimensions`;+a dimension whose Field or value can't be provisioned is dropped from that line's+refs. `createField` (`POST /fields`) is VERIFY-flagged — confirm the payload on+the Rillet sandbox.++**Xero/QBO keep the slot system** (`dimensionSlots` + `maxJournalDimensionSlots`+= 2 each; `validateDimensionSlots`, the Dimensions settings tab). For Rillet the+slot config is now inert (the mapper no longer reads it) — the tab's slot editor+is dead config for Rillet only, left in place for the capped providers.+## Gotchas-- All DB writes during sync are wrapped in `withTriggersDisabled(database, tx => ...)` to break the loop (sync writes DB → event trigger → sync again).+- All DB writes during sync are wrapped in `withTriggersDisabled(database, tx => ...)` to break the loop (sync writes DB → event trigger → sync again). Since migration `20260811224732`, that suppression is **scoped**: `dispatch_event_batch()` drops only SYNC/WEBHOOK/WORKFLOW subscriptions while `app.sync_in_progress` is set (the loop/echo-prone types); SEARCH/AUDIT/EMBEDDING observers now see sync-written rows (v4 F13). **Exception:** payment sync-back invokes `post-payment` *outside* that tx (triggers enabled), like a user posting a payment — intended.+- Rillet create POSTs carry a deterministic, **entity-scoped** `Idempotency-Key`: `buildRilletIdempotencyKey` (`providers/rillet/provider.ts`) = sha256 of `companyId:operation:localId`; Rillet replays the stored response for 24h. The payload is deliberately **NOT hashed** (v4 Pillar C): a crash between the remote create and the local mapping write retries with a possibly-drifted payload, and a payload-sensitive key would mint a fresh key and duplicate the remote document. Contract pinned by `providers/rillet/__tests__/provider.test.ts`.+- The event-queue drainer (`events/queue.ts`) archives unknown-`handlerType` messages to pgmq's dead-letter table (`pgmq.a_event_system`) instead of crash-looping the whole drain (v4 F8) — a poison message can no longer wedge ALL event processing.- `ContactSyncer.getRemoteId` checks both `customer` and `vendor` mappings (one Xero Contact backs both).- Transaction syncers (PO, invoice, bill) use `ensureDependencySynced(type, localId)` for JIT dependency syncing (e.g. push the customer before its invoice); `dependsOn` is declared in `ENTITY_DEFINITIONS`.- DELETE sync is not implemented anywhere yet.diff --git a/.claude/rules/fixed-asset-lifecycle.md b/.claude/rules/fixed-asset-lifecycle.mdindex 4178214d7c..3b0342a556 100644--- a/.claude/rules/fixed-asset-lifecycle.md+++ b/.claude/rules/fixed-asset-lifecycle.md@@ -75,12 +75,12 @@ enum value (CHECK: only Fixed Asset lines have non-NULL `assetId`). The(acquisitionCost/Date, accumulatedDepreciation, depreciationStartDate),`depreciationRunValidator` (periodEnd only), `fixedAssetDisposalValidator`(disposalDate only), `fixedAssetUsageLogValidator`.-- Service: `accounting.service.ts` — `getFixedAsset(s)`, `insert/update/deleteFixedAsset`,+- Service: `accounting.ee.service.ts` — `getFixedAsset(s)`, `insert/update/deleteFixedAsset`,`getFixedAssetsListForSale` (status Active/Fully Depreciated), class CRUD,`insert/getDepreciationRun(s)`, `getDepreciationRunLines`,`getAssetDepreciationHistory`, `getFixedAssetDisposal`, usage-log helpers.Note `upsertFixedAsset` is deprecated — use insert/update.-- Server transactions (Kysely): `accounting.server.ts` — `postDisposal()` (L37)+- Server transactions (Kysely): `accounting.ee.server.ts` — `postDisposal()` (L37)and `postDepreciationRun()` (L225) build journals and update asset rows.- Calc utils: `accounting.utils.ts` — `buildDepreciationLines()` (L447),`getNextPeriodEnd()` (L252), MACRS data.diff --git a/.claude/rules/inventory-system.md b/.claude/rules/inventory-system.mdindex afa48650b4..cab0e8d5b9 100644--- a/.claude/rules/inventory-system.md+++ b/.claude/rules/inventory-system.md@@ -55,7 +55,7 @@ Key service functions (verified):company group, from `functions/lib/seed.data.ts`; backfilled to existing groups by`20260808114732_backfill-scrap-reason-dimension.sql`). Like CustomerType/ItemPostingGroupit is entity-backed — its values resolve live from the `scrapReason` table via- `getEntityDimensionValues`/`getEntityValuesByIds` (accounting.service.ts), so adding a+ `getEntityDimensionValues`/`getEntityValuesByIds` (accounting.ee.service.ts), so adding ascrap reason immediately makes it a selectable/taggable dimension value with no sync step.A tag is only written when the entity type has an **active** `dimension` row — a scrapposting's ScrapReason `extraDimension` is dropped in `post-adjustment.ts` if the dimensiondiff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.mdindex d9648f2915..f23ce87c3e 100644--- a/.claude/rules/mcp-tools-reference.md+++ b/.claude/rules/mcp-tools-reference.md@@ -77,6 +77,7 @@ registered individually:`tool-metadata.json` is **generated**, never hand-edited. Run`npx tsx scripts/generate-mcp.ts`; it parses every `apps/erp/app/modules/*/*.service.ts`+(falling back to the `.ee`-licensed `<module>.ee.service.ts` — e.g. `accounting`)and writes `apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json`(`{ generated, totalTools, modules, tools }`). Each tool entry:`{ name, module, classification, description, paramCount, serviceParams, injectAuth, schema }`.@@ -104,7 +105,8 @@ and writes `apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json``account` · `accounting` · `documents` · `inventory` · `invoicing` · `items` ·`people` · `production` · `purchasing` · `quality` · `resources` · `sales` ·`settings` · `shared` · `users`. Each maps 1:1 to a-`apps/erp/app/modules/<module>/<module>.service.ts` namespace.+`apps/erp/app/modules/<module>/<module>.service.ts` namespace (accounting is the+`.ee`-licensed `accounting.ee.service.ts`; the registry key stays `accounting`).<!-- UNVERIFIED: exact per-module/total tool counts (~1200) drift on every regen — read tool-metadata.json for the live number, don't trust a hardcoded count. -->diff --git a/.claude/rules/project-overview.md b/.claude/rules/project-overview.mdindex 63766bf27b..c524cfab4d 100644--- a/.claude/rules/project-overview.md+++ b/.claude/rules/project-overview.md@@ -44,8 +44,8 @@ pnpm + Turborepo monorepo of `apps/*` and `packages/*`.- **config** — Shared build/test config (tsconfig, vitest, tailwind theme).- **dev** — Local dev CLI (`crbn`) for environment setup and Docker / Supabase /Redis / Inngest orchestration; also exports a Vite plugin.-- **ee** — Enterprise-edition integrations (Slack, Jira, Linear, Xero, OnShape,- Zapier) and accounting/exchange-rate modules.+- **ee** — Enterprise-edition integrations (Slack, Jira, Linear, Xero, OnShape)+ and accounting/exchange-rate modules.- **stripe** — Billing: plans, checkout, subscriptions, webhooks.- **notifications** — Notification infrastructure and types (logic mostly lives inauth/lib/ee).diff --git a/.claude/rules/xero-api-contact-structure.md b/.claude/rules/xero-api-contact-structure.mdindex 226f56babd..5341652f45 100644--- a/.claude/rules/xero-api-contact-structure.md+++ b/.claude/rules/xero-api-contact-structure.md@@ -109,9 +109,11 @@ mapping rows (unique index includes `entityType`).`XeroProvider` (`provider.ts`): OAuth2 against `https://identity.xero.com/connect/token`,base URL `https://api.xero.com/api.xro/2.0`. Every request sends`Authorization: Bearer <token>` + `xero-tenant-id` header. On `401` it refreshes the-token once and retries. OAuth scopes (`packages/ee/src/xero/config.tsx`):-`offline_access`, `accounting.contacts`, `accounting.transactions`,-`accounting.settings`.+token once and retries. OAuth scopes (`packages/ee/src/xero/config.tsx`) — **granular**+(Xero retired the broad `accounting.transactions` scope for apps created after+2026-03-02; granular also works on older apps): `offline_access`,+`accounting.contacts`, `accounting.settings`, `accounting.invoices`,+`accounting.payments`, `accounting.banktransactions`, `accounting.manualjournals`.Contact endpoints used:- `GET /Contacts/{id}`, `GET /Contacts?IDs=a,b,c` — fetch.diff --git a/.claude/skills/carbon-docs/SKILL.md b/.claude/skills/carbon-docs/SKILL.mdindex 609dfdea18..8ad84b67f1 100644--- a/.claude/skills/carbon-docs/SKILL.md+++ b/.claude/skills/carbon-docs/SKILL.md@@ -43,7 +43,7 @@ The **holy source of truth is the actual source code + the LATEST database migra- **Read the newest migration, not the first.** Timestamps order them; a 2026 refactor may have rebuilt asubsystem the cache still describes the old way.- **Document only real, ACTIVE features.** Omit placeholders / inactive / not-yet-shipped things (e.g.- integration registry entries with `active: false` like QuickBooks/Sage/Zapier). Don't surface them.+ integration registry entries with `active: false` like QuickBooks/Sage). Don't surface them.- **When code and cache disagree, code wins** — and note the drift.- **Method:** dispatch a research subagent per feature → return verified facts with `file:line` refs →then write. This is how every flow in the Guide was built. Don't skip it for anything non-trivial.diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex fcae57b3ce..18ed014df6 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -35,6 +35,7 @@ import {LuMailCheck,LuMessageSquare,LuPackageSearch,+ LuRefreshCw,LuShieldAlert,LuShieldX,LuShoppingCart,@@ -237,6 +238,16 @@ function GenericNotification({{...props}/>);+ case NotificationEvent.IntegrationSync:+ // id is the provider id ("rillet", "xero", ...) — link to that+ // integration's settings page, where the Sync Activity tab lives.+ return (+ <Notification+ icon={<LuRefreshCw />}+ to={path.to.integration(id)}+ {...props}+ />+ );case NotificationEvent.JobCompleted:case NotificationEvent.JobAssignment:return (diff --git a/apps/erp/app/components/SettingsSectionHeader.tsx b/apps/erp/app/components/SettingsSectionHeader.tsxindex 6716c5a91a..2745167ef4 100644--- a/apps/erp/app/components/SettingsSectionHeader.tsx+++ b/apps/erp/app/components/SettingsSectionHeader.tsx@@ -15,7 +15,7 @@ export default function SettingsSectionHeader({ children, className }: Props) {return (<pclassName={cn(- "mt-4 text-xxs text-foreground/70 uppercase font-light tracking-wide",+ "mt-4 text-foreground/70 uppercase font-light tracking-wide font-mono text-xs",className)}>diff --git a/apps/erp/app/modules/accounting/accounting.server.ts b/apps/erp/app/modules/accounting/accounting.ee.server.tssimilarity index 100%rename from apps/erp/app/modules/accounting/accounting.server.tsrename to apps/erp/app/modules/accounting/accounting.ee.server.tsdiff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.ee.service.tssimilarity index 87%rename from apps/erp/app/modules/accounting/accounting.service.tsrename to apps/erp/app/modules/accounting/accounting.ee.service.tsindex 8a2f0d13f0..80a8a79dce 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.ee.service.ts@@ -1,5 +1,5 @@import type { Database, Json } from "@carbon/database";-import { getCompanyTimeZone } from "@carbon/database";+import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import type { PeriodPostingSource, ReportPeriodBucket } from "@carbon/utils";import {@@ -2449,6 +2449,114 @@ export type PeriodCloseUnpostedDocument = {const UNPOSTED_DOCUMENT_LIMIT = 25;+/** companyIntegration ids that can carry accounting posting sync. */+const ACCOUNTING_SYNC_INTEGRATION_IDS = ["xero", "quickbooks", "rillet"];++/** Terminal sync dispositions — the journal is accounted for externally. */+const TERMINAL_SYNC_OPERATION_STATUSES = new Set([+ "Completed",+ "Excluded",+ "Skipped"+]);++/**+ * The "External GL sync complete" close auto-check (autoCheckKey+ * "external-gl-sync"): every journal posted into the period must carry a+ * terminal disposition (Completed / Excluded / Skipped) in the+ * accountingSyncOperation ledger for EVERY active accounting integration.+ * Posting sync is ALWAYS-ON when an integration is connected, so the check+ * gates on integration presence alone — it auto-passes (failing false,+ * count 0) only when NO active accounting integration exists. A reversal+ * journal (reversalOfId set) is delivered through the ORIGINAL journal's+ * "<id>:reversal" operation — the reversal row never gets its own ledger+ * entry (see getJournalSyncCompleteness).+ */+export async function getPeriodExternalGlSyncReadiness(+ client: SupabaseClient<Database>,+ companyId: string,+ startDate: string,+ endDate: string+): Promise<{ failing: boolean; count: number; postingSyncEnabled: boolean }> {+ const integrations = await client+ .from("companyIntegration")+ .select("id")+ .eq("companyId", companyId)+ .eq("active", true)+ .in("id", ACCOUNTING_SYNC_INTEGRATION_IDS);++ const enabledIntegrationIds = (integrations.data ?? []).map(+ (integration) => integration.id+ );++ if (enabledIntegrationIds.length === 0) {+ return { failing: false, count: 0, postingSyncEnabled: false };+ }++ const journals = await fetchAllFromTable<{+ id: string;+ reversalOfId: string | null;+ }>(client, "journal", "id, reversalOfId", (query: any) =>+ query+ .eq("companyId", companyId)+ .in("status", ["Posted", "Reversed"])+ .gte("postingDate", startDate)+ .lte("postingDate", endDate)+ .order("id", { ascending: true })+ );++ const journalRows = journals.data ?? [];+ if (journalRows.length === 0) {+ return { failing: false, count: 0, postingSyncEnabled: true };+ }++ // Distinct journals missing a terminal disposition for at least one+ // enabled integration. Bounded loop: at most three integrations.+ const undelivered = new Set<string>();+ for (const integrationId of enabledIntegrationIds) {+ const operations = await fetchAllFromTable<{+ entityId: string;+ status: string;+ }>(client, "accountingSyncOperation", "entityId, status", (query: any) =>+ query+ .eq("companyId", companyId)+ .eq("integration", integrationId)+ .eq("entityType", "journalEntry")+ .order("createdAt", { ascending: false })+ );+ if (operations.error) {+ // Can't verify — fail closed: a Blocker check must not silently pass+ // because its evidence query failed.+ for (const journal of journalRows) {+ undelivered.add(journal.id);+ }+ continue;+ }++ // Newest-first order means first-seen wins as the latest status.+ const latestStatusByEntityId = new Map<string, string>();+ for (const operation of operations.data ?? []) {+ if (!latestStatusByEntityId.has(operation.entityId)) {+ latestStatusByEntityId.set(operation.entityId, operation.status);+ }+ }++ for (const journal of journalRows) {+ const entityId = journal.reversalOfId+ ? `${journal.reversalOfId}:reversal`+ : journal.id;+ const status = latestStatusByEntityId.get(entityId);+ if (!status || !TERMINAL_SYNC_OPERATION_STATUSES.has(status)) {+ undelivered.add(journal.id);+ }+ }+ }++ return {+ failing: undelivered.size > 0,+ count: undelivered.size,+ postingSyncEnabled: true+ };+}/** Business refusal threshold for a journal's debits-vs-credits drift — looser* than EPSILON because multi-currency entries carry real cross-rate residuals.* Shared by the manual-JE validator and the period-close checklist so the two@@ -2488,7 +2596,8 @@ async function computePeriodReadiness(pendingSalesInvoices,pendingPurchaseInvoices,pendingPayments,- pendingMemos+ pendingMemos,+ externalGlSync] = await Promise.all([client.from("journal")@@ -2573,7 +2682,8 @@ async function computePeriodReadiness(.eq("status", "Draft").or(unpostedDateFilter).order("memoId", { ascending: true })- .limit(UNPOSTED_DOCUMENT_LIMIT)+ .limit(UNPOSTED_DOCUMENT_LIMIT),+ getPeriodExternalGlSyncReadiness(client, companyId, startDate, endDate)]);const unbalanced = (journalsInPeriod.data ?? []).filter(@@ -2668,6 +2778,21 @@ async function computePeriodReadiness(failing: unbalanced.length > 0,count: unbalanced.length},+ // Auto-pass only when NO accounting integration is connected:+ // getPeriodExternalGlSyncReadiness returns failing false / count 0 with+ // no active integration (posting sync is always-on when one exists).+ // This evaluator MUST exist for the seeded "External GL sync complete"+ // task (autoCheckKey "external-gl-sync") — an Auto task with no+ // registered evaluator fails closed in evaluateCloseChecklist and would+ // block every close.+ {+ autoCheckKey: "external-gl-sync",+ severity: "Blocker",+ label:+ "Posted journal entries not yet delivered to the external accounting system",+ failing: externalGlSync.failing,+ count: externalGlSync.count+ },{autoCheckKey: "draft-depreciation",severity: "Warning",@@ -5296,3 +5421,545 @@ export async function upsertFixedAssetUsageLog(.select("id").single();}++// /********************************************************\+// * Posting-sync completeness (spec v3, I1) *+// \********************************************************/++export type JournalSyncCompleteness = {+ totalJournals: number;+ dispositions: {+ /** Operation Completed — pushed (individually or inside a batch). */+ synced: number;+ /** Operation Pending / In Flight. */+ pending: number;+ /** Operation Failed / Warning (incl. decision-time DOC_SYNC_DISABLED). */+ blocked: number;+ /** Excluded by policy (FAMILY_OFF / SOURCE_TYPE_DISABLED / MANUAL_DISABLED). */+ excluded: number;+ /** Human opt-out. */+ skipped: number;+ /**+ * Excluded/DOC_BACKED — delivered only while the backing document+ * actually synced (external mapping exists); payments and+ * entity-synced inventory adjustments are provider-native and count+ * delivered by definition.+ */+ docBacked: { delivered: number; undelivered: number };+ };+ /** Posted journals with NO operation row — a missed event (backfill repair). */+ unaccountedJournalIds: string[];+ /** DOC_BACKED journals whose backing document has not reached the provider. */+ undeliveredDocBackedJournalIds: string[];+};++/**+ * The I1 completeness check: every Posted journal since the posting-sync+ * start date must carry exactly one recorded disposition in the+ * accountingSyncOperation ledger. The caller resolves posting-sync settings+ * (this module deliberately does not import @carbon/ee/accounting — see the+ * TS2589 notes in the settings Integrations components) and passes+ * syncFromDate explicitly.+ */+export async function getJournalSyncCompleteness(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ /** companyIntegration id, e.g. "xero" | "quickbooks" | "rillet". */+ integrationId: string;+ /** YYYY-MM-DD; journals dated before this are out of scope. */+ syncFromDate: string;+ /** Restrict to one accounting period (the close auto-check). */+ accountingPeriodId?: string;+ }+): Promise<{ data: JournalSyncCompleteness | null; error: string | null }> {+ const journals = await fetchAllFromTable<{+ id: string;+ sourceType: string | null;+ }>(client, "journal", "id, sourceType", (query: any) => {+ let filtered = query+ .eq("companyId", args.companyId)+ .in("status", ["Posted", "Reversed"])+ .is("reversalOfId", null)+ .gte("postingDate", args.syncFromDate);+ if (args.accountingPeriodId) {+ filtered = filtered.eq("accountingPeriodId", args.accountingPeriodId);+ }+ return filtered.order("id", { ascending: true });+ });+ if (journals.error) {+ return { data: null, error: journals.error.message };+ }++ const operations = await fetchAllFromTable<{+ entityId: string;+ status: string;+ errorCode: string | null;+ metadata: Json | null;+ }>(+ client,+ "accountingSyncOperation",+ "entityId, status, errorCode, metadata",+ (query: any) =>+ query+ .eq("companyId", args.companyId)+ .eq("integration", args.integrationId)+ .eq("entityType", "journalEntry")+ );+ if (operations.error) {+ return { data: null, error: operations.error.message };+ }++ // Original-push operations only: reversal ops (":reversal") supplement the+ // original's disposition, and "daily:" markers are batch bookkeeping+ const operationByJournalId = new Map<+ string,+ { status: string; errorCode: string | null; metadata: Json | null }+ >();+ for (const operation of operations.data ?? []) {+ if (operation.entityId.startsWith("daily:")) continue;+ if (operation.entityId.endsWith(":reversal")) continue;+ operationByJournalId.set(operation.entityId, operation);+ }++ const summary: JournalSyncCompleteness = {+ totalJournals: (journals.data ?? []).length,+ dispositions: {+ synced: 0,+ pending: 0,+ blocked: 0,+ excluded: 0,+ skipped: 0,+ docBacked: { delivered: 0, undelivered: 0 }+ },+ unaccountedJournalIds: [],+ undeliveredDocBackedJournalIds: []+ };++ // DOC_BACKED journals whose backing entity is a Carbon-pushed document+ // (invoice/bill) must have that document actually synced to count as+ // delivered — collect them for the mapping check below+ const docBackedByJournalId = new Map<string, "invoice" | "bill">();++ for (const journal of journals.data ?? []) {+ const operation = operationByJournalId.get(journal.id);+ if (!operation) {+ summary.unaccountedJournalIds.push(journal.id);+ continue;+ }++ switch (operation.status) {+ case "Completed":+ summary.dispositions.synced++;+ break;+ case "Pending":+ case "In Flight":+ summary.dispositions.pending++;+ break;+ case "Failed":+ case "Warning":+ summary.dispositions.blocked++;+ break;+ case "Skipped":+ summary.dispositions.skipped++;+ break;+ case "Excluded": {+ if (operation.errorCode === "DOC_BACKED") {+ const backing =+ operation.metadata &&+ typeof operation.metadata === "object" &&+ !Array.isArray(operation.metadata)+ ? (operation.metadata as Record<string, unknown>).backingDocument+ : null;+ const backingEntityType =+ backing && typeof backing === "object" && !Array.isArray(backing)+ ? (backing as Record<string, unknown>).entityType+ : null;+ if (backingEntityType === "invoice" || backingEntityType === "bill") {+ docBackedByJournalId.set(journal.id, backingEntityType);+ } else {+ // payment / inventoryAdjustment: provider-native representation+ summary.dispositions.docBacked.delivered++;+ }+ } else {+ summary.dispositions.excluded++;+ }+ break;+ }+ default:+ summary.dispositions.blocked++;+ break;+ }+ }++ if (docBackedByJournalId.size > 0) {+ const journalIds = [...docBackedByJournalId.keys()];+ const CHUNK = 300;++ // journal → backing document id via the lines' document linkage+ const documentIdByJournalId = new Map<string, string>();+ for (let i = 0; i < journalIds.length; i += CHUNK) {+ const chunk = journalIds.slice(i, i + CHUNK);+ const lines = await client+ .from("journalLine")+ .select("journalId, documentId")+ .eq("companyId", args.companyId)+ .in("journalId", chunk)+ .not("documentId", "is", null);+ if (lines.error) {+ return { data: null, error: lines.error.message };+ }+ for (const line of lines.data ?? []) {+ if (line.journalId && line.documentId) {+ documentIdByJournalId.set(line.journalId, line.documentId);+ }+ }+ }++ const documentIds = [...new Set(documentIdByJournalId.values())];+ const syncedDocumentIds = new Set<string>();+ for (let i = 0; i < documentIds.length; i += CHUNK) {+ const chunk = documentIds.slice(i, i + CHUNK);+ const mappings = await client+ .from("externalIntegrationMapping")+ .select("entityId")+ .eq("companyId", args.companyId)+ .eq("integration", args.integrationId)+ .in("entityType", ["invoice", "bill"])+ .in("entityId", chunk)+ .not("externalId", "is", null);+ if (mappings.error) {+ return { data: null, error: mappings.error.message };+ }+ for (const mapping of mappings.data ?? []) {+ syncedDocumentIds.add(mapping.entityId);+ }+ }++ for (const journalId of journalIds) {+ const documentId = documentIdByJournalId.get(journalId);+ if (documentId && syncedDocumentIds.has(documentId)) {+ summary.dispositions.docBacked.delivered++;+ } else {+ summary.dispositions.docBacked.undelivered++;+ summary.undeliveredDocBackedJournalIds.push(journalId);+ }+ }+ }++ return { data: summary, error: null };+}++// /********************************************************\+// * Sync tie-out (spec v3 §5, delivered v4 P3) *+// \********************************************************/++/**+ * One (integration × accounting period × account) tie-out cell, written by+ * the tie-out cron. Amounts are net debit-signed. The invariant per cell:+ * carbonPostedAmount = syncedAmount + docBackedAmount + excludedAmount ++ * pendingAmount + blockedAmount (internalDelta) and syncedAmount =+ * providerAmount (externalDelta, null until the provider side is fetched).+ * The table is not in the generated DB types yet, so the query builder is+ * cast and the row payload typed locally — same pattern as+ * @carbon/ee/accounting core/operations.ts.+ */+export type AccountingSyncTieOutCell = {+ id: string;+ companyId: string;+ integration: string;+ accountingPeriodId: string;+ accountId: string;+ carbonPostedAmount: number;+ syncedAmount: number;+ docBackedAmount: number;+ excludedAmount: number;+ pendingAmount: number;+ blockedAmount: number;+ providerAmount: number | null;+ internalDelta: number;+ externalDelta: number | null;+ computedAt: string;+};++export type AccountingSyncTieOutListItem = AccountingSyncTieOutCell & {+ account: { number: string | null; name: string } | null;+ accountingPeriod: {+ startDate: string;+ endDate: string;+ fiscalYear: number | null;+ periodNumber: number | null;+ } | null;+};++/** Attach account (number/name) + period identity to raw tie-out rows. */+async function joinTieOutCells(+ client: SupabaseClient<Database>,+ companyId: string,+ cells: AccountingSyncTieOutCell[]+): Promise<{+ data: AccountingSyncTieOutListItem[] | null;+ error: PostgrestError | null;+}> {+ if (cells.length === 0) {+ return { data: [], error: null };+ }++ const accountIds = [...new Set(cells.map((cell) => cell.accountId))];+ const periodIds = [...new Set(cells.map((cell) => cell.accountingPeriodId))];++ const [accounts, periods] = await Promise.all([+ client.from("account").select("id, number, name").in("id", accountIds),+ client+ .from("accountingPeriod")+ .select("id, startDate, endDate, fiscalYear, periodNumber")+ .eq("companyId", companyId)+ .in("id", periodIds)+ ]);+ if (accounts.error) return { data: null, error: accounts.error };+ if (periods.error) return { data: null, error: periods.error };++ const accountById = new Map(+ (accounts.data ?? []).map((account) => [account.id, account])+ );+ const periodById = new Map(+ (periods.data ?? []).map((period) => [period.id, period])+ );++ return {+ data: cells.map((cell) => {+ const account = accountById.get(cell.accountId);+ const period = periodById.get(cell.accountingPeriodId);+ return {+ ...cell,+ account: account+ ? { number: account.number, name: account.name }+ : null,+ accountingPeriod: period+ ? {+ startDate: period.startDate,+ endDate: period.endDate,+ fiscalYear: period.fiscalYear,+ periodNumber: period.periodNumber+ }+ : null+ };+ }),+ error: null+ };+}++/**+ * The tie-out grid: every persisted cell for the company, joined with+ * account and period identity, newest period first. Optional filters narrow+ * to one integration and/or one accounting period.+ */+export async function getAccountingSyncTieOut(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: {+ integration?: string | string[] | null;+ accountingPeriodId?: string | null;+ accountId?: string | string[] | null;+ }+): Promise<{+ data: AccountingSyncTieOutListItem[] | null;+ error: PostgrestError | null;+}> {+ const rows = await fetchAllFromTable<AccountingSyncTieOutCell>(+ client,+ "accountingSyncTieOut" as any,+ "*",+ (query: any) => {+ let filtered = query.eq("companyId", companyId);+ if (args?.integration) {+ filtered = Array.isArray(args.integration)+ ? filtered.in("integration", args.integration)+ : filtered.eq("integration", args.integration);+ }+ if (args?.accountingPeriodId) {+ filtered = filtered.eq("accountingPeriodId", args.accountingPeriodId);+ }+ if (args?.accountId) {+ filtered = Array.isArray(args.accountId)+ ? filtered.in("accountId", args.accountId)+ : filtered.eq("accountId", args.accountId);+ }+ return filtered.order("id", { ascending: true });+ }+ );+ if (rows.error) return { data: null, error: rows.error };++ const joined = await joinTieOutCells(client, companyId, rows.data ?? []);+ if (joined.error || !joined.data) return joined;++ // Newest period first, then account number, then integration.+ const sorted = [...joined.data].sort((a, b) => {+ const aStart = a.accountingPeriod?.startDate ?? "";+ const bStart = b.accountingPeriod?.startDate ?? "";+ if (aStart !== bStart) return aStart < bStart ? 1 : -1;+ const aAccount = a.account?.number ?? a.account?.name ?? "";+ const bAccount = b.account?.number ?? b.account?.name ?? "";+ if (aAccount !== bAccount) return aAccount < bAccount ? -1 : 1;+ if (a.integration !== b.integration) {+ return a.integration < b.integration ? -1 : 1;+ }+ return 0;+ });++ return { data: sorted, error: null };+}++/** A posted journal behind a tie-out cell, with its sync disposition. */+export type AccountingSyncTieOutJournal = {+ id: string;+ journalEntryId: string;+ postingDate: string;+ sourceType: string | null;+ status: string;+ /** Net debit-signed amount of this journal's lines on the cell's account. */+ accountAmount: number;+ /** Latest sync operation status; null = no operation row recorded. */+ syncStatus: string | null;+};++export type AccountingSyncTieOutCellDetail = {+ cell: AccountingSyncTieOutListItem;+ journals: AccountingSyncTieOutJournal[];+ /** True when more than TIE_OUT_CELL_JOURNAL_LIMIT journals matched. */+ truncated: boolean;+};++const TIE_OUT_CELL_JOURNAL_LIMIT = 200;++/**+ * One tie-out cell plus its drill-down: the posted journals dated inside+ * the cell's period with at least one line on the cell's account, each with+ * the latest accountingSyncOperation disposition for the cell's+ * integration. A reversal journal's disposition lives under the original+ * journal's "<id>:reversal" entity id (see getJournalSyncCompleteness).+ * Bounded to the newest TIE_OUT_CELL_JOURNAL_LIMIT journals.+ */+export async function getAccountingSyncTieOutCell(+ client: SupabaseClient<Database>,+ companyId: string,+ cellId: string+): Promise<{+ data: AccountingSyncTieOutCellDetail | null;+ error: PostgrestError | { message: string } | null;+}> {+ const cellResult = await (client.from("accountingSyncTieOut" as any) as any)+ .select("*")+ .eq("companyId", companyId)+ .eq("id", cellId)+ .single();+ if (cellResult.error || !cellResult.data) {+ return {+ data: null,+ error: cellResult.error ?? { message: "Tie-out cell not found" }+ };+ }++ const joined = await joinTieOutCells(client, companyId, [+ cellResult.data as AccountingSyncTieOutCell+ ]);+ if (joined.error || !joined.data) {+ return { data: null, error: joined.error };+ }+ const cell = joined.data[0];+ if (!cell) {+ return { data: null, error: { message: "Tie-out cell not found" } };+ }+ const period = cell.accountingPeriod;+ if (!period) {+ return {+ data: null,+ error: { message: "Accounting period not found for tie-out cell" }+ };+ }++ const journalsResult = await client+ .from("journal")+ .select(+ "id, journalEntryId, postingDate, sourceType, status, reversalOfId, journalLine!inner(accountId)"+ )+ .eq("companyId", companyId)+ .in("status", ["Posted", "Reversed"])+ .gte("postingDate", period.startDate)+ .lte("postingDate", period.endDate)+ .eq("journalLine.accountId", cell.accountId)+ .order("postingDate", { ascending: false })+ .order("id", { ascending: false })+ .limit(TIE_OUT_CELL_JOURNAL_LIMIT + 1);+ if (journalsResult.error) {+ return { data: null, error: journalsResult.error };+ }++ const allJournals = journalsResult.data ?? [];+ const truncated = allJournals.length > TIE_OUT_CELL_JOURNAL_LIMIT;+ const journalRows = truncated+ ? allJournals.slice(0, TIE_OUT_CELL_JOURNAL_LIMIT)+ : allJournals;++ const journalIds = journalRows.map((journal) => journal.id);+ const CHUNK = 300;++ // Net debit-signed amount per journal on the cell's account.+ const amountByJournalId = new Map<string, number>();+ for (let i = 0; i < journalIds.length; i += CHUNK) {+ const chunk = journalIds.slice(i, i + CHUNK);+ const lines = await client+ .from("journalLine")+ .select("journalId, amount")+ .eq("companyId", companyId)+ .eq("accountId", cell.accountId)+ .in("journalId", chunk);+ if (lines.error) return { data: null, error: lines.error };+ for (const line of lines.data ?? []) {+ amountByJournalId.set(+ line.journalId,+ (amountByJournalId.get(line.journalId) ?? 0) + Number(line.amount ?? 0)+ );+ }+ }++ // Latest disposition per sync entity id (newest-first, first-seen wins).+ const entityIds = journalRows.map((journal) =>+ journal.reversalOfId ? `${journal.reversalOfId}:reversal` : journal.id+ );+ const latestStatusByEntityId = new Map<string, string>();+ for (let i = 0; i < entityIds.length; i += CHUNK) {+ const chunk = entityIds.slice(i, i + CHUNK);+ const operations = await client+ .from("accountingSyncOperation")+ .select("entityId, status, createdAt")+ .eq("companyId", companyId)+ .eq("integration", cell.integration)+ .eq("entityType", "journalEntry")+ .in("entityId", chunk)+ .order("createdAt", { ascending: false });+ if (operations.error) return { data: null, error: operations.error };+ for (const operation of operations.data ?? []) {+ if (!latestStatusByEntityId.has(operation.entityId)) {+ latestStatusByEntityId.set(operation.entityId, operation.status);+ }+ }+ }++ const journals: AccountingSyncTieOutJournal[] = journalRows.map(+ (journal) => ({+ id: journal.id,+ journalEntryId: journal.journalEntryId,+ postingDate: journal.postingDate,+ sourceType: journal.sourceType,+ status: journal.status,+ accountAmount: amountByJournalId.get(journal.id) ?? 0,+ syncStatus:+ latestStatusByEntityId.get(+ journal.reversalOfId ? `${journal.reversalOfId}:reversal` : journal.id+ ) ?? null+ })+ );++ return { data: { cell, journals, truncated }, error: null };+}diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.tsindex 965be0d6ed..4793f94b14 100644--- a/apps/erp/app/modules/accounting/accounting.models.ts+++ b/apps/erp/app/modules/accounting/accounting.models.ts@@ -109,7 +109,7 @@ export const analyticsReportKeys = [export type AnalyticsReportKey = (typeof analyticsReportKeys)[number];// Account scope: exactly one selector. "scrapAccounts" resolves at runtime to-// accountDefault.scrapAccount (getScrapAccountIds in accounting.service.ts).+// accountDefault.scrapAccount (getScrapAccountIds in accounting.ee.service.ts).export type AnalyticsAccountScope =| { classes: (typeof accountClassTypes)[number][] }| { types: (typeof accountTypes)[number][] }diff --git a/apps/erp/app/modules/accounting/accounting.periods.test.ts b/apps/erp/app/modules/accounting/accounting.periods.test.tsindex 0e297c0ccf..7f4ec51f00 100644--- a/apps/erp/app/modules/accounting/accounting.periods.test.ts+++ b/apps/erp/app/modules/accounting/accounting.periods.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from "vitest";// The settings barrel re-exports its UI, which transitively pulls Lingui `msg`-// macros that vitest does not transform. accounting.service only needs+// macros that vitest does not transform. accounting.ee.service only needs// getNextSequence from it, which these tests never exercise — stub it to keep// the import graph light and macro-free.vi.mock("~/modules/settings", () => ({@@ -26,7 +26,7 @@ vi.mock("@carbon/glossary", () => ({import type {PeriodCloseTaskRow,PeriodReadinessCheck-} from "./accounting.service";+} from "./accounting.ee.service";import {checklistTasksToCreate,closeAccountingPeriod,@@ -40,7 +40,7 @@ import {postJournalEntry,reopenAccountingPeriod,skipCloseTask-} from "./accounting.service";+} from "./accounting.ee.service";// ---------------------------------------------------------------------------// Sequential close / reverse-sequential reopen gates (acceptance criteria 4/5)diff --git a/apps/erp/app/modules/accounting/index.ts b/apps/erp/app/modules/accounting/index.tsindex ed0be7c8cf..cbf9fdb972 100644--- a/apps/erp/app/modules/accounting/index.ts+++ b/apps/erp/app/modules/accounting/index.ts@@ -1,3 +1,3 @@+export * from "./accounting.ee.service";export * from "./accounting.models";-export * from "./accounting.service";export * from "./types";diff --git a/apps/erp/app/modules/accounting/types.ts b/apps/erp/app/modules/accounting/types.tsindex 20a8bfa26c..fb9ecd3593 100644--- a/apps/erp/app/modules/accounting/types.ts+++ b/apps/erp/app/modules/accounting/types.ts@@ -1,5 +1,4 @@import type { Database, Json } from "@carbon/database";-import type { periodCloseStatuses } from "./accounting.models";import type {getAccount,getAccountingPeriods,@@ -17,7 +16,8 @@ import type {getPeriodCloseReadiness,getPurchaseLinePivotLines,getReportViews-} from "./accounting.service";+} from "./accounting.ee.service";+import type { periodCloseStatuses } from "./accounting.models";export type Account = NonNullable<Awaited<ReturnType<typeof getAccount>>["data"]@@ -510,7 +510,7 @@ import type {getFixedAssetClasses,getFixedAssetDisposal,getFixedAssets-} from "./accounting.service";+} from "./accounting.ee.service";export type FixedAssetClass = NonNullable<Awaited<ReturnType<typeof getFixedAssetClass>>["data"]diff --git a/apps/erp/app/modules/accounting/ui/Reports/PivotControlBar.tsx b/apps/erp/app/modules/accounting/ui/Reports/PivotControlBar.tsxindex e0735435b4..071b510e9d 100644--- a/apps/erp/app/modules/accounting/ui/Reports/PivotControlBar.tsx+++ b/apps/erp/app/modules/accounting/ui/Reports/PivotControlBar.tsx@@ -32,13 +32,13 @@ import { DimensionEntityTypeIcon } from "~/components/Icons";import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { useUrlParams } from "~/hooks";import { path } from "~/utils/path";+import type { getActiveDimensionsWithValues } from "../../accounting.ee.service";import type {AnalyticsReportKey,PivotMeasure,PivotState} from "../../accounting.models";import { financialReportColumns, pivotMeasures } from "../../accounting.models";-import type { getActiveDimensionsWithValues } from "../../accounting.service";import type { ReportView } from "../../types";import SaveViewModal from "./SaveViewModal";diff --git a/apps/erp/app/modules/accounting/ui/SyncTieOut/SyncTieOutTable.tsx b/apps/erp/app/modules/accounting/ui/SyncTieOut/SyncTieOutTable.tsxnew file mode 100644index 0000000000..69e73be0a0--- /dev/null+++ b/apps/erp/app/modules/accounting/ui/SyncTieOut/SyncTieOutTable.tsx@@ -0,0 +1,233 @@+import { cn } from "@carbon/react";+import { formatDate } from "@carbon/utils";+import { useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useMemo } from "react";+import {+ LuCalendar,+ LuCircleDollarSign,+ LuLink,+ LuScale,+ LuSheet+} from "react-icons/lu";+import { DateTime, Hyperlink, Table } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";+import { path } from "~/utils/path";+import type { AccountingSyncTieOutListItem } from "../../accounting.ee.service";++type SyncTieOutTableProps = {+ data: AccountingSyncTieOutListItem[];+ count: number;+ /** Active accounting integration ids — the integration filter's options. */+ integrations: string[];+ /** All (non-group) accounts — the account filter's options. */+ accounts: { id: string; number: string | null; name: string }[];+};++/** Display labels for the accounting integration ids. */+const INTEGRATION_LABELS: Record<string, string> = {+ xero: "Xero",+ quickbooks: "QuickBooks",+ rillet: "Rillet"+};++function periodLabel(+ period: AccountingSyncTieOutListItem["accountingPeriod"],+ locale: string+): string {+ if (!period) return "—";+ if (period.fiscalYear != null && period.periodNumber != null) {+ return `${period.fiscalYear}-${String(period.periodNumber).padStart(+ 2,+ "0"+ )}`;+ }+ return `${formatDate(period.startDate, undefined, locale)} – ${formatDate(+ period.endDate,+ undefined,+ locale+ )}`;+}++const SyncTieOutTable = memo(+ ({ data, count, integrations, accounts }: SyncTieOutTableProps) => {+ const { t } = useLingui();+ const { locale } = useLocale();+ const currencyFormatter = useCurrencyFormatter();++ const columns = useMemo<ColumnDef<AccountingSyncTieOutListItem>[]>(() => {+ const formatAmount = (value: number | null | undefined) =>+ value == null ? (+ "—"+ ) : (+ <span className="tabular-nums">+ {currencyFormatter.format(Number(value))}+ </span>+ );++ const formatDelta = (value: number | null | undefined) => {+ if (value == null) return "—";+ const nonzero = Math.abs(Number(value)) > 0.001;+ return (+ <span+ className={cn(+ "tabular-nums",+ nonzero && "font-semibold text-destructive"+ )}+ >+ {currencyFormatter.format(Number(value))}+ </span>+ );+ };++ return [+ {+ accessorKey: "accountingPeriodId",+ header: t`Period`,+ cell: ({ row }) => (+ <Hyperlink to={path.to.accountingSyncTieOutCell(row.original.id)}>+ {periodLabel(row.original.accountingPeriod, locale)}+ </Hyperlink>+ ),+ meta: {+ icon: <LuCalendar />,+ exportValue: (row: AccountingSyncTieOutListItem) =>+ periodLabel(row.accountingPeriod, locale)+ }+ },+ {+ accessorKey: "accountId",+ header: t`Account`,+ cell: ({ row }) => (+ <div className="flex flex-col py-1">+ <span className="text-sm">+ {row.original.account?.number ?? "—"}+ </span>+ <span className="text-xs text-muted-foreground line-clamp-1">+ {row.original.account?.name ?? "—"}+ </span>+ </div>+ ),+ meta: {+ icon: <LuSheet />,+ filter: {+ type: "static",+ options: accounts.map((account) => ({+ value: account.id,+ label: (+ <Enumerable+ value={[account.number, account.name]+ .filter(Boolean)+ .join(" - ")}+ />+ )+ }))+ },+ exportValue: (row: AccountingSyncTieOutListItem) =>+ [row.account?.number, row.account?.name].filter(Boolean).join(" ")+ }+ },+ {+ accessorKey: "integration",+ header: t`Integration`,+ cell: ({ row }) => (+ <Enumerable+ value={+ INTEGRATION_LABELS[row.original.integration] ??+ row.original.integration+ }+ />+ ),+ meta: {+ icon: <LuLink />,+ filter: {+ type: "static",+ options: integrations.map((integration) => ({+ value: integration,+ label: (+ <Enumerable+ value={INTEGRATION_LABELS[integration] ?? integration}+ />+ )+ }))+ }+ }+ },+ {+ accessorKey: "carbonPostedAmount",+ header: t`Carbon Posted`,+ cell: ({ row }) => formatAmount(row.original.carbonPostedAmount),+ meta: { icon: <LuCircleDollarSign /> }+ },+ {+ accessorKey: "syncedAmount",+ header: t`Synced`,+ cell: ({ row }) => formatAmount(row.original.syncedAmount),+ meta: { icon: <LuCircleDollarSign /> }+ },+ {+ accessorKey: "docBackedAmount",+ header: t`Doc-Backed`,+ cell: ({ row }) => formatAmount(row.original.docBackedAmount),+ meta: { icon: <LuCircleDollarSign /> }+ },+ {+ accessorKey: "excludedAmount",+ header: t`Excluded`,+ cell: ({ row }) => formatAmount(row.original.excludedAmount),+ meta: { icon: <LuCircleDollarSign /> }+ },+ {+ accessorKey: "pendingAmount",+ header: t`Pending`,+ cell: ({ row }) => formatAmount(row.original.pendingAmount),+ meta: { icon: <LuCircleDollarSign /> }+ },+ {+ accessorKey: "blockedAmount",+ header: t`Blocked`,+ cell: ({ row }) => formatAmount(row.original.blockedAmount),+ meta: { icon: <LuCircleDollarSign /> }+ },+ {+ accessorKey: "providerAmount",+ header: t`Provider`,+ cell: ({ row }) => formatAmount(row.original.providerAmount),+ meta: { icon: <LuCircleDollarSign /> }+ },+ {+ accessorKey: "internalDelta",+ header: t`Internal Delta`,+ cell: ({ row }) => formatDelta(row.original.internalDelta),+ meta: { icon: <LuScale /> }+ },+ {+ accessorKey: "externalDelta",+ header: t`External Delta`,+ cell: ({ row }) => formatDelta(row.original.externalDelta),+ meta: { icon: <LuScale /> }+ },+ {+ accessorKey: "computedAt",+ header: t`Computed At`,+ cell: ({ row }) => <DateTime value={row.original.computedAt} />,+ meta: { icon: <LuCalendar /> }+ }+ ];+ }, [accounts, currencyFormatter, integrations, locale, t]);++ return (+ <Table<AccountingSyncTieOutListItem>+ data={data}+ columns={columns}+ count={count}+ title={t`Sync Tie-Out`}+ />+ );+ }+);++SyncTieOutTable.displayName = "SyncTieOutTable";+export default SyncTieOutTable;diff --git a/apps/erp/app/modules/accounting/ui/SyncTieOut/index.ts b/apps/erp/app/modules/accounting/ui/SyncTieOut/index.tsnew file mode 100644index 0000000000..c37acc0ed4--- /dev/null+++ b/apps/erp/app/modules/accounting/ui/SyncTieOut/index.ts@@ -0,0 +1,3 @@+import SyncTieOutTable from "./SyncTieOutTable";++export { SyncTieOutTable };diff --git a/apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx b/apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsxindex 2f45e83118..1081cb9294 100644--- a/apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx+++ b/apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx@@ -14,6 +14,7 @@ import {LuFileSpreadsheet,LuHandCoins,LuLayers,+ LuScale,LuSheet} from "react-icons/lu";import { usePermissions, useRouteData } from "~/hooks";@@ -22,6 +23,10 @@ import { path } from "~/utils/path";const multiCompanyRoutes = new Set<string>([path.to.intercompany]);+/** Routes that only make sense with an active accounting integration+ * (xero/quickbooks/rillet) — hidden otherwise. */+const integrationRoutes = new Set<string>([path.to.accountingSyncTieOut]);+export default function useAccountingSubmodules() {const { t } = useLingui();const accountingRoutes: AuthenticatedRouteGroup[] = useMemo(@@ -34,6 +39,12 @@ export default function useAccountingSubmodules() {to: path.to.reports,role: "employee",icon: <LuFileSpreadsheet />+ },+ {+ name: t`Sync Tie-Out`,+ to: path.to.accountingSyncTieOut,+ role: "employee",+ icon: <LuScale />}]},@@ -136,14 +147,19 @@ export default function useAccountingSubmodules() {);const permissions = usePermissions();- const routeData = useRouteData<{ hasMultipleCompanies: boolean }>(- path.to.accounting- );+ const routeData = useRouteData<{+ hasMultipleCompanies: boolean;+ accountingIntegrations: string[];+ }>(path.to.accounting);const hasMultipleCompanies = routeData?.hasMultipleCompanies ?? false;+ const hasAccountingIntegration =+ (routeData?.accountingIntegrations?.length ?? 0) > 0;const isRouteVisible = (route: { to: string; role?: string }) => {if (route.role && !permissions.is(route.role as Role)) return false;if (!hasMultipleCompanies && multiCompanyRoutes.has(route.to)) return false;+ if (!hasAccountingIntegration && integrationRoutes.has(route.to))+ return false;return true;};diff --git a/apps/erp/app/modules/agent/kb/docs/integrations/accounting.md b/apps/erp/app/modules/agent/kb/docs/integrations/accounting.mdindex 74e8a9c610..5e7b2603aa 100644--- a/apps/erp/app/modules/agent/kb/docs/integrations/accounting.md+++ b/apps/erp/app/modules/agent/kb/docs/integrations/accounting.md@@ -1,39 +1,90 @@# Accounting-> Post invoices to Xero and keep currency exchange rates current automatically.+> Mirror invoices, bills, and GL journals to Xero, QuickBooks, or Rillet, and keep exchange rates current.-Two accounting integrations: **Xero** mirrors your invoices into an external ledger, and **Exchange Rates**-keeps multi-currency math honest. Exchange Rates is available on every plan; Xero is an Enterprise-(Business-plan) integration.+Carbon keeps an external accounting ledger in step with what happens inside the ERP. Three ledgers are+supported — **Xero**, **QuickBooks Online**, and **Rillet** — plus an **Exchange Rates** service that keeps+multi-currency math honest. The ledger sync is an Enterprise (Business-plan) feature; Exchange Rates is free+on every plan.-## Xero+## How the sync works-Connect over **OAuth**, then choose what Carbon and Xero share. Once connected, Carbon syncs **customers**,-**vendors**, **items**, **sales invoices**, and **bills** with Xero and keeps the two ledgers aligned, with-several of those entities syncing both ways.+Once a ledger is connected, Carbon pushes **customers**, **vendors**, **items**, **sales invoices**, **bills**,+and its automated **GL journals** to the ledger. **Carbon is the source of truth**: its edits always win, and+every record is matched to the same external record each time, so a customer or invoice never duplicates.+Payments recorded in the ledger flow **back** into Carbon to settle the matching invoice or bill.++Connecting a ledger means every automated GL posting Carbon makes is mirrored to it. There is no toggle to+turn that off. Journals you post by hand (`Manual` source) never sync — only automated postings do.++Payment write-back settles the Carbon document from the ledger side: a payment recorded against an invoice in+Xero, QuickBooks, or Rillet comes back as a Carbon payment and an invoice settlement,+then posts to Carbon's general ledger. Rillet can also push Carbon-recorded+payments outbound; Xero and QuickBooks are pull-back only.++## Connect a ledger++Xero and QuickBooks Online connect over **OAuth** — no keys to paste. Rillet uses a per-company **API key**.- ### Connect over OAuth+ ### Authorize the connection- No keys to paste. Authorizing stores the connection.+ For Xero or QuickBooks, authorizing over OAuth stores the connection. For Rillet, paste the connection+ fields below.- ### Choose what's shared+ ### Configure the sync- Set backfill, the per-entity source of truth, and the default account mapping (below).+ Set the account mapping, dimensions, and posting-sync options (below) before the first push.### Run the initial sync- A **Run Initial Sync** action kicks off the first backfill on demand. After that, changes flow continuously, matched to the same Xero record each time so a Carbon customer or invoice never duplicates.+ Xero exposes a **Run Initial Sync** action that seeds the ledger on demand. After that, changes flow+ continuously.- - **Backfill**: Whether to seed Xero with your existing **customers**, **vendors**, and **items** on first connect.- - **Source of truth**: Per entity (customer, vendor, item, invoice, bill): whether **Carbon** or the **accounting system** wins on conflict.- - **Account mapping**: The default **sales** and **purchase** account codes, picked from your Xero chart of accounts.+Rillet's connection fields:++ - **API key**: The Rillet API key that authenticates the connection. Stored as a secret.+ - **Environment**: **Production** (`api.rillet.com`) or **Sandbox** (`sandbox.api.rillet.com`).+ - **Subsidiary ID**: Optional. The Rillet subsidiary (entity) that Carbon posts into, for multi-entity ledgers.+ - **Webhook token**: Optional secret. Inbound payment write-back stays off until this is set.++Xero appears only when `XERO_CLIENT_ID` is set, and QuickBooks Online only when `QUICKBOOKS_CLIENT_ID` is set+(see `docs/platform/self-hosting/environment-variables`). Rillet has no such gate — it+authenticates per company with its own API key, so it is always available.++## Configure the sync++An accounting integration has four tabs beyond the basic connection settings.++ - **Account Mapping**: Map each Carbon posting account to a code in the provider's chart of accounts. Posted journals push using the mapped provider account. Use **Suggest with AI** or **Match by code** to fill the map, then resolve anything left unmapped.+ - **Dimensions**: Map Carbon dimensions to the provider's tracking slots. Xero and QuickBooks expose two slots. Rillet sends every dimension on each line and provisions the matching fields automatically, so the slot editor does not apply to it.+ - **Posting Sync**: Choose how posted journals reach the ledger (see below).+ - **Sync Activity**: Watch every sync operation and retry the ones that failed (see below).++The **Posting Sync** tab controls three things:++ - **Source types**: Posted journals with these source types always sync. A per-type **Daily summary** toggle groups a day's journals of that type into one provider entry instead of sending each individually.+ - **AR / AP representation**: How receivables and payables reach the ledger. Each is either **Documents** (push the invoice or bill itself) or **Off — handled outside the sync**.+ - **Books lock date**: A manual date before which Carbon will not push new entries, so a closed period stays closed.++## Watch it run++The **Sync Activity** tab is an inbox of every sync operation, with **Status**, **Entity**, **Direction**+(push or pull), **Trigger**, **Attempts**, **Last Attempt**, and any **Error**. Filter by status, **Retry** or+**Skip** a failed operation, **Re-send** a completed one, or **Retry all** at once. When failed operations+remain after an outbound sweep, Carbon raises an in-app notification so the sync never fails silently.++Reconciliation runs weekly and writes the **Sync Tie-Out** report (**Accounting → Reports → Sync Tie-Out**).+It lays out one row per accounting period, account, and integration, comparing what Carbon **Posted** against+what actually **Synced**, and against the **Provider** balance. Any **Internal** or **External Delta** is+flagged so a drift between the two ledgers is visible before it becomes a month-end surprise.-Xero only appears when its OAuth client is configured server-side (`XERO_CLIENT_ID`). Without it the-integration is hidden — see `docs/platform/self-hosting/environment-variables`.+Sync Activity answers "did this record make it across?" one operation at a time. Tie-Out answers "do the two+ledgers agree?" per account and period. The Sync Activity tab links straight to the tie-out summary for the+integration.## Exchange rates@@ -45,5 +96,5 @@ then converted into each company's base currency, so every currency you trade in## Related- - Accounting reference How Carbon posts to the ledger — what Xero mirrors.- - Invoices The sales and purchase invoices that sync to Xero.+ - Accounting reference How Carbon posts to the ledger — what the sync mirrors.+ - Invoices The sales and purchase invoices that sync to your ledger.diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.jsonindex 53a51bfd74..94d7df8541 100644--- a/apps/erp/app/modules/agent/kb/manifest.json+++ b/apps/erp/app/modules/agent/kb/manifest.json@@ -45,9 +45,16 @@{"slug": "docs/integrations/accounting","title": "Accounting",- "description": "Post invoices to Xero and keep currency exchange rates current automatically.",+ "description": "Mirror invoices, bills, and GL journals to Xero, QuickBooks, or Rillet, and keep exchange rates current.","keywords": ["accounting", "docs", "integrations"],- "headings": ["Xero", "Exchange rates", "Related"]+ "headings": [+ "How the sync works",+ "Connect a ledger",+ "Configure the sync",+ "Watch it run",+ "Exchange rates",+ "Related"+ ]},{"slug": "docs/integrations/assistant",diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsxindex a9821bb2a9..a65a8fd749 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx@@ -452,14 +452,14 @@ function ReceiptLineItem({return (<div className={cn("flex flex-col border-b p-6 gap-6 relative", className)}>- <div className="absolute top-4 right-6">+ <div className="absolute top-3 right-6"><DropdownMenu><DropdownMenuTrigger asChild><IconButtonaria-label={t`Line options`}variant="secondary"icon={<LuEllipsisVertical />}- size="md"+ size="sm"/></DropdownMenuTrigger><DropdownMenuContent>diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsxindex c4dc138d40..6ae4452b53 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx@@ -439,7 +439,7 @@ function ShipmentLineItem({return (<div className={cn("flex flex-col border-b p-6 gap-6 relative", className)}>- <div className="absolute top-6 right-6">+ <div className="absolute top-3 right-6">{line.fulfillment?.type === "Job" ? (<div className="flex flex-col items-end gap-0"><span>Job</span>@@ -454,7 +454,7 @@ function ShipmentLineItem({aria-label={t`Line options`}variant="secondary"icon={<LuEllipsisVertical />}- size="md"+ size="sm"/></DropdownMenuTrigger><DropdownMenuContent>diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex c3b0eb03bf..3d98f87757 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -13,7 +13,7 @@ import {import type { GenericQueryFilters } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";-import { getCurrencyByCode } from "../accounting/accounting.service";+import { getCurrencyByCode } from "../accounting/accounting.ee.service";import { getEmployeeJob } from "../people/people.service";import {getCustomerPayment,diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsxindex bbfa287813..e72373144b 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx@@ -106,9 +106,12 @@ const SalesInvoiceForm = ({ initialValues }: SalesInvoiceFormProps) => {});const [customerData, paymentTermData] = await Promise.all([- // @ts-ignore TS2589: the composite customerShipping embed trips tsc's- // instantiation-depth limit but not tsgo's — @ts-ignore satisfies both- // (@ts-expect-error would be reported unused by tsgo in CI).+ // @ts-ignore TS2589: the composite customerShipping embed sits on the+ // instantiation-depth cliff — the cliff shifts as unrelated modules+ // join the program (same class as the purchasing.service+ // suppression). ts-ignore (not ts-expect-error) is used so it+ // satisfies both checkers — tsgo would flag an unused expect-error+ // directive in CI — and it survives the cliff receding.carbon?.from("customer").select(diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 091f42b298..036768d1c7 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -13,7 +13,7 @@ import { getEmployeeJob } from "~/modules/people";import type { GenericQueryFilters } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";-import { getCurrencyByCode } from "../accounting/accounting.service";+import { getCurrencyByCode } from "../accounting/accounting.ee.service";import type { PurchaseInvoice } from "../invoicing/types";import {canApproveRequest,@@ -2487,7 +2487,9 @@ export async function getPurchasingRFQSuppliers(client: SupabaseClient<Database>,purchasingRfqId: string): Promise<PostgrestResponse<PurchasingRfqSupplierWithSupplier>> {- // @ts-ignore - nested select instantiation exceeds tsgo depth limit+ // @ts-ignore TS2589 — supabase select-string instantiation depth sits on+ // tsgo's limit; the cliff shifts as unrelated modules join the program.+ // ts-ignore, not ts-expect-error, so it satisfies both tsc and tsgo.return client.from("purchasingRfqSupplier").select("*, supplier(id, name)")diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex 5fbd1fac7c..4d10a228fb 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -380,6 +380,237 @@ export const consoleSettingsValidator = z.object({consoleEnabled: zfd.checkbox()});+/**+ * Retry / Skip / Re-send actions on accounting sync operations. `ids` is a+ * repeated form field (one entry per selected operation) so bulk retry can+ * submit many operations in one POST. The only user-driven target statuses+ * are "Pending" (retry / re-send) and "Skipped" — the service's transition+ * guard re-validates against the row's current status.+ */+export const syncOperationTransitionValidator = z.object({+ intent: z.literal("transition-sync-operation"),+ ids: zfd.repeatable(+ z.array(z.string().min(1)).min(1, { message: "No operations selected" })+ ),+ to: z.enum(["Pending", "Skipped"])+});++/**+ * Saves one account mapping row (Carbon account.id → provider account id)+ * from the integration drawer's Account Mapping tab. externalCode /+ * externalName are display metadata captured from the selected provider+ * account — the journal syncer resolves provider account codes from the+ * mapping's stored externalCode, so the code must be persisted.+ */+export const accountMappingUpsertValidator = z.object({+ intent: z.literal("upsert-account-mapping"),+ accountId: z.string().min(1, { message: "Account is required" }),+ externalId: z.string().min(1, { message: "Provider account is required" }),+ externalCode: zfd.text(z.string().optional()),+ externalName: zfd.text(z.string().optional())+});++const accountMappingEntrySchema = z.object({+ accountId: z.string().min(1),+ externalId: z.string().min(1),+ externalCode: z.string().optional(),+ externalName: z.string().optional()+});++/**+ * Confirm-all from the match-by-code drawer. `mappings` is a repeated form+ * field (per the sync-operation `ids` precedent) — each entry a+ * JSON-encoded proposal validated against the same shape as the single-row+ * upsert.+ */+export const accountMappingBulkUpsertValidator = z.object({+ intent: z.literal("bulk-upsert-account-mappings"),+ mappings: zfd.repeatable(+ z+ .array(+ z+ .string()+ .transform((value, ctx) => {+ try {+ return JSON.parse(value);+ } catch {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Invalid account mapping payload"+ });+ return z.NEVER;+ }+ })+ .pipe(accountMappingEntrySchema)+ )+ .min(1, { message: "No account mappings to save" })+ )+});++/**+ * "Suggest with AI" from the Account Mapping tab. The unmapped Carbon+ * accounts and the provider chart already sit in the loaded tab data, so+ * the client ships them back as two JSON-encoded hidden fields instead of+ * the action re-fetching the provider chart. The AI step only proposes+ * matches (nothing is written) — proposals are confirmed through the same+ * `bulk-upsert-account-mappings` path.+ */+const jsonArrayField = <T extends z.ZodTypeAny>(element: T) =>+ z.string().transform((value, ctx) => {+ try {+ const parsed = JSON.parse(value);+ const result = z.array(element).safeParse(parsed);+ if (!result.success) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Invalid account list payload"+ });+ return z.NEVER;+ }+ return result.data;+ } catch {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Invalid account list payload"+ });+ return z.NEVER;+ }+ });++export const accountMappingAiSuggestValidator = z.object({+ intent: z.literal("ai-suggest-account-mappings"),+ accounts: jsonArrayField(+ z.object({+ id: z.string().min(1),+ number: z.string().nullable(),+ name: z.string()+ })+ ),+ providerAccounts: jsonArrayField(+ z.object({+ id: z.string().min(1),+ code: z.string().nullable().optional(),+ name: z.string().nullable().optional()+ })+ )+});++/**+ * Posting-sync settings persisted (deep-merged) at+ * companyIntegration.metadata.settings.postingSync in the v3 shape. Field+ * semantics mirror @carbon/ee/accounting's PostingSyncSettingsSchema:+ * posting sync is ALWAYS-ON (no master enable, no per-type enable — Manual+ * never syncs per POSTING_POLICY); `sourceTypeConfigs` is a repeated hidden+ * field of "<sourceType>|<granularity>" carrying each non-Manual+ * journal-represented type's granularity; `familyAr`/`familyAp` are the+ * AR/AP representation modes ("journals" is schema-valid but UI-gated until+ * the spec's Phase 4 ships).+ */+export const postingSyncSettingsValidator = z.object({+ intent: z.literal("update-posting-settings"),+ sourceTypeConfigs: zfd.repeatable(+ z.array(+ z+ .string()+ .regex(+ /^[^|]+\|(individual|daily-summary)$/,+ "Malformed source-type config"+ )+ )+ ),+ familyAr: z.enum(["documents", "journals", "none"]),+ familyAp: z.enum(["documents", "journals", "none"]),+ periodLockPolicy: z.enum(["park", "redate"]),+ lockDate: zfd.text(z.string().optional())+});++/**+ * Saves the dimension-slot configuration (Dimensions tab): which Carbon+ * dimensions ride along on pushed journals and which provider analytics+ * target each one maps to. `slots` is a repeated JSON-encoded hidden field+ * (per the bulk account-mapping precedent); zero slots is a valid save+ * (dimension sync off). The action re-validates the slots against the+ * provider's declared targets via validateDimensionSlots before writing.+ */+const dimensionSlotEntrySchema = z.object({+ dimensionId: z.string().min(1),+ target: z.string().min(1),+ autoCreate: z.boolean().optional()+});++export const dimensionSlotsUpdateValidator = z.object({+ intent: z.literal("update-dimension-slots"),+ onUnmappedDimensionValue: z.enum(["warn", "drop"]),+ slots: zfd.repeatable(+ z.array(+ z+ .string()+ .transform((value, ctx) => {+ try {+ return JSON.parse(value);+ } catch {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Invalid dimension slot payload"+ });+ return z.NEVER;+ }+ })+ .pipe(dimensionSlotEntrySchema)+ )+ )+});++/**+ * Saves one dimension-value mapping row (Carbon `<dimensionId>:<valueId>`+ * → provider option id) from the Dimensions tab. externalName is display+ * metadata captured from the selected provider option, mirroring the+ * account-mapping upsert.+ */+export const dimensionValueMappingUpsertValidator = z.object({+ intent: z.literal("upsert-dimension-value-mapping"),+ dimensionId: z.string().min(1, { message: "Dimension is required" }),+ valueId: z.string().min(1, { message: "Value is required" }),+ externalId: z.string().min(1, { message: "Provider value is required" }),+ externalName: zfd.text(z.string().optional())+});++const dimensionValueMappingEntrySchema = z.object({+ dimensionId: z.string().min(1),+ valueId: z.string().min(1),+ externalId: z.string().min(1),+ externalName: z.string().optional()+});++/**+ * Confirm-all from the match-by-name drawer. `mappings` is a repeated+ * JSON-encoded form field — the same shape/precedent as+ * accountMappingBulkUpsertValidator.+ */+export const dimensionValueMappingBulkUpsertValidator = z.object({+ intent: z.literal("bulk-upsert-dimension-value-mappings"),+ mappings: zfd.repeatable(+ z+ .array(+ z+ .string()+ .transform((value, ctx) => {+ try {+ return JSON.parse(value);+ } catch {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Invalid dimension value mapping payload"+ });+ return z.NEVER;+ }+ })+ .pipe(dimensionValueMappingEntrySchema)+ )+ .min(1, { message: "No dimension value mappings to save" })+ )+});+export const quoteLineCategoryMarkupsSettingsValidator = z.object({materialCost: zfd.numeric(z.number().min(0).default(0)),partCost: zfd.numeric(z.number().min(0).default(0)),diff --git a/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx b/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsxnew file mode 100644index 0000000000..8362147be0--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx@@ -0,0 +1,703 @@+import { Combobox, Submit, ValidatedForm } from "@carbon/form";+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerContent,+ DrawerDescription,+ DrawerFooter,+ DrawerHeader,+ DrawerTitle,+ HStack,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ Spinner,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useEffect, useMemo, useRef, useState } from "react";+import { LuArrowRight, LuLink, LuSparkles } from "react-icons/lu";+import { useFetcher } from "react-router";+import { usePermissions } from "~/hooks";+import { accountMappingUpsertValidator } from "~/modules/settings/settings.models";++/**+ * Local structural mirrors of @carbon/ee/accounting's AccountMapping /+ * UnmappedPostingAccount / AccountMatchProposal. Deliberately NOT imported+ * (even type-only) to keep this component's type graph light: marginal+ * additions around the settings module push unrelated supabase+ * select-string parses over TS2589's instantiation-depth limit (see+ * SyncActivity.tsx and the note in ./index.ts — this component isn't+ * barrel-exported for the same reason). The route's loader passes real+ * service rows, so any drift fails typecheck there.+ */+export type AccountMappingChartAccount = {+ id: string;+ code: string;+ name: string;+};++export type AccountMappingRow = {+ id: string;+ accountId: string;+ accountNumber: string | null;+ accountName: string | null;+ externalId: string | null;+ externalCode: string | null;+ externalName: string | null;+};++export type UnmappedAccountRow = {+ id: string;+ number: string | null;+ name: string;+};++export type AccountMatchProposalRow = {+ accountId: string;+ accountNumber: string;+ accountName: string;+ externalId: string;+ externalCode: string;+ externalName: string | null;+};++type AccountMappingProps = {+ /** Shared tab bar, rendered at the top of this tab's body card. */+ tabs?: ReactNode;+ mappings: AccountMappingRow[];+ unmapped: UnmappedAccountRow[];+ chart: AccountMappingChartAccount[];+ proposals: AccountMatchProposalRow[];+};++export function AccountMapping({+ tabs,+ mappings,+ unmapped,+ chart,+ proposals+}: AccountMappingProps) {+ const permissions = usePermissions();+ const canUpdate = permissions.can("update", "settings");+ const [showMatchDrawer, setShowMatchDrawer] = useState(false);+ const [showAiModal, setShowAiModal] = useState(false);++ const chartById = useMemo(+ () => new Map(chart.map((account) => [account.id, account])),+ [chart]+ );+ const chartOptions = useMemo(+ () =>+ chart.map((account) => ({+ value: account.id,+ label: `${account.code} - ${account.name}`+ })),+ [chart]+ );++ return (+ <>+ <DrawerBody className="gap-6">+ {tabs}+ <div className="flex w-full flex-wrap items-center justify-between gap-2">+ <p className="max-w-prose text-xs leading-relaxed text-muted-foreground">+ <Trans>+ Map Carbon accounts to the provider's chart of accounts. Posted+ journals push using the mapped provider account code.+ </Trans>+ </p>+ {chart.length > 0 && (+ <HStack spacing={2}>+ {unmapped.length > 0 && (+ <Button+ size="sm"+ variant="secondary"+ leftIcon={<LuSparkles />}+ isDisabled={!canUpdate}+ onClick={() => setShowAiModal(true)}+ >+ <Trans>Suggest with AI</Trans>+ </Button>+ )}+ <Button+ size="sm"+ variant="secondary"+ leftIcon={<LuLink />}+ onClick={() => setShowMatchDrawer(true)}+ >+ <Trans>Match by code</Trans>+ </Button>+ </HStack>+ )}+ </div>++ <MappingSection+ title={<Trans>Unmapped accounts</Trans>}+ description={+ <Trans>+ Accounts referenced by posting defaults or journal history that+ have no provider mapping yet.+ </Trans>+ }+ count={unmapped.length}+ emptyMessage={<Trans>All posting accounts are mapped</Trans>}+ >+ {unmapped.map((account) => (+ <AccountMappingRowForm+ key={account.id}+ accountId={account.id}+ accountNumber={account.number}+ accountName={account.name}+ currentExternalId={null}+ currentExternalCode={null}+ currentExternalName={null}+ chartById={chartById}+ chartOptions={chartOptions}+ canUpdate={canUpdate}+ />+ ))}+ </MappingSection>++ <MappingSection+ title={<Trans>Mapped accounts</Trans>}+ description={+ <Trans>+ Existing mappings. Pick a different provider account to re-map.+ </Trans>+ }+ count={mappings.length}+ emptyMessage={<Trans>No accounts mapped yet</Trans>}+ >+ {mappings.map((mapping) => (+ <AccountMappingRowForm+ key={mapping.id}+ accountId={mapping.accountId}+ accountNumber={mapping.accountNumber}+ accountName={mapping.accountName}+ currentExternalId={mapping.externalId}+ currentExternalCode={mapping.externalCode}+ currentExternalName={mapping.externalName}+ chartById={chartById}+ chartOptions={chartOptions}+ canUpdate={canUpdate}+ />+ ))}+ </MappingSection>+ </DrawerBody>++ {showMatchDrawer && (+ <MatchByCodeDrawer+ proposals={proposals}+ canUpdate={canUpdate}+ onClose={() => setShowMatchDrawer(false)}+ />+ )}++ {showAiModal && (+ <AiSuggestModal+ unmapped={unmapped}+ chart={chart}+ canUpdate={canUpdate}+ onClose={() => setShowAiModal(false)}+ />+ )}+ </>+ );+}++function MappingSection({+ title,+ description,+ count,+ emptyMessage,+ children+}: {+ title: ReactNode;+ description: ReactNode;+ count: number;+ emptyMessage: ReactNode;+ children: ReactNode;+}) {+ return (+ <section className="flex w-full flex-col gap-2">+ <div className="flex flex-col gap-0.5">+ <div className="flex items-center gap-2">+ <span className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ {title}+ </span>+ <span className="text-[0.6875rem] tabular-nums text-muted-foreground">+ {count}+ </span>+ </div>+ <p className="text-xs text-muted-foreground">{description}</p>+ </div>+ <div className="w-full rounded-lg border border-border">+ {count === 0 ? (+ <div className="flex w-full items-center justify-center py-8 text-sm text-muted-foreground">+ {emptyMessage}+ </div>+ ) : (+ <div className="flex w-full flex-col divide-y divide-border">+ {children}+ </div>+ )}+ </div>+ </section>+ );+}++/**+ * One Carbon account → provider account row. Each row is its own+ * ValidatedForm posting intent=upsert-account-mapping; the provider+ * code/name of the selected option travel in hidden fields because the+ * journal syncer resolves account codes from the mapping metadata.+ */+function AccountMappingRowForm({+ accountId,+ accountNumber,+ accountName,+ currentExternalId,+ currentExternalCode,+ currentExternalName,+ chartById,+ chartOptions,+ canUpdate+}: {+ accountId: string;+ accountNumber: string | null;+ accountName: string | null;+ currentExternalId: string | null;+ currentExternalCode: string | null;+ currentExternalName: string | null;+ chartById: Map<string, AccountMappingChartAccount>;+ chartOptions: { value: string; label: string }[];+ canUpdate: boolean;+}) {+ const { t } = useLingui();+ const [selected, setSelected] = useState<{+ code: string | null;+ name: string | null;+ } | null>(+ currentExternalId+ ? { code: currentExternalCode, name: currentExternalName }+ : null+ );++ // A mapped provider account can be missing from the chart (archived or+ // the chart failed to load): keep it selectable/visible via a fallback+ // option built from the mapping metadata.+ const options = useMemo(() => {+ if (!currentExternalId || chartById.has(currentExternalId)) {+ return chartOptions;+ }+ const fallbackLabel = currentExternalCode+ ? `${currentExternalCode} - ${currentExternalName ?? currentExternalId}`+ : (currentExternalName ?? currentExternalId);+ return [+ { value: currentExternalId, label: fallbackLabel },+ ...chartOptions+ ];+ }, [+ chartById,+ chartOptions,+ currentExternalId,+ currentExternalCode,+ currentExternalName+ ]);++ return (+ <ValidatedForm+ validator={accountMappingUpsertValidator}+ method="post"+ defaultValues={{+ intent: "upsert-account-mapping",+ accountId,+ externalId: currentExternalId ?? undefined+ }}+ className="flex w-full items-center gap-3 p-3"+ >+ <input type="hidden" name="intent" value="upsert-account-mapping" />+ <input type="hidden" name="accountId" value={accountId} />+ <input type="hidden" name="externalCode" value={selected?.code ?? ""} />+ <input type="hidden" name="externalName" value={selected?.name ?? ""} />+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium">+ {accountName ?? accountId}+ </span>+ {accountNumber && (+ <span className="font-mono text-xs text-muted-foreground">+ {accountNumber}+ </span>+ )}+ </div>+ <LuArrowRight className="size-4 shrink-0 text-muted-foreground" />+ <div className="w-[260px] shrink-0">+ <Combobox+ name="externalId"+ options={options}+ placeholder={t`Select provider account`}+ onChange={(option) => {+ if (!option) {+ setSelected(null);+ return;+ }+ const chartAccount = chartById.get(option.value);+ if (chartAccount) {+ setSelected({+ code: chartAccount.code,+ name: chartAccount.name+ });+ } else if (option.value === currentExternalId) {+ setSelected({+ code: currentExternalCode,+ name: currentExternalName+ });+ } else {+ setSelected(null);+ }+ }}+ />+ </div>+ <Submit size="sm" variant="secondary" isDisabled={!canUpdate}>+ <Trans>Save</Trans>+ </Submit>+ </ValidatedForm>+ );+}++/**+ * Preview of exact Carbon-number = provider-code matches with confirm-all.+ * Confirm submits one bulk POST with repeated JSON-encoded `mappings`+ * fields (per the sync-operation `ids` precedent).+ */+function MatchByCodeDrawer({+ proposals,+ canUpdate,+ onClose+}: {+ proposals: AccountMatchProposalRow[];+ canUpdate: boolean;+ onClose: () => void;+}) {+ const fetcher = useFetcher();+ const isSubmitting = fetcher.state !== "idle";+ const submittedRef = useRef(false);++ // Close once the confirm-all POST settles; revalidation has already+ // refreshed the sections behind the drawer.+ useEffect(() => {+ if (submittedRef.current && fetcher.state === "idle") {+ onClose();+ }+ }, [fetcher.state, onClose]);++ const confirmAll = () => {+ if (proposals.length === 0) return;+ const formData = new FormData();+ formData.append("intent", "bulk-upsert-account-mappings");+ for (const proposal of proposals) {+ formData.append(+ "mappings",+ JSON.stringify({+ accountId: proposal.accountId,+ externalId: proposal.externalId,+ externalCode: proposal.externalCode,+ ...(proposal.externalName+ ? { externalName: proposal.externalName }+ : {})+ })+ );+ }+ submittedRef.current = true;+ fetcher.submit(formData, { method: "post" });+ };++ return (+ <Drawer+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <DrawerContent size="sm">+ <DrawerHeader>+ <DrawerTitle>+ <Trans>Match by code</Trans>+ </DrawerTitle>+ <DrawerDescription>+ <Trans>+ Proposed matches where the Carbon account number equals the+ provider account code exactly.+ </Trans>+ </DrawerDescription>+ </DrawerHeader>+ <DrawerBody>+ {proposals.length === 0 ? (+ <div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground">+ <Trans>No unmapped accounts match a provider code</Trans>+ </div>+ ) : (+ <div className="w-full rounded-lg border border-border">+ <Table>+ <Thead>+ <Tr>+ <Th className="px-4">+ <Trans>Carbon account</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Provider account</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {proposals.map((proposal) => (+ <Tr key={proposal.accountId}>+ <Td className="px-4">+ <div className="flex flex-col py-1">+ <span className="text-sm font-medium">+ {proposal.accountName}+ </span>+ <span className="font-mono text-xs text-muted-foreground">+ {proposal.accountNumber}+ </span>+ </div>+ </Td>+ <Td className="px-4">+ <div className="flex flex-col py-1">+ <span className="text-sm font-medium">+ {proposal.externalName ?? proposal.externalCode}+ </span>+ <span className="font-mono text-xs text-muted-foreground">+ {proposal.externalCode}+ </span>+ </div>+ </Td>+ </Tr>+ ))}+ </Tbody>+ </Table>+ </div>+ )}+ </DrawerBody>+ <DrawerFooter>+ <HStack>+ {proposals.length > 0 && (+ <Button+ leftIcon={<LuLink />}+ isDisabled={!canUpdate || isSubmitting}+ isLoading={isSubmitting}+ onClick={confirmAll}+ >+ <Trans>Confirm all</Trans>+ </Button>+ )}+ <Button variant="solid" onClick={onClose}>+ <Trans>Close</Trans>+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </Drawer>+ );+}++/**+ * "Suggest with AI" confirmation modal. Confirming ships the unmapped+ * Carbon accounts + the provider chart to the `ai-suggest-account-mappings`+ * action (gpt-4o best-guess pairing), then previews the returned proposals+ * so the user can review before applying. Applying reuses the same+ * `bulk-upsert-account-mappings` confirm path as Match-by-code — the AI+ * step itself writes nothing.+ */+function AiSuggestModal({+ unmapped,+ chart,+ canUpdate,+ onClose+}: {+ unmapped: UnmappedAccountRow[];+ chart: AccountMappingChartAccount[];+ canUpdate: boolean;+ onClose: () => void;+}) {+ const suggestFetcher = useFetcher<{+ proposals?: AccountMatchProposalRow[];+ }>();+ const applyFetcher = useFetcher();+ const appliedRef = useRef(false);++ const isSuggesting = suggestFetcher.state !== "idle";+ const isApplying = applyFetcher.state !== "idle";+ const proposals = suggestFetcher.data?.proposals;+ const hasSuggested = proposals !== undefined;++ // Close once the apply POST settles; revalidation has already refreshed+ // the sections behind the modal.+ useEffect(() => {+ if (appliedRef.current && applyFetcher.state === "idle") {+ onClose();+ }+ }, [applyFetcher.state, onClose]);++ const suggest = () => {+ const formData = new FormData();+ formData.append("intent", "ai-suggest-account-mappings");+ formData.append("accounts", JSON.stringify(unmapped));+ formData.append("providerAccounts", JSON.stringify(chart));+ suggestFetcher.submit(formData, { method: "post" });+ };++ const applyAll = () => {+ if (!proposals || proposals.length === 0) return;+ const formData = new FormData();+ formData.append("intent", "bulk-upsert-account-mappings");+ for (const proposal of proposals) {+ formData.append(+ "mappings",+ JSON.stringify({+ accountId: proposal.accountId,+ externalId: proposal.externalId,+ ...(proposal.externalCode+ ? { externalCode: proposal.externalCode }+ : {}),+ ...(proposal.externalName+ ? { externalName: proposal.externalName }+ : {})+ })+ );+ }+ appliedRef.current = true;+ applyFetcher.submit(formData, { method: "post" });+ };++ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <ModalContent size="large">+ <ModalHeader>+ <ModalTitle>+ <Trans>Suggest mappings with AI</Trans>+ </ModalTitle>+ <ModalDescription>+ {hasSuggested ? (+ <Trans>+ Review the suggested matches before applying. These are a best+ guess — confirm each is correct.+ </Trans>+ ) : (+ <Trans>+ Carbon will use AI to guess a provider account for each of your{" "}+ {unmapped.length} unmapped accounts. Suggestions are a starting+ point — you can review them before anything is saved.+ </Trans>+ )}+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ {isSuggesting ? (+ <div className="flex w-full items-center justify-center gap-2 py-16 text-sm text-muted-foreground">+ <Spinner className="size-4" />+ <Trans>Generating suggestions…</Trans>+ </div>+ ) : !hasSuggested ? (+ <div className="flex w-full items-center justify-center py-8 text-sm text-muted-foreground">+ <Trans>+ {unmapped.length} unmapped accounts will be matched against{" "}+ {chart.length} provider accounts.+ </Trans>+ </div>+ ) : proposals.length === 0 ? (+ <div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground">+ <Trans>AI couldn't confidently match any accounts</Trans>+ </div>+ ) : (+ <div className="w-full rounded-lg border border-border">+ <Table>+ <Thead>+ <Tr>+ <Th className="px-4">+ <Trans>Carbon account</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Provider account</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {proposals.map((proposal) => (+ <Tr key={proposal.accountId}>+ <Td className="px-4">+ <div className="flex flex-col py-1">+ <span className="text-sm font-medium">+ {proposal.accountName}+ </span>+ <span className="font-mono text-xs text-muted-foreground">+ {proposal.accountNumber}+ </span>+ </div>+ </Td>+ <Td className="px-4">+ <div className="flex flex-col py-1">+ <span className="text-sm font-medium">+ {proposal.externalName ?? proposal.externalCode}+ </span>+ <span className="font-mono text-xs text-muted-foreground">+ {proposal.externalCode}+ </span>+ </div>+ </Td>+ </Tr>+ ))}+ </Tbody>+ </Table>+ </div>+ )}+ </ModalBody>+ <ModalFooter>+ <HStack>+ {!hasSuggested ? (+ <Button+ leftIcon={<LuSparkles />}+ isDisabled={!canUpdate || isSuggesting}+ isLoading={isSuggesting}+ onClick={suggest}+ >+ <Trans>Suggest mappings</Trans>+ </Button>+ ) : (+ proposals.length > 0 && (+ <Button+ leftIcon={<LuLink />}+ isDisabled={!canUpdate || isApplying}+ isLoading={isApplying}+ onClick={applyAll}+ >+ <Trans>Apply suggestions</Trans>+ </Button>+ )+ )}+ <Button variant="solid" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Integrations/DimensionMapping.tsx b/apps/erp/app/modules/settings/ui/Integrations/DimensionMapping.tsxnew file mode 100644index 0000000000..5a9611bdbc--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Integrations/DimensionMapping.tsx@@ -0,0 +1,829 @@+import { Combobox, Radios, Submit, ValidatedForm } from "@carbon/form";+import {+ Badge,+ Button,+ Combobox as ControlledCombobox,+ Drawer,+ DrawerBody,+ DrawerContent,+ DrawerDescription,+ DrawerFooter,+ DrawerHeader,+ DrawerTitle,+ HStack,+ IconButton,+ Switch,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useEffect, useMemo, useRef, useState } from "react";+import { LuArrowRight, LuLink, LuPlus, LuTrash2 } from "react-icons/lu";+import { useFetcher } from "react-router";+import { usePermissions } from "~/hooks";+import {+ dimensionSlotsUpdateValidator,+ dimensionValueMappingUpsertValidator+} from "~/modules/settings/settings.models";++/**+ * Local structural mirrors of @carbon/ee/accounting's DimensionTarget /+ * PostingSyncDimensionSlot / DimensionValueMapping /+ * DimensionValueMatchProposal. Deliberately NOT imported (even type-only)+ * to keep this component's type graph light: marginal additions around+ * the settings module push unrelated supabase select-string parses over+ * TS2589's instantiation-depth limit (see SyncActivity.tsx and the note+ * in ./index.ts — this component isn't barrel-exported for the same+ * reason). The route's loader passes real service rows, so any drift+ * fails typecheck there.+ */+export type DimensionTargetOption = {+ id: string;+ label: string;+ capacity: number;+ values: { id: string; name: string }[];+};++export type CarbonDimensionOption = {+ id: string;+ name: string;+ entityType: string;+ valueCount: number;+};++export type DimensionSlotRow = {+ dimensionId: string;+ target: string;+ autoCreate?: boolean;+};++export type DimensionValueMappingRow = {+ id: string;+ dimensionId: string;+ valueId: string;+ label: string | null;+ externalId: string | null;+ externalName: string | null;+};++export type UnmappedDimensionValueRow = {+ dimensionId: string;+ valueId: string;+ label: string | null;+};++export type DimensionValueMatchProposalRow = {+ dimensionId: string;+ valueId: string;+ label: string;+ externalId: string;+ externalName: string | null;+};++/** Dimensions with more values than this get a high-cardinality warning. */+const HIGH_CARDINALITY_THRESHOLD = 100;++type DimensionMappingProps = {+ /** Shared tab bar, rendered at the top of this tab's body card. */+ tabs?: ReactNode;+ targets: DimensionTargetOption[];+ /** True when the provider target fetch failed (targets renders empty). */+ targetsError: boolean;+ /** Provider structural cap on slots; null = no cap. */+ maxSlots: number | null;+ /** Provider default for new slots' auto-create (Rillet: on). */+ autoCreateDefault: boolean;+ dimensions: CarbonDimensionOption[];+ slots: DimensionSlotRow[];+ onUnmappedDimensionValue: "warn" | "drop";+ mappings: DimensionValueMappingRow[];+ unmapped: UnmappedDimensionValueRow[];+ proposals: DimensionValueMatchProposalRow[];+};++type EditableSlot = {+ key: string;+ dimensionId: string | null;+ target: string | null;+ autoCreate: boolean;+};++export function DimensionMapping({+ tabs,+ targets,+ targetsError,+ maxSlots,+ autoCreateDefault,+ dimensions,+ slots,+ onUnmappedDimensionValue,+ mappings,+ unmapped,+ proposals+}: DimensionMappingProps) {+ const { t } = useLingui();+ const permissions = usePermissions();+ const canUpdate = permissions.can("update", "settings");+ const [showMatchDrawer, setShowMatchDrawer] = useState(false);++ const nextKeyRef = useRef(slots.length);+ const [rows, setRows] = useState<EditableSlot[]>(() =>+ slots.map((slot, index) => ({+ key: `slot-${index}`,+ dimensionId: slot.dimensionId,+ target: slot.target,+ autoCreate: slot.autoCreate ?? autoCreateDefault+ }))+ );++ const dimensionsById = useMemo(+ () => new Map(dimensions.map((dimension) => [dimension.id, dimension])),+ [dimensions]+ );+ const targetsById = useMemo(+ () => new Map(targets.map((target) => [target.id, target])),+ [targets]+ );++ // The saved slot config decides which provider option list each+ // dimension's value-mapping rows offer (value mapping applies to SAVED+ // slots — the unmapped list is computed from them server-side).+ const targetByDimension = useMemo(() => {+ const map = new Map<string, DimensionTargetOption>();+ for (const slot of slots) {+ const target = targetsById.get(slot.target);+ if (target) map.set(slot.dimensionId, target);+ }+ return map;+ }, [slots, targetsById]);++ const totalCapacity = targets.reduce(+ (sum, target) => sum + target.capacity,+ 0+ );+ const slotCap = Math.min(maxSlots ?? Number.POSITIVE_INFINITY, totalCapacity);+ const canAddSlot = canUpdate && rows.length < slotCap;++ const addRow = () => {+ setRows((current) => [+ ...current,+ {+ key: `slot-new-${nextKeyRef.current++}`,+ dimensionId: null,+ target: null,+ autoCreate: autoCreateDefault+ }+ ]);+ };++ const updateRow = (key: string, patch: Partial<EditableSlot>) => {+ setRows((current) =>+ current.map((row) => (row.key === key ? { ...row, ...patch } : row))+ );+ };++ const removeRow = (key: string) => {+ setRows((current) => current.filter((row) => row.key !== key));+ };++ const completeRows = rows.filter(+ (row): row is EditableSlot & { dimensionId: string; target: string } =>+ Boolean(row.dimensionId && row.target)+ );++ const dimensionName = (dimensionId: string) =>+ dimensionsById.get(dimensionId)?.name ?? dimensionId;++ return (+ <>+ <DrawerBody className="gap-6">+ {tabs}+ <div className="flex w-full flex-wrap items-center justify-between gap-2">+ <p className="max-w-prose text-xs leading-relaxed text-muted-foreground">+ <Trans>+ Ride Carbon dimensions along on pushed journals. Each slot maps+ one Carbon dimension to one provider analytics target; the value+ mapping below pairs individual dimension values with provider+ options.+ </Trans>+ </p>+ {targets.length > 0 && slots.length > 0 && (+ <Button+ size="sm"+ variant="secondary"+ leftIcon={<LuLink />}+ onClick={() => setShowMatchDrawer(true)}+ >+ <Trans>Match by name</Trans>+ </Button>+ )}+ </div>++ <ValidatedForm+ validator={dimensionSlotsUpdateValidator}+ method="post"+ defaultValues={{+ intent: "update-dimension-slots",+ onUnmappedDimensionValue+ }}+ className="flex w-full flex-col gap-6"+ >+ <input type="hidden" name="intent" value="update-dimension-slots" />+ {completeRows.map((row) => (+ <input+ key={row.key}+ type="hidden"+ name="slots"+ value={JSON.stringify({+ dimensionId: row.dimensionId,+ target: row.target,+ autoCreate: row.autoCreate+ })}+ />+ ))}++ <section className="flex w-full flex-col gap-2">+ <div className="flex flex-col gap-0.5">+ <div className="flex items-center gap-2">+ <span className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ <Trans>Dimension slots</Trans>+ </span>+ <span className="text-[0.6875rem] tabular-nums text-muted-foreground">+ {rows.length}+ </span>+ </div>+ <p className="text-xs text-muted-foreground">+ <Trans>+ Pick a Carbon dimension and the provider target it posts to.+ Auto-create adds missing provider options by name at push+ time.+ </Trans>+ </p>+ </div>+ {targets.length === 0 && (+ <p className="text-xs text-muted-foreground">+ {targetsError ? (+ <Trans>+ Couldn't load the provider's dimension targets — check the+ connection and reload.+ </Trans>+ ) : (+ <Trans>+ The provider offers no dimension targets. Enable the feature+ in the provider first (e.g. tracking categories, class+ tracking, or fields).+ </Trans>+ )}+ </p>+ )}+ <div className="w-full rounded-lg border border-border">+ {rows.length === 0 ? (+ <div className="flex w-full items-center justify-center py-8 text-sm text-muted-foreground">+ <Trans>No dimension slots configured</Trans>+ </div>+ ) : (+ <div className="flex w-full flex-col divide-y divide-border">+ {rows.map((row) => (+ <SlotRowEditor+ key={row.key}+ row={row}+ rows={rows}+ dimensions={dimensions}+ dimensionsById={dimensionsById}+ targets={targets}+ canUpdate={canUpdate}+ onChange={(patch) => updateRow(row.key, patch)}+ onRemove={() => removeRow(row.key)}+ />+ ))}+ </div>+ )}+ </div>+ <HStack>+ <Button+ size="sm"+ variant="secondary"+ leftIcon={<LuPlus />}+ isDisabled={!canAddSlot}+ onClick={addRow}+ >+ <Trans>Add slot</Trans>+ </Button>+ {maxSlots !== null && (+ <span className="text-xs text-muted-foreground">+ <Trans>+ {rows.length} of {maxSlots} provider slots used+ </Trans>+ </span>+ )}+ </HStack>+ </section>++ <section className="flex w-full flex-col gap-2 border-t border-border pt-4">+ <Radios+ name="onUnmappedDimensionValue"+ label={t`Unmapped dimension values`}+ options={[+ {+ label: t`Park the journal with a warning until the value is mapped`,+ value: "warn"+ },+ {+ label: t`Push the journal without the dimension`,+ value: "drop"+ }+ ]}+ />+ </section>++ <HStack>+ <Submit size="sm" isDisabled={!canUpdate}>+ <Trans>Save dimension settings</Trans>+ </Submit>+ </HStack>+ </ValidatedForm>++ <MappingSection+ title={<Trans>Unmapped values</Trans>}+ description={+ <Trans>+ Dimension values on posted journals that have no provider mapping+ yet.+ </Trans>+ }+ count={unmapped.length}+ emptyMessage={<Trans>All slotted dimension values are mapped</Trans>}+ >+ {unmapped.map((value) => (+ <DimensionValueMappingRowForm+ key={`${value.dimensionId}:${value.valueId}`}+ dimensionId={value.dimensionId}+ dimensionName={dimensionName(value.dimensionId)}+ valueId={value.valueId}+ valueLabel={value.label}+ currentExternalId={null}+ currentExternalName={null}+ target={targetByDimension.get(value.dimensionId) ?? null}+ canUpdate={canUpdate}+ />+ ))}+ </MappingSection>++ <MappingSection+ title={<Trans>Mapped values</Trans>}+ description={+ <Trans>+ Existing mappings. Pick a different provider option to re-map.+ </Trans>+ }+ count={mappings.length}+ emptyMessage={<Trans>No dimension values mapped yet</Trans>}+ >+ {mappings.map((mapping) => (+ <DimensionValueMappingRowForm+ key={mapping.id}+ dimensionId={mapping.dimensionId}+ dimensionName={dimensionName(mapping.dimensionId)}+ valueId={mapping.valueId}+ valueLabel={mapping.label}+ currentExternalId={mapping.externalId}+ currentExternalName={mapping.externalName}+ target={targetByDimension.get(mapping.dimensionId) ?? null}+ canUpdate={canUpdate}+ />+ ))}+ </MappingSection>+ </DrawerBody>++ {showMatchDrawer && (+ <MatchByNameDrawer+ proposals={proposals}+ dimensionName={dimensionName}+ canUpdate={canUpdate}+ onClose={() => setShowMatchDrawer(false)}+ />+ )}+ </>+ );+}++/**+ * One dimension-slot row: Carbon dimension picker → provider target →+ * auto-create switch → remove. Controlled state owned by the parent; the+ * surrounding ValidatedForm posts complete rows as JSON-encoded hidden+ * `slots` fields. Already-used dimensions and at-capacity targets are+ * filtered from the other rows' options (the standalone Combobox has no+ * per-option disable), which enforces one-target-per-dimension and+ * per-target capacity client-side; the action re-validates with+ * validateDimensionSlots server-side.+ */+function SlotRowEditor({+ row,+ rows,+ dimensions,+ dimensionsById,+ targets,+ canUpdate,+ onChange,+ onRemove+}: {+ row: EditableSlot;+ rows: EditableSlot[];+ dimensions: CarbonDimensionOption[];+ dimensionsById: Map<string, CarbonDimensionOption>;+ targets: DimensionTargetOption[];+ canUpdate: boolean;+ onChange: (patch: Partial<EditableSlot>) => void;+ onRemove: () => void;+}) {+ const { t } = useLingui();++ const otherRows = rows.filter((candidate) => candidate.key !== row.key);+ const usedDimensionIds = new Set(+ otherRows.flatMap((candidate) =>+ candidate.dimensionId ? [candidate.dimensionId] : []+ )+ );+ const targetUseCounts = new Map<string, number>();+ for (const candidate of otherRows) {+ if (!candidate.target) continue;+ targetUseCounts.set(+ candidate.target,+ (targetUseCounts.get(candidate.target) ?? 0) + 1+ );+ }++ const dimensionOptions = dimensions+ .filter((dimension) => !usedDimensionIds.has(dimension.id))+ .map((dimension) => ({+ value: dimension.id,+ label: dimension.name,+ helper: t`${dimension.valueCount} values`+ }));+ // A saved slot can reference a dimension that is no longer active: keep+ // it selectable/visible via a fallback option.+ if (row.dimensionId && !dimensionsById.has(row.dimensionId)) {+ dimensionOptions.unshift({+ value: row.dimensionId,+ label: row.dimensionId,+ helper: ""+ });+ }++ const targetOptions = targets+ .filter((target) => (targetUseCounts.get(target.id) ?? 0) < target.capacity)+ .map((target) => ({ value: target.id, label: target.label }));+ // A saved slot can point at a target the provider no longer reports (or+ // the target fetch failed): keep it visible via a fallback option.+ if (row.target && !targets.some((target) => target.id === row.target)) {+ targetOptions.unshift({ value: row.target, label: row.target });+ }++ const selectedDimension = row.dimensionId+ ? dimensionsById.get(row.dimensionId)+ : undefined;+ const isHighCardinality =+ (selectedDimension?.valueCount ?? 0) > HIGH_CARDINALITY_THRESHOLD;++ return (+ <div className="flex w-full items-center gap-3 p-3">+ <div className="flex min-w-0 flex-1 items-center gap-2">+ <ControlledCombobox+ value={row.dimensionId ?? ""}+ options={dimensionOptions}+ placeholder={t`Select dimension`}+ isReadOnly={!canUpdate}+ onChange={(selected) =>+ onChange({ dimensionId: selected ? selected : null })+ }+ />+ {isHighCardinality && (+ <Badge variant="yellow">+ <Trans>{selectedDimension?.valueCount} values</Trans>+ </Badge>+ )}+ </div>+ <LuArrowRight className="size-4 shrink-0 text-muted-foreground" />+ <div className="w-[220px] shrink-0">+ <ControlledCombobox+ value={row.target ?? ""}+ options={targetOptions}+ placeholder={t`Select provider target`}+ isReadOnly={!canUpdate}+ onChange={(selected) =>+ onChange({ target: selected ? selected : null })+ }+ />+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <Switch+ variant="small"+ checked={row.autoCreate}+ disabled={!canUpdate}+ onCheckedChange={(checked) => onChange({ autoCreate: checked })}+ />+ <span className="text-xs text-muted-foreground">+ <Trans>Auto-create</Trans>+ </span>+ </div>+ <IconButton+ aria-label={t`Remove slot`}+ icon={<LuTrash2 />}+ variant="ghost"+ isDisabled={!canUpdate}+ onClick={onRemove}+ />+ </div>+ );+}++function MappingSection({+ title,+ description,+ count,+ emptyMessage,+ children+}: {+ title: ReactNode;+ description: ReactNode;+ count: number;+ emptyMessage: ReactNode;+ children: ReactNode;+}) {+ return (+ <section className="flex w-full flex-col gap-2">+ <div className="flex flex-col gap-0.5">+ <div className="flex items-center gap-2">+ <span className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ {title}+ </span>+ <span className="text-[0.6875rem] tabular-nums text-muted-foreground">+ {count}+ </span>+ </div>+ <p className="text-xs text-muted-foreground">{description}</p>+ </div>+ <div className="w-full rounded-lg border border-border">+ {count === 0 ? (+ <div className="flex w-full items-center justify-center py-8 text-sm text-muted-foreground">+ {emptyMessage}+ </div>+ ) : (+ <div className="flex w-full flex-col divide-y divide-border">+ {children}+ </div>+ )}+ </div>+ </section>+ );+}++/**+ * One Carbon dimension value → provider option row. Each row is its own+ * ValidatedForm posting intent=upsert-dimension-value-mapping; the+ * provider option name travels in a hidden field because the journal+ * syncer surfaces it as the mapping's display metadata (mirroring the+ * account-mapping row form).+ */+function DimensionValueMappingRowForm({+ dimensionId,+ dimensionName,+ valueId,+ valueLabel,+ currentExternalId,+ currentExternalName,+ target,+ canUpdate+}: {+ dimensionId: string;+ dimensionName: string;+ valueId: string;+ valueLabel: string | null;+ currentExternalId: string | null;+ currentExternalName: string | null;+ target: DimensionTargetOption | null;+ canUpdate: boolean;+}) {+ const { t } = useLingui();+ const [selectedName, setSelectedName] = useState<string | null>(+ currentExternalId ? currentExternalName : null+ );++ const optionsById = useMemo(+ () => new Map((target?.values ?? []).map((value) => [value.id, value])),+ [target]+ );++ // A mapped provider option can be missing from the target's list (the+ // dimension is no longer slotted, the option was removed, or the target+ // fetch failed): keep it selectable/visible via a fallback option built+ // from the mapping metadata.+ const options = useMemo(() => {+ const base = (target?.values ?? []).map((value) => ({+ value: value.id,+ label: value.name+ }));+ if (!currentExternalId || optionsById.has(currentExternalId)) {+ return base;+ }+ return [+ {+ value: currentExternalId,+ label: currentExternalName ?? currentExternalId+ },+ ...base+ ];+ }, [currentExternalId, currentExternalName, optionsById, target]);++ return (+ <ValidatedForm+ validator={dimensionValueMappingUpsertValidator}+ method="post"+ defaultValues={{+ intent: "upsert-dimension-value-mapping",+ dimensionId,+ valueId,+ externalId: currentExternalId ?? undefined+ }}+ className="flex w-full items-center gap-3 p-3"+ >+ <input+ type="hidden"+ name="intent"+ value="upsert-dimension-value-mapping"+ />+ <input type="hidden" name="dimensionId" value={dimensionId} />+ <input type="hidden" name="valueId" value={valueId} />+ <input type="hidden" name="externalName" value={selectedName ?? ""} />+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm font-medium">+ {valueLabel ?? valueId}+ </span>+ <span className="text-xs text-muted-foreground">{dimensionName}</span>+ </div>+ <LuArrowRight className="size-4 shrink-0 text-muted-foreground" />+ <div className="w-[260px] shrink-0">+ <Combobox+ name="externalId"+ options={options}+ placeholder={t`Select provider value`}+ onChange={(option) => {+ if (!option) {+ setSelectedName(null);+ return;+ }+ const providerValue = optionsById.get(option.value);+ if (providerValue) {+ setSelectedName(providerValue.name);+ } else if (option.value === currentExternalId) {+ setSelectedName(currentExternalName);+ } else {+ setSelectedName(null);+ }+ }}+ />+ </div>+ <Submit size="sm" variant="secondary" isDisabled={!canUpdate}>+ <Trans>Save</Trans>+ </Submit>+ </ValidatedForm>+ );+}++/**+ * Preview of exact Carbon-label = provider-name matches with confirm-all.+ * Confirm submits one bulk POST with repeated JSON-encoded `mappings`+ * fields (mirroring the account-mapping MatchByCodeDrawer).+ */+function MatchByNameDrawer({+ proposals,+ dimensionName,+ canUpdate,+ onClose+}: {+ proposals: DimensionValueMatchProposalRow[];+ dimensionName: (dimensionId: string) => string;+ canUpdate: boolean;+ onClose: () => void;+}) {+ const fetcher = useFetcher();+ const isSubmitting = fetcher.state !== "idle";+ const submittedRef = useRef(false);++ // Close once the confirm-all POST settles; revalidation has already+ // refreshed the sections behind the drawer.+ useEffect(() => {+ if (submittedRef.current && fetcher.state === "idle") {+ onClose();+ }+ }, [fetcher.state, onClose]);++ const confirmAll = () => {+ if (proposals.length === 0) return;+ const formData = new FormData();+ formData.append("intent", "bulk-upsert-dimension-value-mappings");+ for (const proposal of proposals) {+ formData.append(+ "mappings",+ JSON.stringify({+ dimensionId: proposal.dimensionId,+ valueId: proposal.valueId,+ externalId: proposal.externalId,+ ...(proposal.externalName+ ? { externalName: proposal.externalName }+ : {})+ })+ );+ }+ submittedRef.current = true;+ fetcher.submit(formData, { method: "post" });+ };++ return (+ <Drawer+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <DrawerContent size="sm">+ <DrawerHeader>+ <DrawerTitle>+ <Trans>Match by name</Trans>+ </DrawerTitle>+ <DrawerDescription>+ <Trans>+ Proposed matches where the Carbon dimension value's name equals a+ provider option name exactly.+ </Trans>+ </DrawerDescription>+ </DrawerHeader>+ <DrawerBody>+ {proposals.length === 0 ? (+ <div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground">+ <Trans>No unmapped values match a provider option name</Trans>+ </div>+ ) : (+ <div className="w-full rounded-lg border border-border">+ <Table>+ <Thead>+ <Tr>+ <Th className="px-4">+ <Trans>Carbon value</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Provider option</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {proposals.map((proposal) => (+ <Tr key={`${proposal.dimensionId}:${proposal.valueId}`}>+ <Td className="px-4">+ <div className="flex flex-col py-1">+ <span className="text-sm font-medium">+ {proposal.label}+ </span>+ <span className="text-xs text-muted-foreground">+ {dimensionName(proposal.dimensionId)}+ </span>+ </div>+ </Td>+ <Td className="px-4">+ <span className="text-sm font-medium">+ {proposal.externalName ?? proposal.externalId}+ </span>+ </Td>+ </Tr>+ ))}+ </Tbody>+ </Table>+ </div>+ )}+ </DrawerBody>+ <DrawerFooter>+ <HStack>+ {proposals.length > 0 && (+ <Button+ leftIcon={<LuLink />}+ isDisabled={!canUpdate || isSubmitting}+ isLoading={isSubmitting}+ onClick={confirmAll}+ >+ <Trans>Confirm all</Trans>+ </Button>+ )}+ <Button variant="solid" onClick={onClose}>+ <Trans>Close</Trans>+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </Drawer>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsxindex 838b08a2f7..b739360d5d 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx@@ -19,6 +19,8 @@ import {import {Badge,Button,+ Copy,+ cn,Drawer,DrawerBody,DrawerContent,@@ -28,12 +30,17 @@ import {HStack,ScrollArea,Switch,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,toast,VStack} from "@carbon/react";import { SUPPORT_EMAIL } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useMemo, useState } from "react";+import type { ReactNode } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { useParams } from "react-router";import { Processes } from "~/components/Form";import { MethodIcon, TrackingTypeIcon } from "~/components/Icons";@@ -111,6 +118,23 @@ function GatedIntegrationActionButton({return <IntegrationActionButton action={action} isDisabled={isDisabled} />;}+/**+ * Fills runtime placeholders in a setting's help text — the webhook host and+ * company ID that only exist at render time. Lets a static config description+ * (e.g. Rillet's webhook URL `https://<your-carbon-host>/api/webhook/rillet/<your company ID>`)+ * render as a concrete, copy-pasteable URL.+ */+function fillSettingPlaceholders(+ description: string | undefined,+ host: string,+ companyId: string+): string | undefined {+ if (!description) return description;+ return description+ .replaceAll("<your-carbon-host>", host || "<your-carbon-host>")+ .replaceAll("<your company ID>", companyId);+}+/*** Helper to normalize option to consistent format*/@@ -196,6 +220,9 @@ function SettingFieldInner({ setting }: { setting: IntegrationSetting }) {</div>);+ case "secret":+ return <SecretField setting={setting} />;+case "cards":return <CardSelector setting={setting} />;@@ -279,6 +306,35 @@ function SettingFieldInner({ setting }: { setting: IntegrationSetting }) {}}+/**+ * A masked-but-recoverable credential field. Reuses the `Password` field+ * (form binding + reveal toggle) and adds a copy button that reads the live+ * form value via `useControlField`, so a stored secret prefilled by the+ * loader can be revealed and copied without being re-typed. The value stays+ * editable — pasting a new secret overwrites it. The copy button only shows+ * once the field has a value.+ */+function SecretField({ setting }: { setting: IntegrationSetting }) {+ const [value] = useControlField<string>(setting.name);+ const current = typeof value === "string" ? value : "";++ return (+ <div className="w-full">+ <div className="flex items-end gap-2">+ <div className="min-w-0 flex-1">+ <Password name={setting.name} label={setting.label} />+ </div>+ {current.length > 0 && <Copy text={current} className="shrink-0" />}+ </div>+ {setting.description && (+ <p className="text-xs text-muted-foreground mt-1.5">+ {setting.description}+ </p>+ )}+ </div>+ );+}+/*** Card-style picker for mutually-exclusive options. Wraps the shared* `ChoiceCardGroup` and binds it into the surrounding ValidatedForm via@@ -345,7 +401,7 @@ function SwitchField({ setting }: { setting: IntegrationSetting }) {const checked = value === true;return (- <div className="flex items-center justify-between gap-4 w-full py-2">+ <div className="flex items-center justify-between gap-4 w-full p-3 border rounded-lg"><div className="flex flex-col flex-1"><span className="text-sm font-medium">{setting.label}</span>{setting.description && (@@ -490,6 +546,23 @@ function SettingsGroup({);}+/**+ * An extra tab rendered next to the Settings form (e.g. the accounting+ * Sync Activity inbox). Content is rendered outside the settings+ * ValidatedForm, so tab content can safely contain its own forms.+ */+export type IntegrationFormTab = {+ value: string;+ label: ReactNode;+ /**+ * Render function receiving the shared tab bar, so each tab can render it+ * at the top of its own body card (the white section) instead of the bar+ * living in the gray header. The tab's content component renders `tabs` as+ * the first child of its `DrawerBody`.+ */+ content: (tabs: ReactNode) => ReactNode;+};+interface IntegrationFormProps {metadata: Record<string, unknown>;installed: boolean;@@ -499,13 +572,20 @@ interface IntegrationFormProps {string,Array<{ value: string; label: string; description?: string }>>;+ /** Extra tabs after the Settings tab; when present the drawer widens and+ * a tab bar renders under the header. */+ tabs?: IntegrationFormTab[];+ /** Initially-selected tab value (defaults to the Settings tab). */+ defaultTab?: string;}export function IntegrationForm({installed,metadata,onClose,- dynamicOptions = {}+ dynamicOptions = {},+ tabs = [],+ defaultTab}: IntegrationFormProps) {const { t } = useLingui();const permissions = usePermissions();@@ -513,16 +593,33 @@ export function IntegrationForm({const {company: { id: companyId }} = useUser();+ // Host for filling webhook-URL placeholders in setting help text (client-only).+ const webhookHost = typeof window !== "undefined" ? window.location.host : "";const { id: integrationId } = useParams();+ // Controlled tab state seeded from (and following) the ?tab= deep link:+ // links inside tab content (e.g. the QBD checklist's "Open Account+ // Mapping") update the search param, and this effect switches the tab+ // without a remount. Manual tab clicks don't write the URL.+ const [activeTab, setActiveTab] = useState(defaultTab ?? "settings");+ useEffect(() => {+ if (defaultTab) setActiveTab(defaultTab);+ }, [defaultTab]);+const integration = integrationId? availableIntegrations.find((i) => i.id === integrationId): undefined;- // Extract connected organisation name from metadata (e.g. Xero tenant name)- const connectedOrgName = (metadata?.credentials as Record<string, unknown>)- ?.tenantName as string | undefined;+ // Extract connected organisation name from metadata (e.g. Xero tenant+ // name). New credentials keep provider fields under providerMetadata;+ // legacy rows kept tenantName at the top level.+ const credentialsRecord = metadata?.credentials as+ | Record<string, unknown>+ | undefined;+ const connectedOrgName = ((+ credentialsRecord?.providerMetadata as Record<string, unknown> | undefined+ )?.tenantName ?? credentialsRecord?.tenantName) as string | undefined;// Group settings by their group property// Settings without a group appear first (ungrouped)@@ -541,14 +638,21 @@ export function IntegrationForm({const ungrouped: IntegrationSetting[] = [];const grouped = new Map<string, IntegrationSetting[]>();- for (const baseSetting of integration.settings) {- // Merge dynamic options if available for this setting- const setting: IntegrationSetting = dynamicOptions[baseSetting.name]- ? {- ...baseSetting,- listOptions: dynamicOptions[baseSetting.name]- }- : (baseSetting as IntegrationSetting);+ for (const rawSetting of integration.settings) {+ const baseSetting = rawSetting as IntegrationSetting;+ // Fill runtime placeholders (webhook host + company ID) in help text,+ // then merge dynamic options if available for this setting.+ const setting: IntegrationSetting = {+ ...baseSetting,+ description: fillSettingPlaceholders(+ baseSetting.description,+ webhookHost,+ companyId+ ),+ ...(dynamicOptions[baseSetting.name]+ ? { listOptions: dynamicOptions[baseSetting.name] }+ : {})+ };if (!setting.group) {ungrouped.push(setting);@@ -573,7 +677,7 @@ export function IntegrationForm({groupNames: [...grouped.keys()],groupDescriptions: descriptions};- }, [integration, dynamicOptions]);+ }, [integration, dynamicOptions, webhookHost, companyId]);const initialValues = useMemo(() => {if (!integration) return {};@@ -600,153 +704,211 @@ export function IntegrationForm({return null;}- return (- <Drawer- open- onOpenChange={(open) => {- if (!open) onClose();- }}+ const hasTabs = tabs.length > 0;++ const headerContent = (+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-3">+ <div className="flex size-10 items-center justify-center rounded-lg border border-border bg-card p-1.5">+ <integration.logo className="h-full w-auto" />+ </div>+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <div className="flex items-center gap-2">+ <Heading size="h3" className="truncate">+ {integration.name}+ </Heading>+ {installed && <Badge variant="green">Installed</Badge>}+ </div>+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <Badge variant="secondary">{integration.category}</Badge>+ <span aria-hidden>•</span>+ <span>+ <Trans>Published by Carbon</Trans>+ </span>+ </div>+ </div>+ </div>+ {installed && connectedOrgName && (+ <div className="text-sm text-muted-foreground">+ <Trans>Connected to</Trans>{" "}+ <span className="font-medium text-foreground">+ {connectedOrgName}+ </span>+ </div>+ )}+ </div>+ );++ // Shared tab bar, rendered at the top of each tab's body card (the white+ // section) rather than in the gray header. Null when there are no tabs.+ const tabBar = hasTabs ? (+ <TabsList className="mb-3 self-start">+ <TabsTrigger value="settings">+ <Trans>Settings</Trans>+ </TabsTrigger>+ {tabs.map((tab) => (+ <TabsTrigger key={tab.value} value={tab.value}>+ {tab.label}+ </TabsTrigger>+ ))}+ </TabsList>+ ) : null;++ const settingsForm = (+ <ValidatedForm+ validator={integration.schema}+ method="post"+ action={path.to.integration(integration.id)}+ defaultValues={initialValues}+ className="flex flex-col h-full">- <DrawerContent>- <ValidatedForm- validator={integration.schema}- method="post"- action={path.to.integration(integration.id)}- defaultValues={initialValues}- className="flex flex-col h-full"+ {!hasTabs && <DrawerHeader>{headerContent}</DrawerHeader>}+ <DrawerBody>+ {tabBar}+ <ScrollArea+ className={cn(+ "-mx-2 pb-8",+ hasTabs ? "h-[calc(100dvh-320px)]" : "h-[calc(100dvh-240px)]"+ )}>- <DrawerHeader>- <div className="flex flex-col gap-3">- <div className="flex items-center gap-3">- <div className="flex size-10 items-center justify-center rounded-lg border border-border bg-card p-1.5">- <integration.logo className="h-full w-auto" />- </div>- <div className="flex min-w-0 flex-1 flex-col gap-0.5">- <div className="flex items-center gap-2">- <Heading size="h3" className="truncate">- {integration.name}- </Heading>- {installed && <Badge variant="green">Installed</Badge>}- </div>- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <Badge variant="secondary">{integration.category}</Badge>- <span aria-hidden>•</span>- <span>- <Trans>Published by Carbon</Trans>- </span>- </div>+ <VStack spacing={4} className="px-2">+ <p className="text-xs leading-relaxed text-muted-foreground">+ {integration.description}+ </p>++ {/* @ts-expect-error TS2339 */}+ {integration.setupInstructions && (+ <div className="flex flex-col gap-2">+ <div className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ <Trans>Setup instructions</Trans></div>+ {/* @ts-expect-error TS2339 */}+ <integration.setupInstructions companyId={companyId} /></div>- {installed && connectedOrgName && (- <div className="text-sm text-muted-foreground">- <Trans>Connected to</Trans>{" "}- <span className="font-medium text-foreground">- {connectedOrgName}- </span>- </div>- )}- </div>- </DrawerHeader>- <DrawerBody>- <ScrollArea className="h-[calc(100dvh-240px)] -mx-2 pb-8">- <VStack spacing={4} className="px-2">- <p className="text-xs leading-relaxed text-muted-foreground">- {integration.description}- </p>+ )}- {/* @ts-expect-error TS2339 */}- {integration.setupInstructions && (- <div className="flex flex-col gap-2">- <div className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">- <Trans>Setup instructions</Trans>- </div>- {/* @ts-expect-error TS2339 */}- <integration.setupInstructions companyId={companyId} />- </div>- )}-- {/* Ungrouped settings appear first */}- {ungroupedSettings.length > 0 && (- <VStack spacing={4} className="w-full">- {ungroupedSettings.map((setting) => (- <SettingField key={setting.name} setting={setting} />- ))}- </VStack>- )}-- {/* Grouped settings in flat sections */}- {groupNames.map((groupName) => (- <ConditionalSettingsGroup- key={groupName}- name={groupName}- description={groupDescriptions.get(groupName)}- settings={groupedSettings.get(groupName) ?? []}- />+ {/* Ungrouped settings appear first */}+ {ungroupedSettings.length > 0 && (+ <VStack spacing={4} className="w-full">+ {ungroupedSettings.map((setting) => (+ <SettingField key={setting.name} setting={setting} />))}-- {installed && integrationActions.length > 0 && (- // `has-[button]` collapses the whole section (header included)- // when every gated action is hidden, so the toggle live-controls- // visibility without leaving an empty "Actions" header.- <div className="hidden has-[button]:flex w-full flex-col gap-3 border-t border-border pt-4">- <div className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">- <Trans>Actions</Trans>- </div>- <VStack spacing={2} className="w-full">- {integrationActions.map((action) =>- action.enabledWhenSetting ? (- <GatedIntegrationActionButton- key={action.id}- action={action}- isDisabled={isDisabled}- />- ) : (- <IntegrationActionButton- key={action.id}- action={action}- isDisabled={isDisabled}- />- )- )}- </VStack>- </div>- )}</VStack>- </ScrollArea>- <div className="mt-2">- <p className="text-[0.6875rem] leading-relaxed text-muted-foreground">- Carbon Manufacturing Systems does not endorse any third-party- software.{" "}- <a- href={`mailto:${SUPPORT_EMAIL}`}- className="underline decoration-dotted underline-offset-2 hover:text-foreground"- >- Report integration- </a>- .- </p>- </div>- </DrawerBody>- <DrawerFooter>- <HStack>- {integration.settings.length > 0 ? (- installed ? (- <Submit isDisabled={isDisabled}>- <Trans>Update</Trans>- </Submit>- ) : (- <Submit isDisabled={isDisabled}>- <Trans>Install</Trans>- </Submit>- )- ) : null}-- <Button variant="solid" onClick={onClose}>- <Trans>Close</Trans>- </Button>- </HStack>- </DrawerFooter>- </ValidatedForm>+ )}++ {/* Grouped settings in flat sections */}+ {groupNames.map((groupName) => (+ <ConditionalSettingsGroup+ key={groupName}+ name={groupName}+ description={groupDescriptions.get(groupName)}+ settings={groupedSettings.get(groupName) ?? []}+ />+ ))}++ {installed && integrationActions.length > 0 && (+ // `has-[button]` collapses the whole section (header included)+ // when every gated action is hidden, so the toggle live-controls+ // visibility without leaving an empty "Actions" header.+ <div className="hidden has-[button]:flex w-full flex-col gap-3 border-t border-border pt-4">+ <div className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ <Trans>Actions</Trans>+ </div>+ <VStack spacing={2} className="w-full">+ {integrationActions.map((action) =>+ action.enabledWhenSetting ? (+ <GatedIntegrationActionButton+ key={action.id}+ action={action}+ isDisabled={isDisabled}+ />+ ) : (+ <IntegrationActionButton+ key={action.id}+ action={action}+ isDisabled={isDisabled}+ />+ )+ )}+ </VStack>+ </div>+ )}+ </VStack>+ </ScrollArea>+ <div className="mt-2">+ <p className="text-[0.6875rem] leading-relaxed text-muted-foreground">+ Carbon Manufacturing Systems does not endorse any third-party+ software.{" "}+ <a+ href={`mailto:${SUPPORT_EMAIL}`}+ className="underline decoration-dotted underline-offset-2 hover:text-foreground"+ >+ Report integration+ </a>+ .+ </p>+ </div>+ </DrawerBody>+ <DrawerFooter>+ <HStack>+ {integration.settings.length > 0 ? (+ installed ? (+ <Submit isDisabled={isDisabled}>+ <Trans>Update</Trans>+ </Submit>+ ) : (+ <Submit isDisabled={isDisabled}>+ <Trans>Install</Trans>+ </Submit>+ )+ ) : null}++ <Button variant="solid" onClick={onClose}>+ <Trans>Close</Trans>+ </Button>+ </HStack>+ </DrawerFooter>+ </ValidatedForm>+ );++ return (+ <Drawer+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <DrawerContent size={hasTabs ? "lg" : "md"}>+ {hasTabs ? (+ <Tabs+ value={activeTab}+ onValueChange={setActiveTab}+ className="flex h-full min-h-0 flex-col"+ >+ <DrawerHeader>{headerContent}</DrawerHeader>+ {/* Tab bar now lives inside each tab's body card (rendered by the+ content via `tabBar`), so it sits on the white section. */}+ <TabsContent+ forceMount+ value="settings"+ className="min-h-0 flex-1 outline-none data-[state=inactive]:hidden"+ >+ {settingsForm}+ </TabsContent>+ {tabs.map((tab) => (+ <TabsContent+ forceMount+ key={tab.value}+ value={tab.value}+ className="flex min-h-0 flex-1 flex-col overflow-hidden outline-none data-[state=inactive]:hidden"+ >+ {tab.content(tabBar)}+ </TabsContent>+ ))}+ </Tabs>+ ) : (+ settingsForm+ )}</DrawerContent></Drawer>);diff --git a/apps/erp/app/modules/settings/ui/Integrations/PostingSyncSettings.tsx b/apps/erp/app/modules/settings/ui/Integrations/PostingSyncSettings.tsxnew file mode 100644index 0000000000..93c5b6b04c--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Integrations/PostingSyncSettings.tsx@@ -0,0 +1,334 @@+import {+ ChoiceCardGroup,+ DatePicker,+ Select,+ Submit,+ useControlField,+ ValidatedForm+} from "@carbon/form";+import {+ Badge,+ Checkbox,+ DrawerBody,+ DrawerFooter,+ HStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useState } from "react";+import { usePermissions } from "~/hooks";+import { postingSyncSettingsValidator } from "~/modules/settings/settings.models";++/**+ * Local structural mirrors of @carbon/ee/accounting's PostingSyncSettings /+ * POSTING_POLICY rows (v3). Deliberately NOT imported (even type-only) to+ * keep this component's type graph light: marginal additions around the+ * settings module push unrelated supabase select-string parses over+ * TS2589's instantiation-depth limit (see SyncActivity.tsx and the note in+ * ./index.ts — this component isn't barrel-exported for the same reason).+ * The route passes the resolved settings + policy rows, so drift fails+ * typecheck at that call site.+ */+export type PostingSyncFamilyMode = "documents" | "journals" | "none";++export type PostingSyncSettingsValues = {+ families: { ar: PostingSyncFamilyMode; ap: PostingSyncFamilyMode };+ sourceTypes: Record<+ string,+ { enabled: boolean; granularity: "individual" | "daily-summary" }+ >;+ periodLockPolicy: "park" | "redate";+ lockDate?: string;+};++export type PostingSyncPolicyRow = {+ sourceType: string;+ representation: "journal" | "document";+ family: "ar" | "ap" | "per-line" | null;+};++type PostingSyncSettingsProps = {+ /** Shared tab bar, rendered at the top of this tab's body card. */+ tabs?: ReactNode;+ settings: PostingSyncSettingsValues;+ /** POSTING_POLICY rows (every source type), provided by the loader. */+ policy: PostingSyncPolicyRow[];+ /** Posting-account mapping coverage, from the account-mapping tab data. */+ mappingReadiness: { mapped: number; required: number } | null;+};++type SourceTypeRowState = {+ dailySummary: boolean;+};++/**+ * Period-lock policy picker rendered as card-style radios — the same+ * affordance as the Rillet Production/Sandbox environment selector.+ * Bound into the surrounding ValidatedForm via `useControlField` + a hidden+ * input (the controlled `ChoiceCardGroup` doesn't post a value on its own).+ */+function PeriodLockPolicyChoice() {+ const { t } = useLingui();+ const [value, setValue] = useControlField<string>("periodLockPolicy");+ const current = value === "redate" ? "redate" : "park";++ return (+ <div className="w-full">+ <div className="flex flex-col gap-0.5 pb-2">+ <div className="text-sm font-medium text-foreground">+ {t`Period lock policy`}+ </div>+ <p className="text-xs text-muted-foreground">+ {t`What happens when a journal is dated in a locked period.`}+ </p>+ </div>+ <ChoiceCardGroup+ value={current}+ onChange={setValue}+ options={[+ {+ value: "park",+ title: t`Park as error`,+ description: t`Hold the journal as a warning to fix.`+ },+ {+ value: "redate",+ title: t`Re-date to first open day`,+ description: t`Push it re-dated to the first open day, keeping the original date in the narration.`+ }+ ]}+ />+ <input type="hidden" name="periodLockPolicy" value={current} />+ </div>+ );+}++export function PostingSyncSettings({+ tabs,+ settings,+ policy,+ mappingReadiness+}: PostingSyncSettingsProps) {+ const { t } = useLingui();+ const permissions = usePermissions();+ const canUpdate = permissions.can("update", "settings");++ // Always-on: every automated (non-Manual) journal type syncs; Manual never+ // does and is never rendered. The only per-type control is granularity.+ const journalRows = policy.filter(+ (row) => row.representation === "journal" && row.sourceType !== "Manual"+ );+ const documentRows = policy.filter(+ (row) => row.representation === "document"+ );++ const [rowState, setRowState] = useState<Record<string, SourceTypeRowState>>(+ () =>+ Object.fromEntries(+ journalRows.map((row) => {+ const config = settings.sourceTypes[row.sourceType];+ return [+ row.sourceType,+ { dailySummary: config?.granularity === "daily-summary" }+ ];+ })+ )+ );++ const setRow = (+ sourceType: string,+ patch: Partial<SourceTypeRowState>+ ): void => {+ setRowState((current) => ({+ ...current,+ [sourceType]: {+ dailySummary: current[sourceType]?.dailySummary ?? false,+ ...patch+ }+ }));+ };++ // The AR/AP "journals" representation ships with Phase 4 of the v3 spec;+ // until then only documents/none are offered.+ const familyOptions = [+ { label: t`Documents`, value: "documents" },+ { label: t`Off — handled outside the sync`, value: "none" }+ ];++ const familyLabel = (family: PostingSyncPolicyRow["family"]) => {+ if (family === "ar") return t`AR`;+ if (family === "ap") return t`AP`;+ if (family === "per-line") return t`AR/AP`;+ return null;+ };++ return (+ <ValidatedForm+ validator={postingSyncSettingsValidator}+ method="post"+ defaultValues={{+ intent: "update-posting-settings",+ familyAr:+ settings.families.ar === "journals"+ ? "documents"+ : settings.families.ar,+ familyAp:+ settings.families.ap === "journals"+ ? "documents"+ : settings.families.ap,+ periodLockPolicy: settings.periodLockPolicy,+ lockDate: settings.lockDate+ }}+ className="flex h-full min-h-0 flex-1 flex-col"+ >+ <input type="hidden" name="intent" value="update-posting-settings" />+ {journalRows.map((row) => (+ <input+ key={row.sourceType}+ type="hidden"+ name="sourceTypeConfigs"+ value={`${row.sourceType}|${+ rowState[row.sourceType]?.dailySummary+ ? "daily-summary"+ : "individual"+ }`}+ />+ ))}+ <DrawerBody className="gap-6">+ {tabs}+ {mappingReadiness && (+ <div className="flex items-center justify-between rounded-lg border border-border px-3 py-2.5 text-sm">+ <span>+ <Trans>+ {mappingReadiness.mapped} of {mappingReadiness.required} posting+ accounts mapped+ </Trans>+ </span>+ {mappingReadiness.mapped < mappingReadiness.required ? (+ <a+ className="text-primary underline-offset-2 hover:underline"+ href="?tab=account-mapping"+ >+ <Trans>Map accounts</Trans>+ </a>+ ) : (+ <Badge variant="green">+ <Trans>Ready</Trans>+ </Badge>+ )}+ </div>+ )}++ <section className="flex w-full flex-col gap-2">+ <div className="flex flex-col gap-0.5">+ <span className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ <Trans>Source types</Trans>+ </span>+ <p className="text-xs text-muted-foreground">+ <Trans>+ Posted journals with these source types always sync. Daily+ summary groups a day's journals into one provider entry per+ account.+ </Trans>+ </p>+ </div>+ <div className="flex w-full flex-col divide-y divide-border rounded-lg border border-border">+ {journalRows.map((row) => {+ const state = rowState[row.sourceType];+ return (+ <div+ key={row.sourceType}+ className="flex items-center gap-3 px-3 py-2.5"+ >+ <span className="flex-1 text-sm">{row.sourceType}</span>+ <div className="flex items-center gap-2">+ <Checkbox+ id={`postingGranularity:${row.sourceType}`}+ checked={state?.dailySummary ?? false}+ disabled={!canUpdate}+ onCheckedChange={(next) =>+ setRow(row.sourceType, {+ dailySummary: next === true+ })+ }+ />+ <label+ htmlFor={`postingGranularity:${row.sourceType}`}+ className="cursor-pointer text-xs text-muted-foreground"+ >+ <Trans>Daily summary</Trans>+ </label>+ </div>+ </div>+ );+ })}+ </div>+ </section>++ <section className="flex w-full flex-col gap-2 border-t border-border pt-4">+ <div className="flex flex-col gap-0.5">+ <span className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ <Trans>AR / AP representation</Trans>+ </span>+ <p className="text-xs text-muted-foreground">+ <Trans>+ Documents pushes invoices, bills and payments as native provider+ documents; their journals are recorded as covered by the+ document. It also pulls payments recorded in the provider back+ into Carbon, closing the matching invoice or bill and posting a+ Carbon GL journal. Off records them as deliberately excluded.+ </Trans>+ </p>+ </div>+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <Select+ name="familyAr"+ label={t`Receivables (AR)`}+ options={familyOptions}+ />+ <Select+ name="familyAp"+ label={t`Payables (AP)`}+ options={familyOptions}+ />+ </div>+ <div className="flex w-full flex-col divide-y divide-border rounded-lg border border-border">+ {documentRows.map((row) => (+ <div+ key={row.sourceType}+ className="flex items-center gap-3 px-3 py-2.5"+ >+ <span className="flex-1 text-sm">{row.sourceType}</span>+ <Badge variant="secondary">{familyLabel(row.family)}</Badge>+ <Badge variant="outline">+ <Trans>Document</Trans>+ </Badge>+ </div>+ ))}+ </div>+ </section>++ <section className="flex w-full flex-col gap-3 border-t border-border pt-4">+ <PeriodLockPolicyChoice />+ </section>++ <section className="flex w-full flex-col gap-3 border-t border-border pt-4">+ <DatePicker name="lockDate" label={t`Books lock date (manual)`} />+ <p className="text-xs text-muted-foreground">+ <Trans>+ Journals dated on or before this date are treated as locked.+ Merged with the provider-reported lock date when both exist.+ </Trans>+ </p>+ </section>+ </DrawerBody>+ <DrawerFooter>+ <HStack>+ <Submit isDisabled={!canUpdate}>+ <Trans>Save</Trans>+ </Submit>+ </HStack>+ </DrawerFooter>+ </ValidatedForm>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsxnew file mode 100644index 0000000000..78d2007e9d--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx@@ -0,0 +1,958 @@+import {+ Badge,+ Button,+ cn,+ Drawer,+ DrawerBody,+ DrawerContent,+ DrawerDescription,+ DrawerFooter,+ DrawerHeader,+ DrawerTitle,+ HStack,+ IconButton,+ Status,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ Tr+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useCallback, useMemo, useState } from "react";+import {+ LuArrowDownLeft,+ LuArrowUpRight,+ LuChevronLeft,+ LuChevronRight,+ LuCircleSlash,+ LuRefreshCw,+ LuRotateCw,+ LuScale,+ LuSend,+ LuTriangleAlert+} from "react-icons/lu";+import { Link, useFetcher, useRevalidator } from "react-router";+import { useDateFormatter, usePermissions, useUrlParams } from "~/hooks";+import { path } from "~/utils/path";++/**+ * Local structural mirrors of @carbon/ee/accounting's SyncOperation /+ * SyncOperationStatus. Deliberately NOT imported (even type-only): this+ * component is re-exported through the ~/modules/settings barrel, and a+ * type edge from that barrel into @carbon/ee/accounting pushes unrelated+ * supabase select-string parses over TS2589's instantiation-depth limit+ * (usePurchaseInvoiceAutoFill). The route's loader passes real+ * SyncOperation rows, so any drift from the real shape fails typecheck at+ * that call site.+ */+export type SyncOperationStatus =+ | "Pending"+ | "In Flight"+ | "Completed"+ | "Failed"+ | "Warning"+ | "Skipped"+ | "Excluded";++export type SyncActivityOperation = {+ id: string;+ companyId: string;+ integration: string;+ entityType: string;+ entityId: string;+ direction: "push-to-accounting" | "pull-from-accounting";+ trigger: string;+ status: SyncOperationStatus;+ idempotencyKey: string;+ attemptCount: number;+ lastAttemptAt: string | null;+ completedAt: string | null;+ errorCode: string | null;+ errorMessage: string | null;+ externalId: string | null;+ metadata: Record<string, unknown> | null;+ createdBy: string;+ createdAt: string;+ updatedBy: string | null;+ updatedAt: string | null;+};++/**+ * Structural mirror of the reconciliation cron's drift entries+ * (@carbon/jobs accounting-reconciliation.ts), stored by the weekly cron at+ * companyIntegration.metadata.settings.postingSync.lastReconciliation.+ * Kept local for the same TS2589 reason as the operation types above.+ */+export type SyncReconciliationDriftEntry =+ | {+ type: "missing";+ externalId: string;+ journalId: string;+ amount?: number;+ }+ | {+ type: "mismatch";+ month: string;+ carbonTotal: number;+ providerTotal: number;+ };++export type SyncReconciliationReport = {+ runAt: string;+ drift: SyncReconciliationDriftEntry[];+};++type SyncActivityProps = {+ /** Shared tab bar, rendered at the top of this tab's body card. */+ tabs?: ReactNode;+ operations: SyncActivityOperation[];+ count: number;+ status: SyncOperationStatus | null;+ page: number;+ pageSize: number;+ /**+ * Latest reconciliation report from the integration's metadata+ * (settings.postingSync.lastReconciliation). Rendered as a warning+ * banner + drift table above the operations when drift exists.+ */+ lastReconciliation?: SyncReconciliationReport | null;+ /**+ * Tie-out summary for this integration (accountingSyncTieOut): latest+ * computedAt + how many period × account cells carry a nonzero internal+ * or external delta. Null / undefined = no tie-out rows exist yet, and+ * the card renders nothing.+ */+ tieOut?: {+ computedAt: string | null;+ deltaCellCount: number;+ cellCount: number;+ } | null;+};++const STATUS_FILTERS: SyncOperationStatus[] = [+ "Pending",+ "In Flight",+ "Completed",+ "Failed",+ "Warning",+ "Skipped",+ "Excluded"+];++const STATUS_COLORS: Record<+ SyncOperationStatus,+ "yellow" | "blue" | "green" | "red" | "orange" | "gray"+> = {+ Pending: "yellow",+ "In Flight": "blue",+ Completed: "green",+ Failed: "red",+ Warning: "orange",+ Skipped: "gray",+ Excluded: "gray"+};++/**+ * Display labels for sync entity types (keys of the accounting sync engine's+ * ENTITY_DEFINITIONS). Kept local so this client component doesn't import+ * runtime code from @carbon/ee/accounting.+ */+const ENTITY_LABELS: Record<string, string> = {+ customer: "Customer",+ vendor: "Vendor",+ item: "Item",+ employee: "Employee",+ purchaseOrder: "Purchase Order",+ bill: "Bill",+ salesOrder: "Sales Order",+ invoice: "Invoice",+ payment: "Payment",+ inventoryAdjustment: "Inventory Adjustment",+ journalEntry: "Journal Entry"+};++/**+ * Entity types that have a route helper. Everything else (payments, journal+ * entries, pulled records keyed by remote ids) renders as plain text.+ */+const ENTITY_PATHS: Record<string, (id: string) => string> = {+ customer: path.to.customer,+ vendor: path.to.supplier,+ item: path.to.part,+ employee: path.to.employeeAccount,+ purchaseOrder: path.to.purchaseOrder,+ bill: path.to.purchaseInvoice,+ salesOrder: path.to.salesOrder,+ invoice: path.to.salesInvoice+};++function getEntityLabel(entityType: string): string {+ return ENTITY_LABELS[entityType] ?? entityType;+}++function getEntityPath(operation: SyncActivityOperation): string | null {+ const pathFn = ENTITY_PATHS[operation.entityType];+ return pathFn ? pathFn(operation.entityId) : null;+}++function formatTrigger(trigger: string): string {+ return trigger.charAt(0).toUpperCase() + trigger.slice(1);+}++/**+ * UI actions by status (mirrors the service's transition guard):+ * Retry (Failed/Warning/Skipped → Pending — Skipped covers both a human+ * opt-out and the drain's machine no-op close, either of which a user may+ * re-drive), Skip (Failed/Warning/Pending → Skipped), Re-send+ * (Completed/Excluded → Pending — an Excluded journal re-decides against+ * the current posting-policy config).+ */+function getAvailableTransitions(status: SyncOperationStatus): {+ retry: boolean;+ skip: boolean;+ resend: boolean;+} {+ return {+ retry: status === "Failed" || status === "Warning" || status === "Skipped",+ skip: status === "Failed" || status === "Warning" || status === "Pending",+ resend: status === "Completed" || status === "Excluded"+ };+}++export function SyncActivity({+ tabs,+ operations,+ count,+ status,+ page,+ pageSize,+ lastReconciliation,+ tieOut+}: SyncActivityProps) {+ const { t } = useLingui();+ const permissions = usePermissions();+ const canUpdate = permissions.can("update", "settings");+ const { formatRelativeTime } = useDateFormatter();+ const [, setParams] = useUrlParams();+ const [selectedId, setSelectedId] = useState<string | null>(null);++ const fetcher = useFetcher();+ const isTransitioning = fetcher.state !== "idle";++ // The tab's data (operations, tie-out, reconciliation) lives in the+ // route loader, so a manual refresh re-runs the loader in place.+ const revalidator = useRevalidator();+ const isRefreshing = revalidator.state === "loading";++ const submitTransition = useCallback(+ (ids: string[], to: "Pending" | "Skipped") => {+ if (ids.length === 0) return;+ const formData = new FormData();+ formData.append("intent", "transition-sync-operation");+ formData.append("to", to);+ for (const id of ids) {+ formData.append("ids", id);+ }+ fetcher.submit(formData, { method: "post" });+ },+ [fetcher]+ );++ const setStatusFilter = useCallback(+ (nextStatus: SyncOperationStatus | null) => {+ setParams({+ syncStatus: nextStatus ?? undefined,+ syncPage: undefined+ });+ },+ [setParams]+ );++ const setPage = useCallback(+ (nextPage: number) => {+ setParams({+ syncPage: nextPage > 1 ? String(nextPage) : undefined+ });+ },+ [setParams]+ );++ // Keep the detail drawer in sync with revalidated data: after a+ // transition the row's status updates (or the row leaves the current+ // filter, closing the drawer).+ const selectedOperation = useMemo(+ () => operations.find((operation) => operation.id === selectedId) ?? null,+ [operations, selectedId]+ );++ const retryableIds = useMemo(+ () =>+ operations+ .filter(+ (operation) =>+ operation.status === "Failed" || operation.status === "Warning"+ )+ .map((operation) => operation.id),+ [operations]+ );++ const totalPages = Math.max(1, Math.ceil(count / pageSize));+ const from = count === 0 ? 0 : (page - 1) * pageSize + 1;+ const to = Math.min(count, (page - 1) * pageSize + operations.length);++ return (+ <>+ <DrawerBody className="gap-4">+ {tabs}+ <ReconciliationDrift lastReconciliation={lastReconciliation} />+ <TieOutSummary tieOut={tieOut} />++ <div className="flex w-full flex-wrap items-center justify-between gap-2">+ <div className="flex flex-wrap items-center gap-1">+ <Button+ size="sm"+ variant={status === null ? "active" : "ghost"}+ onClick={() => setStatusFilter(null)}+ >+ <Trans>All</Trans>+ </Button>+ {STATUS_FILTERS.map((filter) => (+ <Button+ key={filter}+ size="sm"+ variant={status === filter ? "active" : "ghost"}+ onClick={() => setStatusFilter(filter)}+ >+ {filter}+ </Button>+ ))}+ </div>+ <div className="flex items-center gap-1">+ {(status === "Failed" || status === "Warning") &&+ retryableIds.length > 0 && (+ <Button+ size="sm"+ variant="secondary"+ leftIcon={<LuRotateCw />}+ isDisabled={!canUpdate || isTransitioning}+ onClick={() => submitTransition(retryableIds, "Pending")}+ >+ <Trans>Retry all</Trans>+ </Button>+ )}+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ aria-label={t`Refresh`}+ icon={+ <LuRefreshCw+ className={cn(isRefreshing && "animate-spin")}+ />+ }+ variant="secondary"+ size="sm"+ isDisabled={isRefreshing}+ onClick={() => revalidator.revalidate()}+ />+ </TooltipTrigger>+ <TooltipContent>+ <Trans>Refresh</Trans>+ </TooltipContent>+ </Tooltip>+ </div>+ </div>++ <div className="w-full rounded-lg border border-border">+ {operations.length === 0 ? (+ <div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground">+ {status ? (+ <Trans>No {status.toLowerCase()} sync operations</Trans>+ ) : (+ <Trans>No sync operations yet</Trans>+ )}+ </div>+ ) : (+ <Table>+ <Thead>+ <Tr>+ <Th className="px-4">+ <Trans>Status</Trans>+ </Th>+ <Th className="px-4 w-full">+ <Trans>Entity</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Direction</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Trigger</Trans>+ </Th>+ <Th className="px-4 text-right">+ <Trans>Attempts</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Last Attempt</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Error</Trans>+ </Th>+ <Th className="px-4" />+ </Tr>+ </Thead>+ <Tbody>+ {operations.map((operation) => {+ const transitions = getAvailableTransitions(operation.status);+ const entityPath = getEntityPath(operation);+ return (+ <Tr+ key={operation.id}+ className="cursor-pointer hover:bg-muted/50"+ onClick={() => setSelectedId(operation.id)}+ >+ <Td className="px-4">+ <Status color={STATUS_COLORS[operation.status]}>+ {operation.status}+ </Status>+ </Td>+ <Td className="px-4">+ <div className="flex flex-col py-1">+ <span className="text-sm font-medium">+ {getEntityLabel(operation.entityType)}+ </span>+ {entityPath ? (+ <Link+ to={entityPath}+ prefetch="intent"+ onClick={(e) => e.stopPropagation()}+ className="block max-w-[180px] truncate font-mono text-xs text-muted-foreground hover:text-foreground hover:underline"+ >+ {operation.entityId}+ </Link>+ ) : (+ <span className="block max-w-[180px] truncate font-mono text-xs text-muted-foreground">+ {operation.entityId}+ </span>+ )}+ </div>+ </Td>+ <Td className="px-4">+ <div className="flex items-center gap-1.5 whitespace-nowrap text-sm">+ {operation.direction === "push-to-accounting" ? (+ <LuArrowUpRight className="size-3.5 shrink-0 text-muted-foreground" />+ ) : (+ <LuArrowDownLeft className="size-3.5 shrink-0 text-muted-foreground" />+ )}+ {operation.direction === "push-to-accounting" ? (+ <Trans>Push</Trans>+ ) : (+ <Trans>Pull</Trans>+ )}+ </div>+ </Td>+ <Td className="px-4 whitespace-nowrap text-sm">+ {formatTrigger(operation.trigger)}+ </Td>+ <Td className="px-4 text-right text-sm tabular-nums">+ {operation.attemptCount}+ </Td>+ <Td className="px-4 whitespace-nowrap text-sm text-muted-foreground">+ {operation.lastAttemptAt+ ? formatRelativeTime(operation.lastAttemptAt)+ : "–"}+ </Td>+ <Td className="px-4">+ {operation.errorMessage ? (+ <span+ className="block max-w-[200px] truncate text-xs text-muted-foreground"+ title={operation.errorMessage}+ >+ {operation.errorMessage}+ </span>+ ) : (+ <span className="text-xs text-muted-foreground">+ –+ </span>+ )}+ </Td>+ <Td className="px-4" onClick={(e) => e.stopPropagation()}>+ <HStack className="justify-end gap-0.5">+ {transitions.retry && (+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ aria-label={t`Retry`}+ icon={<LuRotateCw />}+ variant="ghost"+ size="sm"+ isDisabled={!canUpdate || isTransitioning}+ onClick={() =>+ submitTransition([operation.id], "Pending")+ }+ />+ </TooltipTrigger>+ <TooltipContent>+ <Trans>Retry</Trans>+ </TooltipContent>+ </Tooltip>+ )}+ {transitions.resend && (+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ aria-label={t`Re-send`}+ icon={<LuSend />}+ variant="ghost"+ size="sm"+ isDisabled={!canUpdate || isTransitioning}+ onClick={() =>+ submitTransition([operation.id], "Pending")+ }+ />+ </TooltipTrigger>+ <TooltipContent>+ <Trans>Re-send</Trans>+ </TooltipContent>+ </Tooltip>+ )}+ {transitions.skip && (+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ aria-label={t`Skip`}+ icon={<LuCircleSlash />}+ variant="ghost"+ size="sm"+ isDisabled={!canUpdate || isTransitioning}+ onClick={() =>+ submitTransition([operation.id], "Skipped")+ }+ />+ </TooltipTrigger>+ <TooltipContent>+ <Trans>Skip</Trans>+ </TooltipContent>+ </Tooltip>+ )}+ </HStack>+ </Td>+ </Tr>+ );+ })}+ </Tbody>+ </Table>+ )}+ </div>++ <div className="flex w-full items-center justify-between">+ <p className="text-xs text-muted-foreground tabular-nums">+ {count === 0 ? (+ <Trans>0 operations</Trans>+ ) : (+ <Trans>+ {from}–{to} of {count} operations+ </Trans>+ )}+ </p>+ <div className="flex items-center gap-1">+ <IconButton+ aria-label={t`Previous page`}+ variant="ghost"+ size="sm"+ icon={<LuChevronLeft />}+ isDisabled={page <= 1}+ onClick={() => setPage(page - 1)}+ />+ <IconButton+ aria-label={t`Next page`}+ variant="ghost"+ size="sm"+ icon={<LuChevronRight />}+ isDisabled={page >= totalPages}+ onClick={() => setPage(page + 1)}+ />+ </div>+ </div>+ </DrawerBody>++ <SyncOperationDetailDrawer+ operation={selectedOperation}+ canUpdate={canUpdate}+ isTransitioning={isTransitioning}+ onTransition={submitTransition}+ onClose={() => setSelectedId(null)}+ />+ </>+ );+}++const driftAmountFormatter = new Intl.NumberFormat(undefined, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2+});++/**+ * Warning banner + compact drift table for the latest weekly+ * reconciliation. Rendered above the operations table only when the stored+ * report has drift entries — a clean report (or none yet) shows nothing.+ */+/**+ * Compact tie-out status card, styled after the drift banner above it:+ * amber when any period × account cell carries a nonzero delta, quiet+ * otherwise. Links to the accounting module's tie-out page (which requires+ * accounting_view). Renders nothing when no tie-out rows exist.+ */+function TieOutSummary({+ tieOut+}: {+ tieOut?: {+ computedAt: string | null;+ deltaCellCount: number;+ cellCount: number;+ } | null;+}) {+ const { formatRelativeTime } = useDateFormatter();++ if (!tieOut) return null;+ const hasDeltas = tieOut.deltaCellCount > 0;++ return (+ <div+ className={cn(+ "flex w-full items-center justify-between gap-3 rounded-lg border p-4",+ hasDeltas ? "border-amber-500/40 bg-amber-500/5" : "border-border"+ )}+ >+ <div className="flex items-start gap-3">+ {hasDeltas ? (+ <LuTriangleAlert className="mt-0.5 size-5 shrink-0 text-amber-600 dark:text-amber-500" />+ ) : (+ <LuScale className="mt-0.5 size-5 shrink-0 text-muted-foreground" />+ )}+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">+ <Trans>Tie-out</Trans>+ </span>+ <span className="text-xs text-muted-foreground">+ {hasDeltas ? (+ <Trans>{tieOut.deltaCellCount} cells with deltas</Trans>+ ) : (+ <Trans>All {tieOut.cellCount} cells tie out</Trans>+ )}+ {tieOut.computedAt ? (+ <>+ {" · "}+ <Trans>computed {formatRelativeTime(tieOut.computedAt)}</Trans>+ </>+ ) : null}+ </span>+ </div>+ </div>+ <Button size="sm" variant="secondary" asChild>+ <Link to={path.to.accountingSyncTieOut}>+ <Trans>View tie-out</Trans>+ </Link>+ </Button>+ </div>+ );+}++function ReconciliationDrift({+ lastReconciliation+}: {+ lastReconciliation?: SyncReconciliationReport | null;+}) {+ const { formatDateTime } = useDateFormatter();++ const drift = lastReconciliation?.drift ?? [];+ if (!lastReconciliation || drift.length === 0) return null;++ const missingCount = drift.filter((entry) => entry.type === "missing").length;+ const mismatchCount = drift.length - missingCount;++ return (+ <div className="flex w-full flex-col gap-3 rounded-lg border border-amber-500/40 bg-amber-500/5 p-4">+ <div className="flex items-start gap-3">+ <LuTriangleAlert className="mt-0.5 size-5 shrink-0 text-amber-600 dark:text-amber-500" />+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">+ <Trans>Reconciliation found discrepancies with the provider</Trans>+ </span>+ <span className="text-xs text-muted-foreground">+ {missingCount > 0 && mismatchCount > 0 ? (+ <Trans>+ {missingCount} missing journals and {mismatchCount} mismatched+ months+ </Trans>+ ) : missingCount > 0 ? (+ <Trans>{missingCount} journals missing in the provider</Trans>+ ) : (+ <Trans>{mismatchCount} months with mismatched totals</Trans>+ )}{" "}+ <Trans>+ — last checked {formatDateTime(lastReconciliation.runAt)}+ </Trans>+ </span>+ </div>+ </div>++ <div className="w-full overflow-x-auto rounded-lg border border-border bg-background">+ <Table>+ <Thead>+ <Tr>+ <Th className="px-4">+ <Trans>Type</Trans>+ </Th>+ <Th className="px-4 w-full">+ <Trans>Reference</Trans>+ </Th>+ <Th className="px-4 text-right">+ <Trans>Carbon</Trans>+ </Th>+ <Th className="px-4 text-right">+ <Trans>Provider</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {drift.map((entry, index) =>+ entry.type === "missing" ? (+ <Tr key={`missing-${entry.externalId}-${index}`}>+ <Td className="px-4">+ <Status color="orange">+ <Trans>Missing</Trans>+ </Status>+ </Td>+ <Td className="px-4">+ <div className="flex flex-col py-1">+ <span className="block max-w-[260px] truncate font-mono text-xs">+ {entry.externalId}+ </span>+ <span className="block max-w-[260px] truncate font-mono text-xs text-muted-foreground">+ {entry.journalId}+ </span>+ </div>+ </Td>+ <Td className="px-4 text-right text-sm tabular-nums">+ {entry.amount != null+ ? driftAmountFormatter.format(entry.amount)+ : "–"}+ </Td>+ <Td className="px-4 text-right text-sm text-muted-foreground">+ –+ </Td>+ </Tr>+ ) : (+ <Tr key={`mismatch-${entry.month}-${index}`}>+ <Td className="px-4">+ <Status color="orange">+ <Trans>Mismatch</Trans>+ </Status>+ </Td>+ <Td className="px-4 text-sm">{entry.month}</Td>+ <Td className="px-4 text-right text-sm tabular-nums">+ {driftAmountFormatter.format(entry.carbonTotal)}+ </Td>+ <Td className="px-4 text-right text-sm tabular-nums">+ {driftAmountFormatter.format(entry.providerTotal)}+ </Td>+ </Tr>+ )+ )}+ </Tbody>+ </Table>+ </div>+ </div>+ );+}++function Detail({+ label,+ children+}: {+ label: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="flex flex-col gap-0.5">+ <span className="text-xs text-muted-foreground">{label}</span>+ <div className="text-sm text-foreground">{children}</div>+ </div>+ );+}++function SyncOperationDetailDrawer({+ operation,+ canUpdate,+ isTransitioning,+ onTransition,+ onClose+}: {+ operation: SyncActivityOperation | null;+ canUpdate: boolean;+ isTransitioning: boolean;+ onTransition: (ids: string[], to: "Pending" | "Skipped") => void;+ onClose: () => void;+}) {+ const { t } = useLingui();+ const { formatDateTime } = useDateFormatter();++ if (!operation) return null;++ const transitions = getAvailableTransitions(operation.status);+ const entityPath = getEntityPath(operation);+ const hasMetadata =+ operation.metadata && Object.keys(operation.metadata).length > 0;++ return (+ <Drawer+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <DrawerContent size="sm">+ <DrawerHeader>+ <DrawerTitle>+ {getEntityLabel(operation.entityType)}{" "}+ <span className="font-mono text-muted-foreground">+ {operation.entityId}+ </span>+ </DrawerTitle>+ <DrawerDescription>+ <Trans>Sync operation</Trans>{" "}+ <span className="font-mono">{operation.id}</span>+ </DrawerDescription>+ </DrawerHeader>+ <DrawerBody className="gap-4">+ <div className="grid w-full grid-cols-2 gap-x-4 gap-y-3">+ <Detail label={t`Status`}>+ <Status color={STATUS_COLORS[operation.status]}>+ {operation.status}+ </Status>+ </Detail>+ <Detail label={t`Direction`}>+ {operation.direction === "push-to-accounting" ? (+ <Trans>Push to accounting</Trans>+ ) : (+ <Trans>Pull from accounting</Trans>+ )}+ </Detail>+ <Detail label={t`Trigger`}>+ {formatTrigger(operation.trigger)}+ </Detail>+ <Detail label={t`Attempts`}>+ <span className="tabular-nums">{operation.attemptCount}</span>+ </Detail>+ <Detail label={t`Last attempt`}>+ {operation.lastAttemptAt+ ? formatDateTime(operation.lastAttemptAt)+ : "–"}+ </Detail>+ <Detail label={t`Completed`}>+ {operation.completedAt+ ? formatDateTime(operation.completedAt)+ : "–"}+ </Detail>+ <Detail label={t`Created`}>+ {formatDateTime(operation.createdAt)}+ </Detail>+ <Detail label={t`External ID`}>+ {operation.externalId ? (+ <span className="break-all font-mono text-xs">+ {operation.externalId}+ </span>+ ) : (+ "–"+ )}+ </Detail>+ </div>+ <Detail label={t`Entity`}>+ {entityPath ? (+ <Link+ to={entityPath}+ prefetch="intent"+ className="break-all font-mono text-xs hover:underline"+ >+ {operation.entityId}+ </Link>+ ) : (+ <span className="break-all font-mono text-xs">+ {operation.entityId}+ </span>+ )}+ </Detail>+ <Detail label={t`Idempotency key`}>+ <span className="break-all font-mono text-xs">+ {operation.idempotencyKey}+ </span>+ </Detail>+ {(operation.errorCode || operation.errorMessage) && (+ <div className="flex w-full flex-col gap-2 rounded-lg border border-destructive/30 bg-destructive/5 p-3">+ {operation.errorCode && (+ <Badge variant="destructive" className="self-start font-mono">+ {operation.errorCode}+ </Badge>+ )}+ {operation.errorMessage && (+ <p className="whitespace-pre-wrap break-words text-sm">+ {operation.errorMessage}+ </p>+ )}+ </div>+ )}+ {hasMetadata && (+ <div className="flex w-full flex-col gap-1">+ <span className="text-xs text-muted-foreground">+ <Trans>Metadata</Trans>+ </span>+ <pre className="w-full overflow-x-auto rounded-lg border border-border bg-muted p-3 font-mono text-xs">+ {JSON.stringify(operation.metadata, null, 2)}+ </pre>+ </div>+ )}+ </DrawerBody>+ <DrawerFooter>+ <HStack>+ {transitions.retry && (+ <Button+ leftIcon={<LuRotateCw />}+ isDisabled={!canUpdate || isTransitioning}+ onClick={() => onTransition([operation.id], "Pending")}+ >+ <Trans>Retry</Trans>+ </Button>+ )}+ {transitions.resend && (+ <Button+ leftIcon={<LuSend />}+ isDisabled={!canUpdate || isTransitioning}+ onClick={() => onTransition([operation.id], "Pending")}+ >+ <Trans>Re-send</Trans>+ </Button>+ )}+ {transitions.skip && (+ <Button+ variant="secondary"+ leftIcon={<LuCircleSlash />}+ isDisabled={!canUpdate || isTransitioning}+ onClick={() => onTransition([operation.id], "Skipped")}+ >+ <Trans>Skip</Trans>+ </Button>+ )}+ <Button variant="solid" onClick={onClose}>+ <Trans>Close</Trans>+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </Drawer>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Integrations/index.ts b/apps/erp/app/modules/settings/ui/Integrations/index.tsindex 081157dcdf..57e131ee1c 100644--- a/apps/erp/app/modules/settings/ui/Integrations/index.ts+++ b/apps/erp/app/modules/settings/ui/Integrations/index.ts@@ -1,5 +1,12 @@import { IntegrationForm } from "./IntegrationForm";import IntegrationsList from "./IntegrationsList";import { QuickInstall } from "./QuickInstall";+import { SyncActivity } from "./SyncActivity";-export { IntegrationForm, IntegrationsList, QuickInstall };+// AccountMapping, PostingSyncSettings and DimensionMapping are deliberately+// NOT re-exported here: adding them to this barrel pushes unrelated supabase+// select-string parses (usePurchaseInvoiceAutoFill.ts, purchasing.service.ts)+// over TS2589's instantiation-depth limit — the same cliff SyncActivity's ee+// imports hit (see the note in SyncActivity.tsx). Their only consumer, the+// integrations.$id route, imports them directly from their files.+export { IntegrationForm, IntegrationsList, QuickInstall, SyncActivity };diff --git a/apps/erp/app/routes/api+/integrations.quickbooks.accounts.ts b/apps/erp/app/routes/api+/integrations.quickbooks.accounts.tsnew file mode 100644index 0000000000..acc1c3319f--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.quickbooks.accounts.ts@@ -0,0 +1,68 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import {+ getAccountingIntegration,+ getProviderIntegration,+ ProviderID,+ type QboProvider+} from "@carbon/ee/accounting";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";++export const config = {+ runtime: "nodejs"+};++/**+ * GET: Fetch chart of accounts from QuickBooks Online+ * Returns accounts formatted for use in select dropdowns+ */+export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings"+ });++ try {+ // Get QuickBooks Online integration+ const integration = await getAccountingIntegration(+ client,+ companyId,+ ProviderID.QUICKBOOKS+ );++ // Create provider instance+ const provider = getProviderIntegration(+ client,+ companyId,+ integration.id,+ integration.metadata+ ) as QboProvider;++ // Fetch accounts from QuickBooks Online — already normalized to+ // { id, code, name } with code = AcctNum ?? Id (QBO account numbers+ // are optional)+ const accounts = await provider.listChartOfAccounts();++ // Format accounts for dropdown options. QBO references accounts by Id+ // (the account mapping stores Id as externalId), so Id is the value;+ // the label shows the account number only when one is assigned.+ const options = accounts.map((account) => ({+ value: account.id,+ label:+ account.code !== account.id+ ? `${account.code} - ${account.name}`+ : account.name+ }));++ return data({ accounts: options });+ } catch (error) {+ console.error("Failed to fetch QuickBooks Online accounts:", error);+ return data(+ {+ error:+ error instanceof Error ? error.message : "Failed to fetch accounts",+ accounts: []+ },+ { status: 500 }+ );+ }+}diff --git a/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts b/apps/erp/app/routes/api+/integrations.quickbooks.oauth.tsnew file mode 100644index 0000000000..58b46a9bef--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts@@ -0,0 +1,127 @@+import {+ QUICKBOOKS_CLIENT_ID,+ QUICKBOOKS_CLIENT_SECRET,+ VERCEL_URL+} from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { QuickBooks } from "@carbon/ee";+import {+ DEFAULT_SYNC_CONFIG,+ getProviderIntegration,+ ProviderID+} from "@carbon/ee/accounting";+import { quickbooksOnInstall } from "@carbon/ee/quickbooks/hooks.server";+import type { LoaderFunctionArgs } from "react-router";+import { data, redirect } from "react-router";+import { upsertCompanyIntegration } from "~/modules/settings/settings.server";+import { oAuthCallbackSchema } from "~/modules/shared";+import { path } from "~/utils/path";++export const config = {+ runtime: "nodejs"+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, userId, companyId } = await requirePermissions(request, {+ update: "settings"+ });++ const url = new URL(request.url);+ const searchParams = Object.fromEntries(url.searchParams.entries());++ const quickBooksAuthResponse = oAuthCallbackSchema.safeParse(searchParams);++ if (!quickBooksAuthResponse.success) {+ return data({ error: "Invalid QuickBooks auth response" }, { status: 400 });+ }++ const { data: params } = quickBooksAuthResponse;++ // TODO: Verify state parameter+ if (!params.state) {+ return data({ error: "Invalid state parameter" }, { status: 400 });+ }++ if (!QUICKBOOKS_CLIENT_ID || !QUICKBOOKS_CLIENT_SECRET) {+ return data({ error: "QuickBooks OAuth not configured" }, { status: 500 });+ }++ // Intuit sends the company (realm) id alongside the auth code — no+ // discovery call needed (unlike Xero's GET /connections)+ const realmId = url.searchParams.get("realmId");++ if (!realmId) {+ return data(+ { error: "No realmId found in QuickBooks callback" },+ { status: 400 }+ );+ }++ try {+ const provider = getProviderIntegration(+ client,+ companyId,+ ProviderID.QUICKBOOKS+ );++ // Exchange the authorization code for tokens+ const auth = await provider.authenticate(+ params.code,+ `${url.origin}/api/integrations/quickbooks/oauth`+ );++ if (!auth || auth.type !== "oauth2") {+ return data(+ { error: "Failed to exchange code for token" },+ { status: 500 }+ );+ }++ const createdQuickBooksIntegration = await upsertCompanyIntegration(+ client,+ {+ id: QuickBooks.id,+ active: true,+ // @ts-ignore+ metadata: {+ syncConfig: DEFAULT_SYNC_CONFIG,+ // Provider-specific fields live under providerMetadata (new+ // credential shape) — legacy rows are upgraded on read+ credentials: {+ ...auth,+ providerMetadata: {+ realmId+ }+ }+ },+ updatedBy: userId,+ companyId: companyId+ }+ );++ await quickbooksOnInstall(companyId);++ if (createdQuickBooksIntegration?.data?.metadata) {+ const requestUrl = new URL(request.url);++ if (!VERCEL_URL || VERCEL_URL.includes("localhost")) {+ requestUrl.protocol = "http";+ }++ const redirectUrl = `${requestUrl.origin}${path.to.integrations}`;++ return redirect(redirectUrl);+ } else {+ return data(+ { error: "Failed to save QuickBooks integration" },+ { status: 500 }+ );+ }+ } catch (err) {+ console.error("QuickBooks OAuth Error:", err);+ return data(+ { error: "Failed to exchange code for token" },+ { status: 500 }+ );+ }+}diff --git a/apps/erp/app/routes/api+/integrations.xero.oauth.ts b/apps/erp/app/routes/api+/integrations.xero.oauth.tsindex bc46ee0793..55bbe6d1b9 100644--- a/apps/erp/app/routes/api+/integrations.xero.oauth.ts+++ b/apps/erp/app/routes/api+/integrations.xero.oauth.ts@@ -54,7 +54,7 @@ export async function loader({ request }: LoaderFunctionArgs) {`${url.origin}/api/integrations/xero/oauth`);- if (!auth) {+ if (!auth || auth.type !== "oauth2") {return data({ error: "Failed to exchange code for token" },{ status: 500 }@@ -174,10 +174,14 @@ export async function loader({ request }: LoaderFunctionArgs) {// @ts-ignoremetadata: {syncConfig: DEFAULT_SYNC_CONFIG,+ // Provider-specific fields live under providerMetadata (new+ // credential shape) — legacy rows are upgraded on readcredentials: {...auth,- tenantId,- tenantName: tenantName ?? undefined+ providerMetadata: {+ tenantId,+ tenantName: tenantName ?? undefined+ }}},updatedBy: userId,@@ -203,9 +207,10 @@ export async function loader({ request }: LoaderFunctionArgs) {);}} catch (err) {- logger.error("Xero OAuth Error", { error: err });+ const detail = err instanceof Error ? err.message : String(err);+ logger.error("Xero OAuth Error", { error: detail });return data(- { error: "Failed to exchange code for token" },+ { error: "Failed to exchange code for token", detail },{ status: 500 });}diff --git a/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts b/apps/erp/app/routes/api+/mcp+/lib/direct-executor.tsindex 3f0e2ba325..03c0ce7120 100644--- a/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts@@ -4,7 +4,7 @@ import type { Database } from "@carbon/database";import { getLogger } from "@carbon/logger";import type { SupabaseClient } from "@supabase/supabase-js";import * as accountFunctions from "~/modules/account/account.service";-import * as accountingFunctions from "~/modules/accounting/accounting.service";+import * as accountingFunctions from "~/modules/accounting/accounting.ee.service";import * as documentsFunctions from "~/modules/documents/documents.service";import * as inventoryFunctions from "~/modules/inventory/inventory.service";import * as invoicingFunctions from "~/modules/invoicing/invoicing.service";diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex ee4a393c9e..5f4a2222bb 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-08-13T15:12:30.047Z",- "totalTools": 1436,+ "generated": "2026-08-14T17:02:35.388Z",+ "totalTools": 1440,"modules": 15,"tools": [{@@ -1691,6 +1691,37 @@]}},+ {+ "name": "accounting_getPeriodExternalGlSyncReadiness",+ "module": "accounting",+ "classification": "READ",+ "description": "get period external gl sync readiness",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "companyId",+ "startDate",+ "endDate"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "startDate": {+ "type": "string"+ },+ "endDate": {+ "type": "string"+ }+ },+ "required": [+ "startDate",+ "endDate"+ ]+ }+ },{"name": "accounting_getPeriodCloseReadiness","module": "accounting",@@ -4144,6 +4175,104 @@]}},+ {+ "name": "accounting_getJournalSyncCompleteness",+ "module": "accounting",+ "classification": "READ",+ "description": "get journal sync completeness",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "/** companyIntegration id, e.g. \"xero\" | \"quickbooks\" | \"rillet\". */\n integrationId": {+ "type": "string"+ },+ "journals dated before this are out of scope. */\n syncFromDate": {+ "type": "string"+ },+ "/** Restrict to one accounting period (the close auto-check). */\n accountingPeriodId": {+ "type": "string"+ }+ },+ "required": [+ "/** companyIntegration id, e.g. \"xero\" | \"quickbooks\" | \"rillet\". */\n integrationId",+ "journals dated before this are out of scope. */\n syncFromDate"+ ]+ }+ },+ {+ "name": "accounting_getAccountingSyncTieOut",+ "module": "accounting",+ "classification": "READ",+ "description": "get accounting sync tie out",+ "paramCount": 3,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "integration": {+ "type": [+ "array",+ "null"+ ],+ "items": {}+ },+ "accountingPeriodId": {+ "type": [+ "string",+ "null"+ ]+ },+ "accountId": {+ "type": [+ "array",+ "null"+ ],+ "items": {}+ }+ }+ }+ },+ {+ "name": "accounting_getAccountingSyncTieOutCell",+ "module": "accounting",+ "classification": "READ",+ "description": "get accounting sync tie out cell",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "cellId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "cellId": {+ "type": "string"+ }+ },+ "required": [+ "cellId"+ ]+ }+ },{"name": "documents_deleteDocument","module": "documents",diff --git a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.tsnew file mode 100644index 0000000000..8c99bc2e06--- /dev/null+++ b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.test.ts@@ -0,0 +1,224 @@+import { createHmac } from "node:crypto";+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: () => ({})+}));+vi.mock("@carbon/jobs", () => ({ trigger: vi.fn() }));+vi.mock("@carbon/logger", () => ({+ getLogger: () => ({ info: vi.fn(), error: vi.fn(), warning: vi.fn() })+}));++const getAccountingIntegration = vi.fn();+const getProviderIntegration = vi.fn();+vi.mock("@carbon/ee/accounting", () => ({+ getAccountingIntegration: (...args: unknown[]) =>+ getAccountingIntegration(...args),+ getProviderIntegration: (...args: unknown[]) =>+ getProviderIntegration(...args),+ parseStoredCredentials: (raw: unknown) => raw,+ ProviderID: { QUICKBOOKS: "quickbooks" },+ // Faithful minimal version of the real helper: first LinkedTxn of the+ // family's TxnType → canonical composite.+ buildQboPaymentSyncChange: (+ remote: {+ Id: string;+ Line?: Array<{ LinkedTxn?: Array<{ TxnId: string; TxnType: string }> }>;+ },+ family: "ar" | "ap"+ ) => {+ const txnType = family === "ap" ? "Bill" : "Invoice";+ for (const line of remote.Line ?? []) {+ for (const linked of line.LinkedTxn ?? []) {+ if (linked.TxnType === txnType) {+ return {+ documentRemoteId: linked.TxnId,+ entityId:+ family === "ap"+ ? `bill:${linked.TxnId}:${remote.Id}`+ : `${linked.TxnId}:${remote.Id}`+ };+ }+ }+ }+ return null;+ }+}));++import { trigger } from "@carbon/jobs";+import { action } from "./webhook.quickbooks.$companyId";++const TOKEN = "verifier-secret";++function makeRequest(+ bodyObj: unknown,+ opts: { token?: string | null; signature?: string } = {}+) {+ const body = JSON.stringify(bodyObj);+ const headers = new Headers();+ if (opts.signature !== undefined) {+ headers.set("intuit-signature", opts.signature);+ } else if (opts.token !== null) {+ const sig = createHmac("sha256", opts.token ?? TOKEN)+ .update(body)+ .digest("base64");+ headers.set("intuit-signature", sig);+ }+ return new Request("http://localhost/api/webhook/quickbooks/company-1", {+ method: "POST",+ body,+ headers+ });+}++function run(request: Request) {+ return action({ request, params: { companyId: "company-1" } } as never);+}++const billPaymentEvent = {+ eventNotifications: [+ {+ realmId: "realm-1",+ dataChangeEvent: {+ entities: [+ { name: "BillPayment", id: "bp-1", operation: "Update" },+ { name: "Vendor", id: "v-1", operation: "Update" }+ ]+ }+ }+ ]+};++describe("webhook.quickbooks payment accelerator", () => {+ beforeEach(() => {+ vi.mocked(trigger).mockReset();+ getAccountingIntegration.mockReset();+ getProviderIntegration.mockReset();++ getAccountingIntegration.mockResolvedValue({+ active: true,+ metadata: {+ credentials: {+ type: "oauth2",+ providerMetadata: { webhookVerifierToken: TOKEN }+ }+ }+ });+ getProviderIntegration.mockReturnValue({+ getBillPayment: async (id: string) => ({+ Id: id,+ TotalAmt: 500,+ Line: [+ { Amount: 500, LinkedTxn: [{ TxnId: "bill-9", TxnType: "Bill" }] }+ ]+ }),+ getPayment: async (id: string) => ({+ Id: id,+ TotalAmt: 125,+ Line: [+ { Amount: 125, LinkedTxn: [{ TxnId: "inv-7", TxnType: "Invoice" }] }+ ]+ })+ });+ });++ it("verifies a valid intuit-signature and enqueues the AP composite; ignores non-payment entities", async () => {+ const result = (await run(makeRequest(billPaymentEvent))) as {+ success: boolean;+ };+ expect(result.success).toBe(true);++ expect(trigger).toHaveBeenCalledTimes(1);+ const payload = vi.mocked(trigger).mock.calls[0]?.[1] as {+ companyId: string;+ provider: string;+ syncType: string;+ syncDirection: string;+ entities: Array<{+ entityType: string;+ entityId: string;+ operation: string;+ }>;+ };+ expect(payload).toMatchObject({+ companyId: "company-1",+ provider: "quickbooks",+ syncType: "webhook",+ syncDirection: "pull-from-accounting"+ });+ // Vendor is ignored; only the BillPayment is enqueued (AP `bill:` composite).+ expect(payload.entities).toEqual([+ {+ entityType: "payment",+ entityId: "bill:bill-9:bp-1",+ operation: "update"+ }+ ]);+ });++ it("enqueues the prefix-less AR composite for a Payment", async () => {+ await run(+ makeRequest({+ eventNotifications: [+ {+ dataChangeEvent: {+ entities: [{ name: "Payment", id: "pay-1", operation: "Update" }]+ }+ }+ ]+ })+ );++ const payload = vi.mocked(trigger).mock.calls[0]?.[1] as {+ entities: Array<{ entityType: string; entityId: string }>;+ };+ expect(payload.entities).toEqual([+ { entityType: "payment", entityId: "inv-7:pay-1", operation: "update" }+ ]);+ });++ it("acks and ignores a payload with no payment entities", async () => {+ const result = (await run(+ makeRequest({+ eventNotifications: [+ {+ dataChangeEvent: {+ entities: [{ name: "Customer", id: "c-1", operation: "Update" }]+ }+ }+ ]+ })+ )) as { success: boolean; ignored?: boolean };+ expect(result).toEqual({ success: true, ignored: true });+ expect(trigger).not.toHaveBeenCalled();+ });++ it("rejects an invalid signature with 401 and does not enqueue", async () => {+ const result = (await run(+ makeRequest(billPaymentEvent, { signature: "not-a-valid-signature" })+ )) as { init?: { status?: number } };+ expect(result.init?.status).toBe(401);+ expect(trigger).not.toHaveBeenCalled();+ });++ it("returns 401 when no verifier token is configured", async () => {+ getAccountingIntegration.mockResolvedValue({+ active: true,+ metadata: { credentials: { type: "oauth2", providerMetadata: {} } }+ });+ const original = process.env.QUICKBOOKS_WEBHOOK_VERIFIER_TOKEN;+ delete process.env.QUICKBOOKS_WEBHOOK_VERIFIER_TOKEN;++ const result = (await run(+ makeRequest(billPaymentEvent, { token: null })+ )) as {+ init?: { status?: number };+ };+ expect(result.init?.status).toBe(401);+ expect(trigger).not.toHaveBeenCalled();++ if (original !== undefined) {+ process.env.QUICKBOOKS_WEBHOOK_VERIFIER_TOKEN = original;+ }+ });+});diff --git a/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.tsnew file mode 100644index 0000000000..16712f1453--- /dev/null+++ b/apps/erp/app/routes/api+/webhook.quickbooks.$companyId.ts@@ -0,0 +1,255 @@+import { createHmac, timingSafeEqual } from "node:crypto";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ buildQboPaymentSyncChange,+ getAccountingIntegration,+ getProviderIntegration,+ ProviderID,+ parseStoredCredentials+} from "@carbon/ee/accounting";+import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { z } from "zod";++// Needs node:crypto for HMAC signature verification + a QBO API refetch+export const config = { runtime: "nodejs" };++const logger = getLogger("erp", "webhook-quickbooks");++/**+ * Intuit webhook payload. NOTIFICATION-ONLY: each entity carries just+ * `{ name, id, operation, lastUpdated }` — no object body — so the payment op+ * is enqueued and its `fetchRemote` pulls the object. Lenient: only the fields+ * the route reads are required; Intuit may add fields at any time.+ */+const webhookValidator = z+ .object({+ eventNotifications: z+ .array(+ z+ .object({+ realmId: z.string().optional(),+ dataChangeEvent: z+ .object({+ entities: z+ .array(+ z+ .object({+ name: z.string(),+ id: z.string(),+ operation: z.string().optional(),+ lastUpdated: z.string().optional()+ })+ .passthrough()+ )+ .default([])+ })+ .passthrough()+ .optional()+ })+ .passthrough()+ )+ .default([])+ })+ .passthrough();++/** Payment entity names Carbon acts on; every other name is acked + ignored. */+const PAYMENT_ENTITY_NAMES = new Set(["Payment", "BillPayment"]);++/** Health-check endpoint for the URL pasted into Intuit's webhook form. */+export async function loader({ params }: LoaderFunctionArgs) {+ if (!params.companyId) {+ return data({ success: false }, { status: 400 });+ }+ return { success: true };+}++/**+ * Constant-time compare of the base64 `intuit-signature` header against the+ * expected HMAC. Length mismatch fails fast (timingSafeEqual throws on unequal+ * buffer lengths).+ */+function signaturesMatch(headerValue: string, expected: string): boolean {+ const a = Buffer.from(headerValue, "base64");+ const b = Buffer.from(expected, "base64");+ if (a.length !== b.length || a.length === 0) return false;+ return timingSafeEqual(a, b);+}++export async function action({ request, params }: ActionFunctionArgs) {+ // CORS preflight short-circuit (webhooks are server-to-server, but ack it).+ if (request.method === "OPTIONS") {+ return new Response(null, {+ status: 204,+ headers: {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "POST, OPTIONS",+ "Access-Control-Allow-Headers": "content-type, intuit-signature"+ }+ });+ }++ const { companyId } = params;+ if (!companyId) {+ return data({ success: false }, { status: 400 });+ }++ // Raw body FIRST — the Intuit signature covers the exact bytes, not+ // re-serialized JSON.+ const body = await request.text();++ const serviceRole = getCarbonServiceRole();++ const integration = await getAccountingIntegration(+ serviceRole,+ companyId,+ ProviderID.QUICKBOOKS+ ).catch(() => null);+ if (!integration || !integration.active) {+ return data({ success: false }, { status: 404 });+ }++ // Intuit signs webhooks with the app's "verifier token" (base64+ // HMAC-SHA256 of the raw body). VERIFY: it currently lives on the QBO+ // credentials as providerMetadata.webhookVerifierToken (per-company), with an+ // env fallback for a single app-wide token — confirm where Carbon persists+ // it during QBO setup and drop whichever branch is unused.+ let verifierToken: string | null = null;+ try {+ const credentials = parseStoredCredentials(+ integration.metadata.credentials+ );+ if (credentials.type === "oauth2") {+ const token = credentials.providerMetadata?.webhookVerifierToken;+ if (typeof token === "string" && token.length > 0) {+ verifierToken = token;+ }+ }+ } catch (error) {+ logger.error("Failed to parse stored QuickBooks Online credentials", {+ error+ });+ }+ if (!verifierToken) {+ const envToken = process.env.QUICKBOOKS_WEBHOOK_VERIFIER_TOKEN;+ if (typeof envToken === "string" && envToken.length > 0) {+ verifierToken = envToken;+ }+ }+ if (!verifierToken) {+ return data(+ { success: false, error: "Webhook verifier token not configured" },+ { status: 401 }+ );+ }++ const signature = request.headers.get("intuit-signature");+ if (!signature) {+ return data({ success: false }, { status: 401 });+ }++ const expected = createHmac("sha256", verifierToken)+ .update(body)+ .digest("base64");+ if (!signaturesMatch(signature, expected)) {+ return data({ success: false }, { status: 401 });+ }++ let parsed: z.infer<typeof webhookValidator>;+ try {+ parsed = webhookValidator.parse(JSON.parse(body));+ } catch (error) {+ logger.error("Invalid QuickBooks Online webhook payload", { error });+ return data({ success: false }, { status: 400 });+ }++ // Forward-compatibility: unrecognized entity names are acknowledged and+ // ignored, never rejected.+ const paymentNotifications = parsed.eventNotifications+ .flatMap((notification) => notification.dataChangeEvent?.entities ?? [])+ .filter((entity) => PAYMENT_ENTITY_NAMES.has(entity.name));++ if (paymentNotifications.length === 0) {+ return { success: true, ignored: true };+ }++ // The notification is object-less, so refetch each payment to resolve its+ // settled document and build the CANONICAL composite id — the same id the+ // CDC sweep emits, so webhook + sweep dedupe on the one `payment` mapping+ // (ledger idempotency). The CDC sweep is the correctness backstop.+ const provider = getProviderIntegration(+ serviceRole,+ companyId,+ ProviderID.QUICKBOOKS,+ integration.metadata+ );++ const entities: Array<{+ entityType: "payment";+ entityId: string;+ operation: "update";+ }> = [];++ for (const notification of paymentNotifications) {+ const family = notification.name === "BillPayment" ? "ap" : "ar";+ try {+ const remote =+ family === "ap"+ ? await provider.getBillPayment(notification.id)+ : await provider.getPayment(notification.id);+ if (!remote) {+ logger.info("QuickBooks Online payment not found on refetch", {+ companyId,+ name: notification.name,+ id: notification.id+ });+ continue;+ }++ const change = buildQboPaymentSyncChange(remote, family);+ if (!change) {+ logger.info("QuickBooks Online payment settles no Bill/Invoice", {+ companyId,+ name: notification.name,+ id: notification.id+ });+ continue;+ }++ entities.push({+ entityType: "payment",+ entityId: change.entityId,+ operation: "update"+ });+ } catch (error) {+ logger.error("Failed to resolve QuickBooks Online payment", {+ companyId,+ name: notification.name,+ id: notification.id,+ error+ });+ }+ }++ if (entities.length === 0) {+ return { success: true, ignored: true };+ }++ await trigger("sync-external-accounting", {+ companyId,+ provider: ProviderID.QUICKBOOKS,+ syncType: "webhook",+ syncDirection: "pull-from-accounting",+ entities,+ metadata: { raw: parsed }+ });++ logger.info("Triggered QuickBooks Online payment sync", {+ companyId,+ count: entities.length+ });++ return { success: true };+}diff --git a/apps/erp/app/routes/api+/webhook.rillet.$companyId.ts b/apps/erp/app/routes/api+/webhook.rillet.$companyId.tsnew file mode 100644index 0000000000..104a64d9a6--- /dev/null+++ b/apps/erp/app/routes/api+/webhook.rillet.$companyId.ts@@ -0,0 +1,147 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ getRilletPaymentSyncEntityId,+ ProviderID,+ parseStoredCredentials,+ verifyRilletWebhookSignature+} from "@carbon/ee/accounting";+import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { z } from "zod";+import { getIntegration } from "~/modules/settings/settings.service";++// Needs node:crypto for constant-time HMAC comparison+export const config = { runtime: "nodejs" };++const logger = getLogger("erp", "webhook-rillet");++/**+ * Rillet invoice-payment payload. Lenient: only the ids the sync needs are+ * required; Rillet may add fields at any time.+ */+const paymentPayloadValidator = z+ .object({+ id: z.string().min(1),+ invoice_id: z.string().min(1)+ })+ .passthrough();++/** Health-check endpoint for the URL pasted into Rillet's webhook form. */+export async function loader({ params }: LoaderFunctionArgs) {+ if (!params.companyId) {+ return data({ success: false }, { status: 400 });+ }+ return { success: true };+}++export async function action({ request, params }: ActionFunctionArgs) {+ const { companyId } = params;+ if (!companyId) {+ return data({ success: false }, { status: 400 });+ }++ // Raw body FIRST — the signature covers the exact bytes, not re-serialized+ // JSON.+ const body = await request.text();++ const serviceRole = getCarbonServiceRole();+ const integration = await getIntegration(serviceRole, "rillet", companyId);+ if (integration.error || !integration.data || !integration.data.active) {+ return data({ success: false }, { status: 404 });+ }++ // The per-webhook token lives with the API-key credentials. No token =+ // payments not enabled — reject rather than fail open.+ const metadata = (integration.data.metadata ?? {}) as Record<string, unknown>;+ let webhookToken: string | null = null;+ try {+ const credentials = parseStoredCredentials(metadata.credentials);+ if (+ credentials.type === "apiKey" &&+ typeof credentials.providerMetadata?.webhookToken === "string" &&+ credentials.providerMetadata.webhookToken.length > 0+ ) {+ webhookToken = credentials.providerMetadata.webhookToken;+ }+ } catch (error) {+ logger.error("Failed to parse stored Rillet credentials", { error });+ }+ if (!webhookToken) {+ return data(+ { success: false, error: "Webhook token not configured" },+ { status: 401 }+ );+ }++ const signature = request.headers.get("x-rillet-signature");+ const timestamp = request.headers.get("x-rillet-timestamp");+ const deliveryId = request.headers.get("x-rillet-id");+ const entity = request.headers.get("x-rillet-entity");+ const event = request.headers.get("x-rillet-event");++ if (!signature || !timestamp || !deliveryId || !entity || !event) {+ return data({ success: false }, { status: 401 });+ }++ const verified = verifyRilletWebhookSignature({+ headers: { signature, timestamp, id: deliveryId, entity, event },+ body,+ token: webhookToken+ });+ if (!verified) {+ return data({ success: false }, { status: 401 });+ }++ // VERIFY(Phase 1.3): AP bill payments are POLL-ONLY. Rillet documents only+ // `bill-created`/`bill-updated`/`bill-deleted` webhook events — no+ // bill-payment (or bill-updated-on-payment) event is confirmed — so this+ // route stays AR-only and the accounting-pull-sweep (RilletProvider.listChanges+ // over /bill-payments) is the guarantee for AP settlement. If a+ // bill-updated-on-payment event is later confirmed, branch here and enqueue a+ // `bill:` composite-id `payment` op via getRilletBillPaymentSyncEntityId.+ //+ // Forward-compatibility contract: unrecognized entity/event values are+ // acknowledged and ignored, never rejected.+ const isInvoicePayment =+ entity.toLowerCase() === "invoice" &&+ event.toLowerCase() === "payment-updated";+ if (!isInvoicePayment) {+ return { success: true, ignored: true };+ }++ let parsed: z.infer<typeof paymentPayloadValidator>;+ try {+ parsed = paymentPayloadValidator.parse(JSON.parse(body));+ } catch (error) {+ logger.error("Invalid Rillet payment webhook payload", { error });+ return data({ success: false }, { status: 400 });+ }++ // Ack fast; the sync job enqueues to the ledger and drains. The composite+ // entity id makes the payment syncer self-sufficient (invoice + payment+ // remote ids), so no metadata threading is required.+ await trigger("sync-external-accounting", {+ companyId,+ provider: ProviderID.RILLET,+ syncType: "webhook",+ syncDirection: "pull-from-accounting",+ entities: [+ {+ entityType: "payment",+ entityId: getRilletPaymentSyncEntityId(parsed.invoice_id, parsed.id),+ operation: "update"+ }+ ],+ metadata: { deliveryId, raw: parsed }+ });++ logger.info("Triggered Rillet payment sync", {+ companyId,+ deliveryId,+ paymentId: parsed.id+ });++ return { success: true };+}diff --git a/apps/erp/app/routes/api+/webhook.xero.test.ts b/apps/erp/app/routes/api+/webhook.xero.test.tsnew file mode 100644index 0000000000..62e3cf4032--- /dev/null+++ b/apps/erp/app/routes/api+/webhook.xero.test.ts@@ -0,0 +1,159 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// Fail-open: no secret configured → signature verification is skipped.+vi.mock("@carbon/auth", () => ({ XERO_WEBHOOK_SECRET: undefined }));+vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: () => ({})+}));+vi.mock("@carbon/jobs", () => ({ trigger: vi.fn() }));+vi.mock("@carbon/logger", () => ({+ getLogger: () => ({ info: vi.fn(), error: vi.fn(), warning: vi.fn() })+}));++const getAccountingIntegration = vi.fn();+const getProviderIntegration = vi.fn();+vi.mock("@carbon/ee/accounting", () => ({+ getAccountingIntegration: (...args: unknown[]) =>+ getAccountingIntegration(...args),+ getProviderIntegration: (...args: unknown[]) =>+ getProviderIntegration(...args),+ ProviderID: { XERO: "xero" },+ // Real composite-id shape (the syncer's contract): ACCREC prefix-less AR,+ // ACCPAY `bill:`-prefixed AP.+ getXeroPaymentSyncEntityId: (+ invoiceRemoteId: string,+ paymentRemoteId: string+ ) => `${invoiceRemoteId}:${paymentRemoteId}`,+ getXeroBillPaymentSyncEntityId: (+ invoiceRemoteId: string,+ paymentRemoteId: string+ ) => `bill:${invoiceRemoteId}:${paymentRemoteId}`+}));++import { trigger } from "@carbon/jobs";+import { action } from "./webhook.xero";++function invoiceEvent() {+ return {+ events: [+ {+ tenantId: "tenant-1",+ eventCategory: "INVOICE",+ eventType: "UPDATE",+ resourceId: "inv-remote-1",+ eventDateUtc: "2026-08-01T00:00:00Z"+ }+ ],+ firstEventSequence: 0,+ lastEventSequence: 0+ };+}++function makeRequest(body: unknown) {+ return new Request("http://localhost/api/webhook/xero", {+ method: "POST",+ body: JSON.stringify(body)+ });+}++describe("webhook.xero Invoice-update payment accelerator", () => {+ beforeEach(() => {+ vi.mocked(trigger).mockReset();+ getAccountingIntegration.mockReset();+ getProviderIntegration.mockReset();++ getAccountingIntegration.mockResolvedValue({+ companyId: "company-1",+ metadata: {}+ });+ });++ it("enqueues a payment op per Payments[] entry for an ACCPAY invoice (bill: ids)", async () => {+ getProviderIntegration.mockReturnValue({+ request: vi.fn().mockResolvedValue({+ error: false,+ data: {+ Invoices: [+ {+ Type: "ACCPAY",+ Payments: [{ PaymentID: "pay-1" }, { PaymentID: "pay-2" }]+ }+ ]+ }+ })+ });++ const result = (await action({+ request: makeRequest(invoiceEvent())+ } as never)) as { success: boolean; jobsTriggered: number };++ expect(result.success).toBe(true);+ expect(result.jobsTriggered).toBe(1);++ expect(trigger).toHaveBeenCalledTimes(1);+ const payload = vi.mocked(trigger).mock.calls[0]?.[1] as {+ entities: Array<{+ entityType: string;+ entityId: string;+ operation: string;+ }>;+ };++ expect(payload.entities).toEqual([+ { entityType: "bill", entityId: "inv-remote-1", operation: "update" },+ {+ entityType: "payment",+ entityId: "bill:inv-remote-1:pay-1",+ operation: "update"+ },+ {+ entityType: "payment",+ entityId: "bill:inv-remote-1:pay-2",+ operation: "update"+ }+ ]);+ });++ it("uses prefix-less AR ids for an ACCREC invoice payment", async () => {+ getProviderIntegration.mockReturnValue({+ request: vi.fn().mockResolvedValue({+ error: false,+ data: {+ Invoices: [{ Type: "ACCREC", Payments: [{ PaymentID: "pay-9" }] }]+ }+ })+ });++ await action({ request: makeRequest(invoiceEvent()) } as never);++ const payload = vi.mocked(trigger).mock.calls[0]?.[1] as {+ entities: Array<{ entityType: string; entityId: string }>;+ };+ expect(payload.entities).toEqual([+ { entityType: "invoice", entityId: "inv-remote-1", operation: "update" },+ {+ entityType: "payment",+ entityId: "inv-remote-1:pay-9",+ operation: "update"+ }+ ]);+ });++ it("enqueues only the document entity when the invoice has no payments", async () => {+ getProviderIntegration.mockReturnValue({+ request: vi.fn().mockResolvedValue({+ error: false,+ data: { Invoices: [{ Type: "ACCPAY", Payments: [] }] }+ })+ });++ await action({ request: makeRequest(invoiceEvent()) } as never);++ const payload = vi.mocked(trigger).mock.calls[0]?.[1] as {+ entities: Array<{ entityType: string }>;+ };+ expect(payload.entities).toEqual([+ { entityType: "bill", entityId: "inv-remote-1", operation: "update" }+ ]);+ });+});diff --git a/apps/erp/app/routes/api+/webhook.xero.ts b/apps/erp/app/routes/api+/webhook.xero.tsindex 4594345be6..7023a7c19b 100644--- a/apps/erp/app/routes/api+/webhook.xero.ts+++ b/apps/erp/app/routes/api+/webhook.xero.ts@@ -23,12 +23,14 @@ import { XERO_WEBHOOK_SECRET } from "@carbon/auth";import { getCarbonServiceRole } from "@carbon/auth/client.server";import type {AccountingEntity,- AccountingProvider,- AccountingSyncPayload+ AccountingSyncPayload,+ XeroProvider} from "@carbon/ee/accounting";import {getAccountingIntegration,getProviderIntegration,+ getXeroBillPaymentSyncEntityId,+ getXeroPaymentSyncEntityId,ProviderID} from "@carbon/ee/accounting";import { trigger } from "@carbon/jobs";@@ -230,9 +232,9 @@ export async function action({ request }: ActionFunctionArgs) {break;case "INVOICE":- const invoiceType = await fetchInvoiceType(provider, resourceId);+ const invoiceInfo = await fetchInvoiceForSync(provider, resourceId);- if (!invoiceType) {+ if (!invoiceInfo) {logger.info("Skipping invoice - could not determine type", {resourceId});@@ -240,11 +242,39 @@ export async function action({ request }: ActionFunctionArgs) {}entities.push({- entityType: invoiceType,+ entityType: invoiceInfo.entityType,entityId: resourceId,operation: operation});+ // Payment accelerator: Xero has no payment webhook, but paying an+ // ACCPAY/ACCREC invoice fires an Invoice UPDATE event. Enqueue a+ // pull-only `payment` op per settlement (composite id per the+ // syncer's contract: ACCPAY → `bill:` prefix, ACCREC → prefix-less).+ // The accounting-pull-sweep (XeroProvider.listChanges over+ // /Payments) remains the correctness guarantee; ledger idempotency+ // dedupes this webhook against the sweep.+ //+ // VERIFY: that paying an ACCPAY (bill) invoice actually fires an+ // INVOICE webhook event and that the fetched invoice carries the+ // settling payment(s) in `Payments[]` — confirm on the Xero sandbox.+ for (const payment of invoiceInfo.payments) {+ if (!payment.PaymentID) continue;+ const paymentEntityId =+ invoiceInfo.entityType === "bill"+ ? getXeroBillPaymentSyncEntityId(+ resourceId,+ payment.PaymentID+ )+ : getXeroPaymentSyncEntityId(resourceId, payment.PaymentID);++ entities.push({+ entityType: "payment",+ entityId: paymentEntityId,+ operation: "update"+ });+ }+break;}}@@ -309,10 +339,7 @@ export async function action({ request }: ActionFunctionArgs) {};}-const fetchContactType = async (- provider: AccountingProvider,- resourceId: string-) => {+const fetchContactType = async (provider: XeroProvider, resourceId: string) => {const res = await provider.request<{Contacts: { IsSupplier: boolean; IsCustomer: boolean }[];}>("GET", `/Contacts/${resourceId}`);@@ -335,16 +362,28 @@ const fetchContactType = async (};/**- * Fetches invoice from Xero to determine if it's a sales invoice or bill.- * - ACCREC (Accounts Receivable) = Sales Invoice -> maps to "invoice"- * - ACCPAY (Accounts Payable) = Purchase Invoice/Bill -> maps to "bill"+ * Fetches an invoice from Xero to determine its Carbon entity type AND the+ * payments settling it (the payment accelerator reads `Payments[]`).+ * - ACCREC (Accounts Receivable) = Sales Invoice -> "invoice"+ * - ACCPAY (Accounts Payable) = Purchase Invoice/Bill -> "bill"+ *+ * `Payments[]` lists the currently-applied payments on the invoice (voided+ * payments are dropped from the array by Xero), so the accelerator only ever+ * enqueues settled payments; void detection is left to the poll sweep / status+ * re-pull.*/-const fetchInvoiceType = async (- provider: AccountingProvider,+const fetchInvoiceForSync = async (+ provider: XeroProvider,resourceId: string-): Promise<"invoice" | "bill" | null> => {+): Promise<{+ entityType: "invoice" | "bill";+ payments: { PaymentID: string }[];+} | null> => {const res = await provider.request<{- Invoices: { Type: "ACCREC" | "ACCPAY" }[];+ Invoices: {+ Type: "ACCREC" | "ACCPAY";+ Payments?: { PaymentID: string }[];+ }[];}>("GET", `/Invoices/${resourceId}`);if (res.error || !res.data || res.data.Invoices.length === 0) {@@ -355,5 +394,8 @@ const fetchInvoiceType = async (// ACCREC = Accounts Receivable = Sales Invoice// ACCPAY = Accounts Payable = Bill/Purchase Invoice- return invoice.Type === "ACCREC" ? "invoice" : "bill";+ return {+ entityType: invoice.Type === "ACCREC" ? "invoice" : "bill",+ payments: (invoice.Payments ?? []).filter((p) => p.PaymentID)+ };};diff --git a/apps/erp/app/routes/x+/_index.tsx b/apps/erp/app/routes/x+/_index.tsxindex c7b1d5c419..958dc48586 100644--- a/apps/erp/app/routes/x+/_index.tsx+++ b/apps/erp/app/routes/x+/_index.tsx@@ -149,8 +149,8 @@ export default function AppIndexRoute() {action={path.to.getStartedEnroll}className="mb-6">- <div className="rounded-lg ring-2 ring-transparent bg-gradient-to-bl from-card/70 from-50% to-background/70 backdrop-blur-md shadow-button-base p-6 flex items-start gap-4">- <div className="shrink-0 size-11 rounded-lg bg-accent flex items-center justify-center text-primary">+ <div className="rounded-lg ring-2 ring-transparent bg-gradient-to-bl from-card/70 from-50% to-background/70 backdrop-blur-md shadow-button-base p-4 flex items-start gap-4">+ <div className="shrink-0 p-2.5 rounded-lg border border-border"><LuRocket className="text-xl" /></div><div className="flex-1 min-w-0">@@ -207,7 +207,7 @@ const ModuleCard = ({ module }: { module: Authenticated<NavItem> }) => ({...(module.external? { target: "_blank", rel: "noopener noreferrer" }: {})}- className="flex items-center gap-4 p-4 bg-card/70 backdrop-blur-md rounded-lg border border-border group hover:bg-accent/40 hover:border-foreground/20 cursor-pointer transition-colors duration-200"+ className="flex items-center gap-4 p-4 bg-card/70 backdrop-blur-md rounded-lg border border-border group hover:bg-card/60 hover:border-foreground/20 cursor-pointer transition-colors duration-200"><div className="shrink-0 p-2.5 rounded-lg border border-border group-hover:border-foreground/20 transition-colors"><module.icon className="text-xl" />diff --git a/apps/erp/app/routes/x+/accounting+/_layout.tsx b/apps/erp/app/routes/x+/accounting+/_layout.tsxindex c242be0260..27eb00badb 100644--- a/apps/erp/app/routes/x+/accounting+/_layout.tsx+++ b/apps/erp/app/routes/x+/accounting+/_layout.tsx@@ -35,12 +35,20 @@ export async function loader({ request }: LoaderFunctionArgs) {});- const [accounts, baseCurrency, companies] = await Promise.all([+ const [accounts, baseCurrency, companies, integrations] = await Promise.all([getAccountsList(client, companyGroupId, {isGroup: false}),getBaseCurrency(client, companyId),- getCompaniesInGroup(client, companyGroupId)+ getCompaniesInGroup(client, companyGroupId),+ // Active accounting integrations gate integration-dependent nav items+ // (Sync Tie-Out) and feed the tie-out table's integration filter+ client+ .from("companyIntegration")+ .select("id")+ .eq("companyId", companyId)+ .eq("active", true)+ .in("id", ["xero", "quickbooks", "rillet"])]);if (accounts.error) {@@ -56,7 +64,8 @@ export async function loader({ request }: LoaderFunctionArgs) {accounts.data.filter((a) => a.incomeBalance === "Balance Sheet") ?? [],incomeStatementAccounts:accounts.data.filter((a) => a.incomeBalance === "Income Statement") ?? [],- hasMultipleCompanies: (companies.data?.length ?? 0) > 1+ hasMultipleCompanies: (companies.data?.length ?? 0) > 1,+ accountingIntegrations: (integrations.data ?? []).map((row) => row.id)};}diff --git a/apps/erp/app/routes/x+/accounting+/sync-tieout.$cellId.tsx b/apps/erp/app/routes/x+/accounting+/sync-tieout.$cellId.tsxnew file mode 100644index 0000000000..77ef120a7c--- /dev/null+++ b/apps/erp/app/routes/x+/accounting+/sync-tieout.$cellId.tsx@@ -0,0 +1,239 @@+import { error, notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import {+ cn,+ Drawer,+ DrawerBody,+ DrawerContent,+ DrawerDescription,+ DrawerHeader,+ DrawerTitle,+ Status,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { formatDate } from "@carbon/utils";+import { msg } from "@lingui/core/macro";+import { Trans, useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";+import type { LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData, useNavigate } from "react-router";+import { Hyperlink } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";+import { getAccountingSyncTieOutCell } from "~/modules/accounting";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: msg`Sync Tie-Out`,+ to: path.to.accountingSyncTieOut+};++/**+ * Disposition colors — same semantics as the Sync Activity inbox+ * (~/modules/settings/ui/Integrations/SyncActivity.tsx STATUS_COLORS).+ */+const SYNC_STATUS_COLORS: Record<+ string,+ "yellow" | "blue" | "green" | "red" | "orange" | "gray"+> = {+ Pending: "yellow",+ "In Flight": "blue",+ Completed: "green",+ Failed: "red",+ Warning: "orange",+ Skipped: "gray",+ Excluded: "gray"+};++const INTEGRATION_LABELS: Record<string, string> = {+ xero: "Xero",+ quickbooks: "QuickBooks",+ rillet: "Rillet"+};++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "accounting",+ role: "employee"+ });++ const { cellId } = params;+ if (!cellId) throw notFound("cellId not found");++ const cellDetail = await getAccountingSyncTieOutCell(+ client,+ companyId,+ cellId+ );+ if (cellDetail.error || !cellDetail.data) {+ throw redirect(+ path.to.accountingSyncTieOut,+ await flash(+ request,+ error(cellDetail.error, "Failed to load the tie-out cell")+ )+ );+ }++ return cellDetail.data;+}++export default function SyncTieOutCellRoute() {+ const { cell, journals, truncated } = useLoaderData<typeof loader>();+ const { t } = useLingui();+ const { locale } = useLocale();+ const navigate = useNavigate();+ const currencyFormatter = useCurrencyFormatter();++ const period = cell.accountingPeriod;+ const periodLabel = period+ ? period.fiscalYear != null && period.periodNumber != null+ ? `${period.fiscalYear}-${String(period.periodNumber).padStart(2, "0")}`+ : `${formatDate(period.startDate, undefined, locale)} – ${formatDate(+ period.endDate,+ undefined,+ locale+ )}`+ : "—";+ const accountLabel = cell.account+ ? [cell.account.number, cell.account.name].filter(Boolean).join(" · ")+ : cell.accountId;+ const integrationLabel =+ INTEGRATION_LABELS[cell.integration] ?? cell.integration;++ const amounts: { label: string; value: number | null; delta?: boolean }[] = [+ { label: t`Carbon Posted`, value: cell.carbonPostedAmount },+ { label: t`Synced`, value: cell.syncedAmount },+ { label: t`Doc-Backed`, value: cell.docBackedAmount },+ { label: t`Excluded`, value: cell.excludedAmount },+ { label: t`Pending`, value: cell.pendingAmount },+ { label: t`Blocked`, value: cell.blockedAmount },+ { label: t`Provider`, value: cell.providerAmount },+ { label: t`Internal Delta`, value: cell.internalDelta, delta: true },+ { label: t`External Delta`, value: cell.externalDelta, delta: true }+ ];++ return (+ <Drawer+ open+ onOpenChange={(open) => {+ if (!open) navigate(path.to.accountingSyncTieOut);+ }}+ >+ <DrawerContent size="lg">+ <DrawerHeader>+ <DrawerTitle>{accountLabel}</DrawerTitle>+ <DrawerDescription>+ {periodLabel} · {integrationLabel}+ </DrawerDescription>+ </DrawerHeader>+ <DrawerBody className="gap-4">+ <div className="grid w-full grid-cols-2 gap-x-8 gap-y-2 rounded-lg border border-border p-4 sm:grid-cols-3">+ {amounts.map((amount) => {+ const nonzeroDelta =+ amount.delta &&+ amount.value != null &&+ Math.abs(amount.value) > 0.001;+ return (+ <div key={amount.label} className="flex flex-col">+ <span className="text-xs text-muted-foreground">+ {amount.label}+ </span>+ <span+ className={cn(+ "text-sm tabular-nums",+ nonzeroDelta && "font-semibold text-destructive"+ )}+ >+ {amount.value == null+ ? "—"+ : currencyFormatter.format(amount.value)}+ </span>+ </div>+ );+ })}+ </div>++ <div className="w-full rounded-lg border border-border">+ {journals.length === 0 ? (+ <div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground">+ <Trans>+ No posted journals in this period for this account+ </Trans>+ </div>+ ) : (+ <Table>+ <Thead>+ <Tr>+ <Th className="px-4">+ <Trans>Journal</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Date</Trans>+ </Th>+ <Th className="px-4 w-full">+ <Trans>Source</Trans>+ </Th>+ <Th className="px-4 text-right">+ <Trans>Amount</Trans>+ </Th>+ <Th className="px-4">+ <Trans>Sync</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {journals.map((journal) => (+ <Tr key={journal.id}>+ <Td className="px-4">+ <Hyperlink to={path.to.journalEntryDetails(journal.id)}>+ {journal.journalEntryId}+ </Hyperlink>+ </Td>+ <Td className="px-4 whitespace-nowrap">+ {formatDate(journal.postingDate, undefined, locale)}+ </Td>+ <Td className="px-4">+ <Enumerable value={journal.sourceType} />+ </Td>+ <Td className="px-4 text-right text-sm tabular-nums">+ {currencyFormatter.format(journal.accountAmount)}+ </Td>+ <Td className="px-4">+ {journal.syncStatus ? (+ <Status+ color={+ SYNC_STATUS_COLORS[journal.syncStatus] ?? "gray"+ }+ >+ {journal.syncStatus}+ </Status>+ ) : (+ <Status color="gray">+ <Trans>Not recorded</Trans>+ </Status>+ )}+ </Td>+ </Tr>+ ))}+ </Tbody>+ </Table>+ )}+ </div>+ {truncated && (+ <p className="text-xs text-muted-foreground">+ <Trans>Showing the newest 200 journals</Trans>+ </p>+ )}+ </DrawerBody>+ </DrawerContent>+ </Drawer>+ );+}diff --git a/apps/erp/app/routes/x+/accounting+/sync-tieout.tsx b/apps/erp/app/routes/x+/accounting+/sync-tieout.tsxnew file mode 100644index 0000000000..ec856e6cab--- /dev/null+++ b/apps/erp/app/routes/x+/accounting+/sync-tieout.tsx@@ -0,0 +1,87 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { VStack } from "@carbon/react";+import { msg } from "@lingui/core/macro";+import type { LoaderFunctionArgs } from "react-router";+import { Outlet, useLoaderData } from "react-router";+import { useRouteData } from "~/hooks";+import { getAccountingSyncTieOut } from "~/modules/accounting";+import { SyncTieOutTable } from "~/modules/accounting/ui/SyncTieOut";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import type { Filter } from "~/utils/query";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: msg`Sync Tie-Out`,+ to: path.to.accountingSyncTieOut+};++/** `eq` value or `in` comma-list from the table's filter params. */+function filterValues(+ filters: Filter[] | undefined,+ column: string+): string[] | null {+ const match = filters?.find((filter) => filter.column === column);+ if (!match?.value) return null;+ return match.operator === "in" ? match.value.split(",") : [match.value];+}++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "accounting",+ role: "employee"+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const { filters } = getGenericQueryFilters(searchParams);++ // Table filter params, with the SyncActivity card's direct-param+ // deep-links (?integration=, ?periodId=) as fallbacks.+ const integration =+ filterValues(filters, "integration") ?? searchParams.get("integration");+ const accountId = filterValues(filters, "accountId");+ const accountingPeriodId = searchParams.get("periodId");++ const tieOut = await getAccountingSyncTieOut(client, companyId, {+ integration,+ accountingPeriodId,+ accountId+ });++ return {+ data: tieOut.data ?? [],+ count: tieOut.data?.length ?? 0+ };+}++export default function SyncTieOutRoute() {+ const { data, count } = useLoaderData<typeof loader>();+ const accountingRouteData = useRouteData<{+ accountingIntegrations: string[];+ balanceSheetAccounts: { id: string; number: string | null; name: string }[];+ incomeStatementAccounts: {+ id: string;+ number: string | null;+ name: string;+ }[];+ }>(path.to.accounting);++ const integrations = accountingRouteData?.accountingIntegrations ?? [];+ const accounts = [+ ...(accountingRouteData?.balanceSheetAccounts ?? []),+ ...(accountingRouteData?.incomeStatementAccounts ?? [])+ ];++ return (+ <VStack spacing={0} className="h-full">+ <SyncTieOutTable+ data={data}+ count={count}+ integrations={integrations}+ accounts={accounts}+ />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.post.tsx b/apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.post.tsxindex 7b3010ff54..d9c6b3546b 100644--- a/apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.post.tsx+++ b/apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.post.tsx@@ -4,7 +4,7 @@ import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { getOrCreateAccountingPeriod } from "~/modules/accounting";-import { postDepreciationRun } from "~/modules/accounting/accounting.server";+import { postDepreciationRun } from "~/modules/accounting/accounting.ee.server";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";diff --git a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsx b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsxindex 9887682ada..b47849093c 100644--- a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsx+++ b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.dispose.tsx@@ -9,7 +9,7 @@ import {getFixedAsset,getOrCreateAccountingPeriod} from "~/modules/accounting";-import { postDisposal } from "~/modules/accounting/accounting.server";+import { postDisposal } from "~/modules/accounting/accounting.ee.server";import { FixedAssetDisposalForm } from "~/modules/accounting/ui/FixedAssets";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";diff --git a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.register.tsx b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.register.tsxindex 53f4401dde..24ec9b80fd 100644--- a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.register.tsx+++ b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.register.tsx@@ -10,7 +10,7 @@ import {getFixedAsset,getOrCreateAccountingPeriod} from "~/modules/accounting";-import { postAssetRegistration } from "~/modules/accounting/accounting.server";+import { postAssetRegistration } from "~/modules/accounting/accounting.ee.server";import { FixedAssetRegisterForm } from "~/modules/accounting/ui/FixedAssets";import { getCompanySettings } from "~/modules/settings";import { getDatabaseClient } from "~/services/database.server";diff --git a/apps/erp/app/routes/x+/get-started+/_layout.tsx b/apps/erp/app/routes/x+/get-started+/_layout.tsxindex a6c9b927a7..8dcbf2354e 100644--- a/apps/erp/app/routes/x+/get-started+/_layout.tsx+++ b/apps/erp/app/routes/x+/get-started+/_layout.tsx@@ -251,7 +251,7 @@ export default function GetStartedLayout() {<CollapsibleSidebarProvider><div className="bg-card grid grid-cols-[auto_1fr] grid-rows-[minmax(0,1fr)] w-full h-full overflow-hidden"><GroupedContentSidebar groups={groups} exactMatch />- <div className="relative min-w-0 overflow-hidden">+ <div className="relative min-w-0 overflow-hidden bg-card"><div ref={scrollRef} className="relative z-10 h-full overflow-y-auto">{isInternal ? (<PreviewBar previewing={previewingAsCustomer} />diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex de9d037309..851388363d 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -1,11 +1,42 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import type { Database, Json } from "@carbon/database";import { integrations as availableIntegrations } from "@carbon/ee";import {+ buildDimensionValueMappingEntityId,+ buildRilletFieldTarget,+ buildXeroTrackingTarget,getAccountingIntegration,+ getAccountMappings,+ getDimensionValueMappings,getProviderIntegration,+ getSyncOperations,+ getUnmappedPostingAccounts,+ getUnmappedSlottedDimensionValues,+ JOURNAL_ENTRY_SOURCE_TYPES,+ loadAccountDefaultAccountIds,+ matchAccountsByCode,+ matchDimensionValuesByName,+ POSTING_POLICY,ProviderID,+ QBO_DIMENSION_TARGET_CLASS,+ QBO_DIMENSION_TARGET_DEPARTMENT,+ type QboProvider,+ // Aliased: the PostingSyncSettings component is imported below.+ type PostingSyncSettings as ResolvedPostingSyncSettings,+ type RilletProvider,+ resolveDimensionValueLabels,+ resolvePostingSyncSettings,+ type SyncOperation,+ type SyncOperationStatus,+ SyncOperationStatusSchema,+ suggestAccountMatchesWithAI,+ transitionOperation,+ upsertAccountMapping,+ upsertDimensionValueMapping,+ validateDimensionSlots,+ XERO_MAX_JOURNAL_DIMENSION_SLOTS,type XeroProvider} from "@carbon/ee/accounting";import {@@ -17,108 +48,459 @@ import { isIntegrationWhitelisted } from "@carbon/ee/plan";import { requirePlan } from "@carbon/ee/plan.server";import { validationError, validator } from "@carbon/form";import { getLogger } from "@carbon/logger";+import { Badge } from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";-import { redirect, useLoaderData, useNavigate } from "react-router";-import { getIntegration, IntegrationForm } from "~/modules/settings";+import {+ data,+ redirect,+ useLoaderData,+ useNavigate,+ useSearchParams+} from "react-router";+// Deep service import (not the ~/modules/accounting barrel) to keep this+// route's type graph light — see the TS2589 note in+// ~/modules/settings/ui/Integrations/index.ts.+import { getActiveDimensionsWithValues } from "~/modules/accounting/accounting.ee.service";+import {+ getIntegration,+ IntegrationForm,+ SyncActivity,+ syncOperationTransitionValidator+} from "~/modules/settings";+import {+ accountMappingAiSuggestValidator,+ accountMappingBulkUpsertValidator,+ accountMappingUpsertValidator,+ dimensionSlotsUpdateValidator,+ dimensionValueMappingBulkUpsertValidator,+ dimensionValueMappingUpsertValidator,+ postingSyncSettingsValidator+} from "~/modules/settings/settings.models";import {invalidateIntegrationHealthCache,upsertCompanyIntegration} from "~/modules/settings/settings.server";+import { AccountMapping } from "~/modules/settings/ui/Integrations/AccountMapping";+import { DimensionMapping } from "~/modules/settings/ui/Integrations/DimensionMapping";+import type { IntegrationFormTab } from "~/modules/settings/ui/Integrations/IntegrationForm";+import { PostingSyncSettings } from "~/modules/settings/ui/Integrations/PostingSyncSettings";+import type { SyncReconciliationReport } from "~/modules/settings/ui/Integrations/SyncActivity";+import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";const logger = getLogger("erp", "integrations-id");/**- * Transforms flat owner settings (customerOwner, vendorOwner, etc.) into- * the nested syncConfig.entities structure expected by the accounting sync.+ * Rillet authenticates with an API key entered on the standard install+ * form. The engine reads credentials exclusively from+ * `metadata.credentials` (top-level metadata keys are stripped by+ * ProviderIntegrationMetadataSchema), so fold the form fields into the+ * canonical apiKey credentials variant. The loader mirrors this with+ * `unfoldRilletCredentials`, so the drawer prefills from stored+ * credentials — meaning a re-save round-trips the real values instead of+ * wiping environment/subsidiaryId/webhookToken back to their defaults.+ * What's submitted is what's stored: clearing the webhook token turns+ * inbound payments off.+ */+function foldRilletCredentials(+ metadata: Record<string, unknown>+): Record<string, unknown> {+ const { apiKey, environment, subsidiaryId, webhookToken, ...rest } = metadata;+ if (typeof apiKey !== "string" || apiKey.length === 0) return metadata;++ const providerMetadata = {+ ...(typeof subsidiaryId === "string" && subsidiaryId.length > 0+ ? { subsidiaryId }+ : {}),+ ...(typeof webhookToken === "string" && webhookToken.length > 0+ ? { webhookToken }+ : {})+ };++ return {+ ...rest,+ credentials: {+ type: "apiKey",+ apiKey,+ environment: environment === "sandbox" ? "sandbox" : "production",+ ...(Object.keys(providerMetadata).length > 0 ? { providerMetadata } : {})+ }+ };+}++/**+ * Inverse of `foldRilletCredentials`: unfold the stored+ * `metadata.credentials` back into the flat apiKey/environment/+ * subsidiaryId/webhookToken fields the settings form binds to. Without+ * this the drawer opens with every Connection/Webhooks field blank, and+ * re-saving (which requires the API key) rebuilds credentials from those+ * blank defaults — silently wiping the environment, subsidiary, and+ * webhook token. The loader reads raw metadata (getIntegration does not+ * strip `credentials`), so the values are available here.*/-function buildIntegrationMetadata(- existingMetadata: Record<string, unknown>,- formData: Record<string, unknown>+function unfoldRilletCredentials(+ metadata: Record<string, unknown>): Record<string, unknown> {- // Extract owner settings from form data- const ownerSettings = {- customerOwner: formData.customerOwner as string | undefined,- vendorOwner: formData.vendorOwner as string | undefined,- itemOwner: formData.itemOwner as string | undefined,- invoiceOwner: formData.invoiceOwner as string | undefined,- billOwner: formData.billOwner as string | undefined+ const credentials = metadata.credentials as+ | Record<string, unknown>+ | undefined;+ if (!credentials || credentials.type !== "apiKey") return metadata;++ const providerMetadata =+ (credentials.providerMetadata as Record<string, unknown> | undefined) ?? {};++ return {+ ...metadata,+ apiKey: typeof credentials.apiKey === "string" ? credentials.apiKey : "",+ environment:+ credentials.environment === "sandbox" ? "sandbox" : "production",+ subsidiaryId:+ typeof providerMetadata.subsidiaryId === "string"+ ? providerMetadata.subsidiaryId+ : "",+ webhookToken:+ typeof providerMetadata.webhookToken === "string"+ ? providerMetadata.webhookToken+ : ""};+}++/**+ * Account-mapping data for the integration drawer's Account Mapping tab.+ * The @carbon/ee account-mapping services are Kysely-based (DISTINCT ++ * unbounded reads that supabase-js can't express), so they get the app's+ * Kysely client. Kysely bypasses RLS — safe here because the route has+ * already passed requirePermissions and every query is companyId-scoped.+ */+async function getAccountMappingTabData(+ companyId: string,+ integrationId: string,+ chart: Array<{ id: string; code: string; name: string }>+) {+ const db = getDatabaseClient();++ const [mappings, unmapped, proposals, accountDefaultIds] = await Promise.all([+ getAccountMappings(db, { companyId, integration: integrationId }),+ getUnmappedPostingAccounts(db, { companyId, integration: integrationId }),+ chart.length > 0+ ? matchAccountsByCode(db, {+ companyId,+ integration: integrationId,+ providerAccounts: chart+ })+ : Promise.resolve({ data: [], error: null }),+ loadAccountDefaultAccountIds(db, companyId)+ ]);++ // Don't block the settings drawer on a mapping load failure — render+ // what loaded and log the cause.+ for (const result of [mappings, unmapped, proposals]) {+ if (result.error) {+ console.error("Failed to load account mapping data:", result.error);+ }+ }- // Check if any owner settings are present- const hasOwnerSettings = Object.values(ownerSettings).some(- (v) => v !== undefined+ // The tab manages only accountDefault accounts (the mappable set — every+ // automated posting runs through one), so hide any legacy mapping for an+ // account outside that set: it never syncs and would only inflate the list.+ // getAccountMappings itself is left untouched so the journal/bill/invoice+ // syncers' account resolution keeps seeing every mapping. Unmapped and+ // proposals are already accountDefault-scoped in @carbon/ee.+ const mappableIds = new Set(accountDefaultIds);+ const scopedMappings = (mappings.data ?? []).filter((mapping) =>+ mappableIds.has(mapping.accountId));- if (!hasOwnerSettings) {- // No owner settings, just merge as-is- return { ...existingMetadata, ...formData };+ return {+ mappings: scopedMappings,+ unmapped: unmapped.data ?? [],+ chart,+ proposals: proposals.data ?? []+ };+}++/** One provider analytics target with its selectable option values. */+type DimensionTargetWithValues = {+ id: string;+ label: string;+ capacity: number;+ values: { id: string; name: string }[];+};++/**+ * Provider journal-dimension targets with their selectable values, for+ * the Dimensions tab and the slot-save validation. Guarded on the+ * provider actually implementing `journalDimensionTargets`; option values+ * come from the provider's list methods (Rillet Fields carry their values+ * inline; QBO Classes/Departments and Xero tracking options are the+ * target's own list). A provider API failure degrades to an empty target+ * list + `targetsError` so the settings drawer never blocks on a provider+ * outage.+ */+async function getProviderDimensionTargets(+ client: SupabaseClient<Database>,+ companyId: string,+ integrationId: string+): Promise<{+ supported: boolean;+ targets: DimensionTargetWithValues[];+ maxSlots: number | null;+ targetsError: boolean;+}> {+ const unsupported = {+ supported: false,+ targets: [],+ maxSlots: null,+ targetsError: false+ };++ const providerId = (Object.values(ProviderID) as string[]).includes(+ integrationId+ )+ ? (integrationId as ProviderID)+ : null;+ if (!providerId) return unsupported;++ try {+ const accountingIntegration = await getAccountingIntegration(+ client,+ companyId,+ providerId+ );+ const provider = getProviderIntegration(+ client,+ companyId,+ providerId,+ accountingIntegration.metadata+ );++ if (typeof provider.journalDimensionTargets !== "function") {+ return unsupported;+ }++ if (providerId === ProviderID.RILLET) {+ // One GET /fields serves both the targets and their values (calling+ // journalDimensionTargets() separately would hit the same endpoint+ // twice); target ids come from the engine's composite-id helper.+ const fields = await (provider as RilletProvider).listFields();+ return {+ supported: true,+ targets: fields.map((field) => ({+ id: buildRilletFieldTarget(field.id),+ label: field.name,+ capacity: 1,+ values: (field.values ?? [])+ .filter((value) => !value.deactivated)+ .map((value) => ({ id: value.id, name: value.name }))+ })),+ maxSlots: provider.capabilities?.maxJournalDimensionSlots ?? null,+ targetsError: false+ };+ }++ if (providerId === ProviderID.QUICKBOOKS) {+ // journalDimensionTargets() probes the Intuit feature gates, so an+ // org without class/location tracking sees a reduced target list;+ // the values then load from the matching list method.+ const qbo = provider as QboProvider;+ const declared = await qbo.journalDimensionTargets();+ const targets: DimensionTargetWithValues[] = [];+ for (const target of declared) {+ const options =+ target.id === QBO_DIMENSION_TARGET_CLASS+ ? await qbo.listClasses()+ : target.id === QBO_DIMENSION_TARGET_DEPARTMENT+ ? await qbo.listDepartments()+ : [];+ targets.push({+ id: target.id,+ label: target.label,+ capacity: target.capacity ?? 1,+ values: options.map((option) => ({+ id: option.Id,+ name: option.Name+ }))+ });+ }+ return {+ supported: true,+ targets,+ maxSlots: qbo.capabilities?.maxJournalDimensionSlots ?? null,+ targetsError: false+ };+ }++ // Xero: one target per active tracking category, options inline.+ const categories = await (+ provider as XeroProvider+ ).listTrackingCategories();+ return {+ supported: true,+ targets: categories.map((category) => ({+ id: buildXeroTrackingTarget(category.TrackingCategoryID),+ label: category.Name,+ capacity: 1,+ values: (category.Options ?? [])+ .filter(+ (option) =>+ option.Status === "ACTIVE" || option.Status === undefined+ )+ .map((option) => ({ id: option.TrackingOptionID, name: option.Name }))+ })),+ maxSlots: XERO_MAX_JOURNAL_DIMENSION_SLOTS,+ targetsError: false+ };+ } catch (err) {+ console.error("Failed to load provider dimension targets:", err);+ return { supported: true, targets: [], maxSlots: null, targetsError: true };}+}- // Build syncConfig.entities from owner settings- const existingSyncConfig =- (existingMetadata.syncConfig as Record<string, unknown>) ?? {};- const existingEntities =- (existingSyncConfig.entities as Record<string, unknown>) ?? {};-- const syncConfig = {- ...existingSyncConfig,- entities: {- ...existingEntities,- ...(ownerSettings.customerOwner && {- customer: {- ...(existingEntities.customer as Record<string, unknown>),- owner: ownerSettings.customerOwner- }- }),- ...(ownerSettings.vendorOwner && {- vendor: {- ...(existingEntities.vendor as Record<string, unknown>),- owner: ownerSettings.vendorOwner- }- }),- ...(ownerSettings.itemOwner && {- item: {- ...(existingEntities.item as Record<string, unknown>),- owner: ownerSettings.itemOwner- }- }),- ...(ownerSettings.invoiceOwner && {- invoice: {- ...(existingEntities.invoice as Record<string, unknown>),- owner: ownerSettings.invoiceOwner- }- }),- ...(ownerSettings.billOwner && {- bill: {- ...(existingEntities.bill as Record<string, unknown>),- owner: ownerSettings.billOwner- }- })+/**+ * Dimension-sync data for the integration drawer's Dimensions tab: the+ * provider targets (+ values), the company's dimensions with value counts+ * (high-cardinality warning), the stored slot config, the per-slot value+ * mappings with resolved Carbon labels, the unmapped slotted values, and+ * exact name-match proposals. Returns null when the provider doesn't+ * implement journalDimensionTargets (no tab). The dimension-mapping+ * services are Kysely-based (RLS bypassed) — same auth stance as+ * getAccountMappingTabData.+ */+async function getDimensionSyncTabData(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ companyGroupId: string;+ integrationId: string;+ settings: ResolvedPostingSyncSettings;+ }+) {+ const { companyId, companyGroupId, integrationId, settings } = args;++ const providerTargets = await getProviderDimensionTargets(+ client,+ companyId,+ integrationId+ );+ if (!providerTargets.supported) return null;++ const db = getDatabaseClient();+ const slots = settings.dimensionSlots;++ const [dimensionsResult, mappingsResult, unmappedResult] = await Promise.all([+ getActiveDimensionsWithValues(client, companyGroupId, companyId),+ getDimensionValueMappings(db, { companyId, integration: integrationId }),+ getUnmappedSlottedDimensionValues(db, {+ companyId,+ integration: integrationId,+ slots+ })+ ]);++ // Don't block the settings drawer on a load failure — render what+ // loaded and log the cause.+ for (const result of [dimensionsResult, mappingsResult, unmappedResult]) {+ if (result.error) {+ console.error("Failed to load dimension sync data:", result.error);}- };+ }- // Remove owner settings from formData since they're now in syncConfig- const {- customerOwner: _customerOwner,- vendorOwner: _vendorOwner,- itemOwner: _itemOwner,- invoiceOwner: _invoiceOwner,- billOwner: _billOwner,- ...restFormData- } = formData;+ const dimensions = (dimensionsResult.error ? [] : dimensionsResult.data).map(+ (dimension) => ({+ id: dimension.dimensionId,+ name: dimension.dimensionName,+ entityType: String(dimension.entityType),+ valueCount: dimension.values.length+ })+ );++ const mappingRows = mappingsResult.data ?? [];++ // Readable Carbon labels for the mapped rows (engine-resolved per the+ // dimension's entityType). A resolution failure degrades to raw ids.+ let mappedLabels = new Map<string, string>();+ try {+ mappedLabels = await resolveDimensionValueLabels(db, {+ values: mappingRows.map(({ dimensionId, valueId }) => ({+ dimensionId,+ valueId+ }))+ });+ } catch (err) {+ console.error("Failed to resolve dimension value labels:", err);+ }++ const mappings = mappingRows.map((mapping) => ({+ id: mapping.id,+ dimensionId: mapping.dimensionId,+ valueId: mapping.valueId,+ label:+ mappedLabels.get(+ buildDimensionValueMappingEntityId(mapping.dimensionId, mapping.valueId)+ ) ?? null,+ externalId: mapping.externalId,+ externalName: mapping.externalName+ }));++ const unmapped = unmappedResult.data ?? [];++ // Exact name-match proposals, per slot: each slot pairs one dimension's+ // unmapped values with its provider target's option list. Provider+ // options already used by a mapping on the SAME dimension are excluded+ // (an option may legitimately back several dimensions).+ const targetsById = new Map(+ providerTargets.targets.map((target) => [target.id, target])+ );+ const mappedValueKeys = mappingRows+ .filter((mapping) => mapping.externalId)+ .map((mapping) =>+ buildDimensionValueMappingEntityId(mapping.dimensionId, mapping.valueId)+ );+ const proposals = slots.flatMap((slot) => {+ const target = targetsById.get(slot.target);+ if (!target) return [];+ const values = unmapped.filter(+ (value) => value.dimensionId === slot.dimensionId+ );+ if (values.length === 0) return [];+ const mappedExternalIds = mappingRows.flatMap((mapping) =>+ mapping.dimensionId === slot.dimensionId && mapping.externalId+ ? [mapping.externalId]+ : []+ );+ return matchDimensionValuesByName({+ values,+ providerOptions: target.values,+ mappedValueKeys,+ mappedExternalIds+ });+ });return {- ...existingMetadata,- ...restFormData,- syncConfig+ targets: providerTargets.targets,+ targetsError: providerTargets.targetsError,+ maxSlots: providerTargets.maxSlots,+ // Rillet's Field-value upsert flow defaults auto-create ON; QBO/Xero+ // stay opt-in (see resolveDimensionSlotAutoCreate in @carbon/ee).+ autoCreateDefault: integrationId === ProviderID.RILLET,+ dimensions,+ slots,+ onUnmappedDimensionValue: settings.onUnmappedDimensionValue,+ mappings,+ unmapped,+ proposals};}export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- update: "settings"- });+ const { client, companyId, companyGroupId } = await requirePermissions(+ request,+ {+ update: "settings"+ }+ );const { id: integrationId } = params;if (!integrationId) throw new Error("Integration ID not found");@@ -136,23 +518,165 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return {installed: false,metadata: {},- dynamicOptions: {}+ dynamicOptions: {},+ syncActivity: null,+ accountMapping: null,+ postingSync: null,+ dimensionSync: null+ };+ }++ const isAccountingInstalled =+ integration.category === "Accounting" && integrationData.data.active;++ // Sync-operation inbox for accounting integrations (RLS SELECT covers+ // employees, so the user-scoped client is enough). Params are prefixed+ // (syncStatus/syncPage) to avoid clashing with other search params.+ let syncActivity: {+ operations: SyncOperation[];+ count: number;+ status: SyncOperationStatus | null;+ page: number;+ pageSize: number;+ lastReconciliation: SyncReconciliationReport | null;+ /** Failed + Warning operations — the tab-label badge. */+ failingCount: number;+ /**+ * Tie-out summary: latest computedAt + how many (period × account)+ * cells carry a nonzero internal or external delta. Null when no+ * tie-out rows exist (or the viewer lacks accounting_view — the+ * table's RLS SELECT — in which case the rows read back empty).+ */+ tieOut: {+ computedAt: string | null;+ deltaCellCount: number;+ cellCount: number;+ } | null;+ } | null = null;++ if (isAccountingInstalled) {+ const url = new URL(request.url);+ const statusFilter = SyncOperationStatusSchema.safeParse(+ url.searchParams.get("syncStatus")+ );+ const page = Math.max(+ 1,+ Number.parseInt(url.searchParams.get("syncPage") ?? "1", 10) || 1+ );+ const pageSize = 25;++ const [operations, failingOps, tieOutRows] = await Promise.all([+ getSyncOperations(client, {+ companyId,+ integration: integrationId,+ status: statusFilter.success ? statusFilter.data : undefined,+ limit: pageSize,+ offset: (page - 1) * pageSize+ }),+ // Failed + Warning count for the tab badge — only the exact count is+ // used, so fetch a single row.+ getSyncOperations(client, {+ companyId,+ integration: integrationId,+ status: ["Failed", "Warning"],+ limit: 1+ }),+ // Tie-out cells for this integration. The table is not in the+ // generated DB types yet — cast, same pattern as+ // @carbon/ee/accounting core/operations.ts.+ (client.from("accountingSyncTieOut" as any) as any)+ .select("internalDelta, externalDelta, computedAt")+ .eq("companyId", companyId)+ .eq("integration", integrationId)+ ]);++ if (operations.error) {+ // Don't block the settings drawer on an inbox failure — render the+ // tab empty and log the cause.+ console.error("Failed to load sync operations:", operations.error);+ }++ let tieOut: {+ computedAt: string | null;+ deltaCellCount: number;+ cellCount: number;+ } | null = null;+ const tieOutCells = (tieOutRows.error ? [] : (tieOutRows.data ?? [])) as {+ internalDelta: number | null;+ externalDelta: number | null;+ computedAt: string | null;+ }[];+ if (tieOutCells.length > 0) {+ tieOut = {+ computedAt: tieOutCells.reduce<string | null>(+ (latest, row) =>+ row.computedAt && (latest == null || row.computedAt > latest)+ ? row.computedAt+ : latest,+ null+ ),+ deltaCellCount: tieOutCells.filter(+ (row) =>+ Math.abs(Number(row.internalDelta ?? 0)) > 0.001 ||+ Math.abs(Number(row.externalDelta ?? 0)) > 0.001+ ).length,+ cellCount: tieOutCells.length+ };+ }++ // Latest weekly reconciliation report, written by the+ // accounting-reconciliation cron to+ // metadata.settings.postingSync.lastReconciliation. Shape-guarded so+ // stored garbage renders as "no report" instead of crashing the tab.+ const storedReconciliation = (+ (integrationData.data.metadata as Record<string, any> | null)?.settings+ ?.postingSync as Record<string, any> | undefined+ )?.lastReconciliation;+ const lastReconciliation: SyncReconciliationReport | null =+ storedReconciliation &&+ typeof storedReconciliation.runAt === "string" &&+ Array.isArray(storedReconciliation.drift)+ ? (storedReconciliation as SyncReconciliationReport)+ : null;++ syncActivity = {+ operations: operations.data,+ count: operations.count ?? 0,+ status: statusFilter.success ? statusFilter.data : null,+ page,+ pageSize,+ lastReconciliation,+ failingCount: failingOps.error ? 0 : (failingOps.count ?? 0),+ tieOut};}- // Extract owner settings from syncConfig back into flat fields for the formconst metadata = (integrationData.data.metadata ?? {}) as Record<string,unknown>;- const flattenedMetadata = flattenSyncConfigToOwnerSettings(metadata);+ let flattenedMetadata: Record<string, unknown> = metadata;+ // Rillet keeps its API credentials under metadata.credentials; unfold+ // them into the flat form fields so the drawer prefills instead of+ // showing blanks (which a re-save would then persist over the real+ // stored connection).+ if (integrationId === "rillet") {+ flattenedMetadata = unfoldRilletCredentials(flattenedMetadata);+ }- // Fetch dynamic options for Xero integration (chart of accounts)- let dynamicOptions: Record<+ // Server-fetched options for "options"-type settings fields. No current+ // integration config populates this, but IntegrationForm still accepts it+ // generically for a future provider-fetched choice list.+ const dynamicOptions: Record<string,Array<{ value: string; label: string; description?: string }>> = {};+ // Provider chart of accounts for the Account Mapping tab. Xero manual+ // journals reference accounts by code, so only coded accounts are+ // mappable.+ let chartAccounts: Array<{ id: string; code: string; name: string }> = [];+if (integrationId === "xero" && integrationData.data.active) {try {const xeroIntegration = await getAccountingIntegration(@@ -170,56 +694,132 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const accounts = await provider.listChartOfAccounts();- const accountOptions = accounts.map((account) => ({- value: account.Code ?? account.AccountID,- label: account.Code- ? `${account.Code} - ${account.Name}`- : account.Name,- description: account.Type- }));-- dynamicOptions = {- defaultSalesAccountCode: accountOptions,- defaultPurchaseAccountCode: accountOptions- };+ chartAccounts = accounts.flatMap((account) =>+ account.Code+ ? [{ id: account.AccountID, code: account.Code, name: account.Name }]+ : []+ );} catch (error) {logger.error("Failed to fetch Xero accounts for settings", {error: error});- // Continue without dynamic options - form will show empty selects+ // Continue without chart accounts — the Account Mapping tab renders+ // with Carbon accounts only}}- return {- installed: integrationData.data.active,- metadata: flattenedMetadata,- dynamicOptions- };-}+ if (integrationId === "quickbooks" && integrationData.data.active) {+ try {+ const qboIntegration = await getAccountingIntegration(+ client,+ companyId,+ ProviderID.QUICKBOOKS+ );-/**- * Extracts owner settings from nested syncConfig.entities back into- * flat fields (customerOwner, vendorOwner, etc.) for the form.- */-function flattenSyncConfigToOwnerSettings(- metadata: Record<string, unknown>-): Record<string, unknown> {- const syncConfig = metadata.syncConfig as Record<string, unknown> | undefined;- const entities = syncConfig?.entities as- | Record<string, Record<string, unknown>>- | undefined;+ const provider = getProviderIntegration(+ client,+ companyId,+ qboIntegration.id,+ qboIntegration.metadata+ ) as QboProvider;- if (!entities) {- return metadata;+ // Already normalized to { id, code, name } with code = AcctNum ?? Id.+ // QBO journal lines reference accounts by Id, so every account is+ // mappable — no coded-accounts filter like Xero. (The quickbooks+ // config defines no account-code settings fields, so dynamicOptions+ // stays empty.)+ chartAccounts = await provider.listChartOfAccounts();+ } catch (error) {+ console.error(+ "Failed to fetch QuickBooks Online accounts for settings:",+ error+ );+ // Continue without chart accounts — the Account Mapping tab renders+ // with Carbon accounts only+ }+ }++ if (integrationId === "rillet" && integrationData.data.active) {+ try {+ const rilletIntegration = await getAccountingIntegration(+ client,+ companyId,+ ProviderID.RILLET+ );++ const provider = getProviderIntegration(+ client,+ companyId,+ rilletIntegration.id,+ rilletIntegration.metadata+ ) as RilletProvider;++ // Already normalized to { id, code, name }. Rillet journal items+ // reference accounts by CODE, so only coded, ACTIVE accounts are+ // returned by listChartOfAccounts.+ chartAccounts = await provider.listChartOfAccounts();+ } catch (error) {+ console.error("Failed to fetch Rillet accounts for settings:", error);+ // Continue without chart accounts — the Account Mapping tab renders+ // with Carbon accounts only+ }}+ const accountMapping = isAccountingInstalled+ ? await getAccountMappingTabData(companyId, integrationId, chartAccounts)+ : null;++ const resolvedPostingSettings = isAccountingInstalled+ ? resolvePostingSyncSettings(metadata)+ : null;+ const mappedAccountCount =+ accountMapping?.mappings.filter((mapping) => mapping.externalId).length ??+ 0;+ const postingSync = resolvedPostingSettings+ ? {+ settings: {+ families: resolvedPostingSettings.families,+ sourceTypes: resolvedPostingSettings.sourceTypes,+ periodLockPolicy: resolvedPostingSettings.periodLockPolicy,+ lockDate: resolvedPostingSettings.lockDate+ },+ // Manual never syncs (POSTING_POLICY syncable: false) and is never+ // rendered as a configurable row.+ policy: JOURNAL_ENTRY_SOURCE_TYPES.filter(+ (sourceType) => sourceType !== "Manual"+ ).map((sourceType) => ({+ sourceType,+ representation: POSTING_POLICY[sourceType].representation,+ family: POSTING_POLICY[sourceType].family ?? null+ })),+ mappingReadiness: accountMapping+ ? {+ mapped: mappedAccountCount,+ required: mappedAccountCount + accountMapping.unmapped.length+ }+ : null+ }+ : null;++ // Dimension-sync tab data — accounting integrations whose provider+ // implements journalDimensionTargets (guarded inside the helper).+ const dimensionSync = resolvedPostingSettings+ ? await getDimensionSyncTabData(client, {+ companyId,+ companyGroupId,+ integrationId,+ settings: resolvedPostingSettings+ })+ : null;+return {- ...metadata,- customerOwner: entities.customer?.owner,- vendorOwner: entities.vendor?.owner,- itemOwner: entities.item?.owner,- invoiceOwner: entities.invoice?.owner,- billOwner: entities.bill?.owner+ installed: integrationData.data.active,+ metadata: flattenedMetadata,+ dynamicOptions,+ syncActivity,+ accountMapping,+ postingSync,+ dimensionSync};}@@ -232,6 +832,532 @@ export async function action({ request, params }: ActionFunctionArgs) {const { id: integrationId } = params;if (!integrationId) throw new Error("Integration ID not found");+ const formData = await request.formData();++ // Retry / Skip / Re-send on sync operations (Sync Activity tab). Stays on+ // the page so the inbox revalidates in place — no redirect.+ if (formData.get("intent") === "transition-sync-operation") {+ const validation = await validator(+ syncOperationTransitionValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { ids, to } = validation.data;+ const failures: string[] = [];++ for (const operationId of ids) {+ const result = await transitionOperation(client, {+ id: operationId,+ companyId,+ to,+ userId+ });+ if (result.error) {+ failures.push(result.error);+ }+ }++ if (failures.length > 0) {+ const succeeded = ids.length - failures.length;+ return data(+ {},+ await flash(+ request,+ error(+ failures[0],+ succeeded > 0+ ? `Updated ${succeeded} of ${ids.length} sync operations`+ : "Failed to update sync operation"+ )+ )+ );+ }++ const noun =+ ids.length === 1 ? "sync operation" : `${ids.length} sync operations`;+ return data(+ {},+ await flash(+ request,+ success(+ to === "Skipped" ? `Skipped ${noun}` : `Queued ${noun} for sync`+ )+ )+ );+ }++ // Save one account mapping row (Account Mapping tab). The mapping+ // services are Kysely-based (RLS bypassed) — requirePermissions above ++ // companyId scoping is the auth gate. Stays on the page so the tab+ // revalidates in place.+ if (formData.get("intent") === "upsert-account-mapping") {+ const validation = await validator(accountMappingUpsertValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { accountId, externalId, externalCode, externalName } =+ validation.data;++ const result = await upsertAccountMapping(getDatabaseClient(), {+ companyId,+ integration: integrationId,+ accountId,+ externalId,+ externalCode,+ externalName,+ userId+ });++ if (result.error) {+ return data(+ {},+ await flash(+ request,+ error(result.error, "Failed to save account mapping")+ )+ );+ }++ return data({}, await flash(request, success("Saved account mapping")));+ }++ // "Suggest with AI" from the Account Mapping tab: ask gpt-4o for a+ // best-guess pairing of the still-unmapped Carbon accounts to the+ // provider chart. Writes nothing — returns proposals for the confirm+ // step, which posts them back as `bulk-upsert-account-mappings`.+ if (formData.get("intent") === "ai-suggest-account-mappings") {+ const validation = await validator(+ accountMappingAiSuggestValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { accounts, providerAccounts } = validation.data;++ const result = await suggestAccountMatchesWithAI({+ accounts,+ providerAccounts+ });++ if (result.error || !result.data) {+ return data(+ {},+ await flash(+ request,+ error(result.error, "Failed to suggest account mappings")+ )+ );+ }++ return data({ proposals: result.data });+ }++ // Confirm-all from the match-by-code drawer: repeated JSON-encoded+ // `mappings` fields, one upsert per proposal.+ if (formData.get("intent") === "bulk-upsert-account-mappings") {+ const validation = await validator(+ accountMappingBulkUpsertValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { mappings } = validation.data;+ const db = getDatabaseClient();+ const failures: string[] = [];++ for (const mapping of mappings) {+ const result = await upsertAccountMapping(db, {+ companyId,+ integration: integrationId,+ ...mapping,+ userId+ });+ if (result.error) {+ failures.push(result.error);+ }+ }++ if (failures.length > 0) {+ const succeeded = mappings.length - failures.length;+ return data(+ {},+ await flash(+ request,+ error(+ failures[0],+ succeeded > 0+ ? `Saved ${succeeded} of ${mappings.length} account mappings`+ : "Failed to save account mappings"+ )+ )+ );+ }++ const mappingNoun =+ mappings.length === 1+ ? "account mapping"+ : `${mappings.length} account mappings`;+ return data({}, await flash(request, success(`Saved ${mappingNoun}`)));+ }++ // Save the dimension-slot configuration (Dimensions tab): validate the+ // slots against the provider's declared targets server-side, then+ // read-modify-write the postingSync fragment. Unlike the Posting intent,+ // the v2 shim-marker keys are deliberately LEFT in place — this intent+ // doesn't write the v3 sourceTypes record, so stripping the markers here+ // would make the schema shim lose the stored v2 enabled set on the next+ // read. Stays on the page so the tab revalidates in place.+ if (formData.get("intent") === "update-dimension-slots") {+ const validation = await validator(dimensionSlotsUpdateValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { slots, onUnmappedDimensionValue } = validation.data;++ const providerTargets = await getProviderDimensionTargets(+ client,+ companyId,+ integrationId+ );+ if (!providerTargets.supported) {+ return data(+ {},+ await flash(+ request,+ error(+ "unsupported integration",+ "This integration does not support dimension sync"+ )+ )+ );+ }+ // Clearing every slot is always allowed; validating a non-empty config+ // against a failed target fetch would reject every target as unknown.+ if (slots.length > 0 && providerTargets.targetsError) {+ return data(+ {},+ await flash(+ request,+ error(+ "provider targets unavailable",+ "Couldn't load the provider's dimension targets — try again"+ )+ )+ );+ }+ const slotErrors = validateDimensionSlots({+ slots,+ targets: providerTargets.targets,+ maxSlots: providerTargets.maxSlots ?? undefined+ });+ if (slotErrors.length > 0) {+ return data(+ {},+ await flash(+ request,+ error(slotErrors.join(" "), "Invalid dimension slot configuration")+ )+ );+ }++ const existing = await getIntegration(client, integrationId, companyId);+ if (existing.error || !existing.data) {+ return data(+ {},+ await flash(+ request,+ error(existing.error, "Failed to load integration settings")+ )+ );+ }++ const existingMetadata =+ (existing.data.metadata as Record<string, unknown>) ?? {};+ const existingSettings =+ (existingMetadata.settings as Record<string, unknown> | undefined) ?? {};+ const existingPostingSync =+ (existingSettings.postingSync as Record<string, unknown> | undefined) ??+ {};++ const metadata = {+ ...existingMetadata,+ settings: {+ ...existingSettings,+ postingSync: {+ ...existingPostingSync,+ dimensionSlots: slots,+ onUnmappedDimensionValue+ }+ }+ };++ const update = await upsertCompanyIntegration(client, {+ id: integrationId,+ active: existing.data.active ?? true,+ metadata: metadata as Json,+ companyId,+ updatedBy: userId+ });++ if (update.error) {+ return data(+ {},+ await flash(+ request,+ error(update.error, "Failed to update dimension sync settings")+ )+ );+ }++ await invalidateIntegrationHealthCache(integrationId, companyId);++ return data(+ {},+ await flash(request, success("Updated dimension sync settings"))+ );+ }++ // Save one dimension-value mapping row (Dimensions tab). The mapping+ // services are Kysely-based (RLS bypassed) — requirePermissions above ++ // companyId scoping is the auth gate. Stays on the page so the tab+ // revalidates in place.+ if (formData.get("intent") === "upsert-dimension-value-mapping") {+ const validation = await validator(+ dimensionValueMappingUpsertValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { dimensionId, valueId, externalId, externalName } = validation.data;++ const result = await upsertDimensionValueMapping(getDatabaseClient(), {+ companyId,+ integration: integrationId,+ dimensionId,+ valueId,+ externalId,+ externalName,+ userId+ });++ if (result.error) {+ return data(+ {},+ await flash(+ request,+ error(result.error, "Failed to save dimension value mapping")+ )+ );+ }++ return data(+ {},+ await flash(request, success("Saved dimension value mapping"))+ );+ }++ // Confirm-all from the match-by-name drawer: repeated JSON-encoded+ // `mappings` fields, one upsert per proposal.+ if (formData.get("intent") === "bulk-upsert-dimension-value-mappings") {+ const validation = await validator(+ dimensionValueMappingBulkUpsertValidator+ ).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { mappings } = validation.data;+ const db = getDatabaseClient();+ const failures: string[] = [];++ for (const mapping of mappings) {+ const result = await upsertDimensionValueMapping(db, {+ companyId,+ integration: integrationId,+ ...mapping,+ userId+ });+ if (result.error) {+ failures.push(result.error);+ }+ }++ if (failures.length > 0) {+ const succeeded = mappings.length - failures.length;+ return data(+ {},+ await flash(+ request,+ error(+ failures[0],+ succeeded > 0+ ? `Saved ${succeeded} of ${mappings.length} dimension value mappings`+ : "Failed to save dimension value mappings"+ )+ )+ );+ }++ const dimensionMappingNoun =+ mappings.length === 1+ ? "dimension value mapping"+ : `${mappings.length} dimension value mappings`;+ return data(+ {},+ await flash(request, success(`Saved ${dimensionMappingNoun}`))+ );+ }++ // Persist posting-sync settings (Posting tab): read-modify-write the+ // companyIntegration metadata JSONB, deep-merging the postingSync+ // fragment under metadata.settings so credentials and other settings+ // keys are never clobbered. Stays on the page.+ if (formData.get("intent") === "update-posting-settings") {+ const validation = await validator(postingSyncSettingsValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const {+ sourceTypeConfigs,+ familyAr,+ familyAp,+ periodLockPolicy,+ lockDate+ } = validation.data;++ // "<sourceType>|<granularity>" hidden fields → the v3 per-source-type+ // record. Always-on: every non-Manual journal-represented type is+ // enabled; the form only carries granularity. Manual is hard-excluded+ // (POSTING_POLICY marks it syncable: false; resolution fills its entry+ // from defaults). Document-represented types fill from POSTING_POLICY+ // defaults at resolution time.+ const sourceTypes: Record<+ string,+ { enabled: boolean; granularity: "individual" | "daily-summary" }+ > = {};+ const granularityBySourceType = new Map(+ sourceTypeConfigs.map((config) => {+ const separator = config.lastIndexOf("|");+ return [+ config.slice(0, separator),+ config.slice(separator + 1) as "individual" | "daily-summary"+ ] as const;+ })+ );+ for (const sourceType of JOURNAL_ENTRY_SOURCE_TYPES) {+ if (POSTING_POLICY[sourceType].representation !== "journal") continue;+ if (sourceType === "Manual") continue;+ sourceTypes[sourceType] = {+ enabled: true,+ granularity:+ granularityBySourceType.get(sourceType) ??+ POSTING_POLICY[sourceType].defaultGranularity+ };+ }++ const existing = await getIntegration(client, integrationId, companyId);+ if (existing.error || !existing.data) {+ return data(+ {},+ await flash(+ request,+ error(existing.error, "Failed to load integration settings")+ )+ );+ }++ const existingMetadata =+ (existing.data.metadata as Record<string, unknown>) ?? {};+ const existingSettings =+ (existingMetadata.settings as Record<string, unknown> | undefined) ?? {};+ // Spread the existing postingSync so keys this form doesn't own —+ // lastReconciliation is written by the weekly reconciliation cron —+ // survive a settings save. The v2 shim-marker keys (includeManual,+ // consolidation, the legacy sourceTypes array) are stripped: saving+ // writes the v3 shape, and leaving a marker behind would make the+ // schema shim mis-read the stored fragment as v2.+ const {+ includeManual: _legacyIncludeManual,+ consolidation: _legacyConsolidation,+ sourceTypes: _legacySourceTypes,+ ...existingPostingSync+ } = ((existingSettings.postingSync as+ | Record<string, unknown>+ | undefined) ?? {}) as Record<string, unknown>;++ // Always-on: posting sync has no master toggle anymore. `enabled` is no+ // longer written to postingSync (the stored-schema default is true, and+ // the decision core doesn't read it), and there is no+ // syncConfig.entities.journalEntry mirror to maintain — the provider+ // configs force journalEntry on. Writing the v3 shape strips a stale+ // stored postingSync.enabled on the next save; a stale+ // syncConfig.entities.journalEntry.enabled === false (if any) is left as-is+ // and still honored at the isJournalEntryPostingEnabled seam.+ const { enabled: _legacyEnabled, ...postingSyncWithoutEnabled } =+ existingPostingSync;++ const metadata = {+ ...existingMetadata,+ settings: {+ ...existingSettings,+ postingSync: {+ ...postingSyncWithoutEnabled,+ families: { ar: familyAr, ap: familyAp },+ sourceTypes,+ periodLockPolicy,+ ...(lockDate ? { lockDate } : {})+ }+ }+ };++ const update = await upsertCompanyIntegration(client, {+ id: integrationId,+ active: existing.data.active ?? true,+ metadata: metadata as Json,+ companyId,+ updatedBy: userId+ });++ if (update.error) {+ return data(+ {},+ await flash(+ request,+ error(update.error, "Failed to update posting sync settings")+ )+ );+ }++ await invalidateIntegrationHealthCache(integrationId, companyId);++ return data(+ {},+ await flash(request, success("Updated posting sync settings"))+ );+ }+if (!isIntegrationWhitelisted(integrationId)) {await requirePlan({request,@@ -251,7 +1377,7 @@ export async function action({ request, params }: ActionFunctionArgs) {// discriminated union for Email). Cast to a generic ZodType so the// validator signature accepts it.integration.schema as unknown as Parameters<typeof validator>[0]- ).validate(await request.formData());+ ).validate(formData);if (validation.error) {return validationError(validation.error);@@ -266,8 +1392,10 @@ export async function action({ request, params }: ActionFunctionArgs) {const existingMetadata =(existing.data?.metadata as Record<string, unknown>) ?? {};- // Build metadata, transforming owner settings into syncConfig structure- const metadata = buildIntegrationMetadata(existingMetadata, d);+ let metadata: Record<string, unknown> = { ...existingMetadata, ...d };+ if (integrationId === "rillet") {+ metadata = foldRilletCredentials(metadata);+ }// Onshape asset sync needs the OAuth2Write scope (export jobs + webhook). A// connection authorized read-only can't run it, and a refresh can't widen the@@ -330,6 +1458,22 @@ export async function action({ request, params }: ActionFunctionArgs) {);}}+ } else {+ // Settings save on an already-installed integration: run `onUpdate` so+ // derived server state (e.g. accounting event subscriptions) converges+ // without a reinstall. Best-effort — the save is already persisted, so+ // a hook failure is logged rather than surfaced as a save failure.+ const onUpdate = getIntegrationServerHooks(integrationId)?.onUpdate;+ if (onUpdate) {+ try {+ await onUpdate(companyId);+ } catch (hookError) {+ logger.error("onUpdate hook failed for integration", {+ integrationId,+ error: hookError+ });+ }+ }}// Onshape: keep the release-webhook subscription in lockstep with the@@ -387,16 +1531,112 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function IntegrationRoute() {- const { installed, metadata, dynamicOptions } =- useLoaderData<typeof loader>();+ const {+ installed,+ metadata,+ dynamicOptions,+ syncActivity,+ accountMapping,+ postingSync,+ dimensionSync+ } = useLoaderData<typeof loader>();const navigate = useNavigate();+ const [searchParams] = useSearchParams();++ // Accounting-category integrations get Account Mapping, Posting, Dimensions+ // and Sync Activity tabs next to the Settings form (deep-linkable via+ // ?tab=<value>).+ const tabs: IntegrationFormTab[] = [];+ if (accountMapping) {+ tabs.push({+ value: "account-mapping",+ label: <Trans>Account Mapping</Trans>,+ content: (tabBar) => (+ <AccountMapping+ tabs={tabBar}+ mappings={accountMapping.mappings}+ unmapped={accountMapping.unmapped}+ chart={accountMapping.chart}+ proposals={accountMapping.proposals}+ />+ )+ });+ }+ if (postingSync) {+ tabs.push({+ value: "posting",+ label: <Trans>Posting</Trans>,+ content: (tabBar) => (+ <PostingSyncSettings+ tabs={tabBar}+ settings={postingSync.settings}+ policy={postingSync.policy}+ mappingReadiness={postingSync.mappingReadiness}+ />+ )+ });+ }+ if (dimensionSync) {+ tabs.push({+ value: "dimensions",+ label: <Trans>Dimensions</Trans>,+ content: (tabBar) => (+ <DimensionMapping+ tabs={tabBar}+ targets={dimensionSync.targets}+ targetsError={dimensionSync.targetsError}+ maxSlots={dimensionSync.maxSlots}+ autoCreateDefault={dimensionSync.autoCreateDefault}+ dimensions={dimensionSync.dimensions}+ slots={dimensionSync.slots}+ onUnmappedDimensionValue={dimensionSync.onUnmappedDimensionValue}+ mappings={dimensionSync.mappings}+ unmapped={dimensionSync.unmapped}+ proposals={dimensionSync.proposals}+ />+ )+ });+ }+ if (syncActivity) {+ tabs.push({+ value: "sync-activity",+ label:+ syncActivity.failingCount > 0 ? (+ <span className="flex items-center gap-1.5">+ <Trans>Sync Activity</Trans>+ <Badge variant="orange">{syncActivity.failingCount}</Badge>+ </span>+ ) : (+ <Trans>Sync Activity</Trans>+ ),+ content: (tabBar) => (+ <SyncActivity+ tabs={tabBar}+ operations={syncActivity.operations}+ count={syncActivity.count}+ status={syncActivity.status}+ page={syncActivity.page}+ pageSize={syncActivity.pageSize}+ lastReconciliation={syncActivity.lastReconciliation}+ tieOut={syncActivity.tieOut}+ />+ )+ });+ }++ const tabParam = searchParams.get("tab");+ const defaultTab = tabs.some((tab) => tab.value === tabParam)+ ? (tabParam ?? undefined)+ : undefined;return (<IntegrationForminstalled={installed}metadata={metadata}dynamicOptions={dynamicOptions}+ tabs={tabs.length > 0 ? tabs : undefined}+ defaultTab={defaultTab}onClose={() => navigate(path.to.integrations)}/>);diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 7e3fb65382..e7d5c3b0cc 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -31,6 +31,9 @@ export const path = {accountingPeriodsGenerate: `${x}/accounting/periods/generate`,accountingRoot: `${x}/accounting`,accountingSettings: `${x}/settings/accounting`,+ accountingSyncTieOut: `${x}/accounting/sync-tieout`,+ accountingSyncTieOutCell: (id: string) =>+ generatePath(`${x}/accounting/sync-tieout/${id}`),accountPassword: `${x}/account/password`,accountPersonal: `${x}/account/personal`,accountSecurity: `${x}/account/security`,diff --git a/docs/content/docs/integrations/accounting.mdx b/docs/content/docs/integrations/accounting.mdxindex 4cbb571b66..1a4b1dd323 100644--- a/docs/content/docs/integrations/accounting.mdx+++ b/docs/content/docs/integrations/accounting.mdx@@ -1,47 +1,106 @@---title: Accounting-description: Post invoices to Xero and keep currency exchange rates current automatically.+description: Mirror invoices, bills, and GL journals to Xero, QuickBooks, or Rillet, and keep exchange rates current.----Two accounting integrations: **Xero** mirrors your <Term id="invoice">invoices</Term> into an external ledger, and **Exchange Rates**-keeps multi-currency math honest. Exchange Rates is available on every plan; Xero is an Enterprise-(Business-plan) integration.+Carbon keeps an external accounting ledger in step with what happens inside the ERP. Three ledgers are+supported — **Xero**, **QuickBooks Online**, and **Rillet** — plus an **Exchange Rates** service that keeps+multi-currency math honest. The ledger sync is an Enterprise (Business-plan) feature; Exchange Rates is free+on every plan.-## Xero+## How the sync works<PlanBadge plan="Business" className="my-[8px]" />-Connect over **OAuth**, then choose what Carbon and Xero share. Once connected, Carbon syncs **customers**,-**vendors**, **items**, **sales invoices**, and **bills** with Xero and keeps the two ledgers aligned, with-several of those entities syncing both ways.+Once a ledger is connected, Carbon pushes **customers**, **vendors**, **items**, **sales invoices**, **bills**,+and its automated **GL journals** to the ledger. **Carbon is the source of truth**: its edits always win, and+every record is matched to the same external record each time, so a customer or invoice never duplicates.+Payments recorded in the ledger flow **back** into Carbon to settle the matching invoice or bill.++<Callout type="note" title="Journal mirroring is automatic, and always on">+Connecting a ledger means every automated GL posting Carbon makes is mirrored to it. There is no toggle to+turn that off. Journals you post by hand (`Manual` source) never sync — only automated postings do.+</Callout>++Payment write-back settles the Carbon document from the ledger side: a payment recorded against an invoice in+Xero, QuickBooks, or Rillet comes back as a Carbon payment and an <Term id="invoice-settlement">invoice settlement</Term>,+then posts to Carbon's <Term id="general-ledger">general ledger</Term>. Rillet can also push Carbon-recorded+payments outbound; Xero and QuickBooks are pull-back only.++## Connect a ledger++Xero and QuickBooks Online connect over **OAuth** — no keys to paste. Rillet uses a per-company **API key**.<Steps><Step>- ### Connect over OAuth+ ### Authorize the connection- No keys to paste. Authorizing stores the connection.+ For Xero or QuickBooks, authorizing over OAuth stores the connection. For Rillet, paste the connection+ fields below.</Step><Step>- ### Choose what's shared+ ### Configure the sync- Set backfill, the per-entity source of truth, and the default account mapping (below).+ Set the account mapping, dimensions, and posting-sync options (below) before the first push.</Step><Step>### Run the initial sync- A **Run Initial Sync** action kicks off the first backfill on demand. After that, changes flow continuously, matched to the same Xero record each time so a Carbon customer or invoice never duplicates.+ Xero exposes a **Run Initial Sync** action that seeds the ledger on demand. After that, changes flow+ continuously.</Step></Steps>+Rillet's connection fields:++<FieldTable>+ <Field name="API key" required>The Rillet API key that authenticates the connection. Stored as a secret.</Field>+ <Field name="Environment">**Production** (`api.rillet.com`) or **Sandbox** (`sandbox.api.rillet.com`).</Field>+ <Field name="Subsidiary ID">Optional. The Rillet subsidiary (entity) that Carbon posts into, for multi-entity ledgers.</Field>+ <Field name="Webhook token">Optional secret. Inbound payment write-back stays off until this is set.</Field>+</FieldTable>++<Callout type="warn" title="Xero and QuickBooks are hidden without a server-side client">+Xero appears only when `XERO_CLIENT_ID` is set, and QuickBooks Online only when `QUICKBOOKS_CLIENT_ID` is set+(see [Environment variables](/docs/platform/self-hosting/environment-variables)). Rillet has no such gate — it+authenticates per company with its own API key, so it is always available.+</Callout>++## Configure the sync++An accounting integration has four tabs beyond the basic connection settings.++<FieldTable>+ <Field name="Account Mapping">Map each Carbon posting account to a code in the provider's chart of accounts. Posted journals push using the mapped provider account. Use **Suggest with AI** or **Match by code** to fill the map, then resolve anything left unmapped.</Field>+ <Field name="Dimensions">Map Carbon dimensions to the provider's tracking slots. Xero and QuickBooks expose two slots. Rillet sends every dimension on each line and provisions the matching fields automatically, so the slot editor does not apply to it.</Field>+ <Field name="Posting Sync">Choose how posted journals reach the ledger (see below).</Field>+ <Field name="Sync Activity">Watch every sync operation and retry the ones that failed (see below).</Field>+</FieldTable>++The **Posting Sync** tab controls three things:+<FieldTable>- <Field name="Backfill">Whether to seed Xero with your existing **customers**, **vendors**, and **items** on first connect.</Field>- <Field name="Source of truth">Per entity (customer, vendor, item, invoice, bill): whether **Carbon** or the **accounting system** wins on conflict.</Field>- <Field name="Account mapping">The default **sales** and **purchase** account codes, picked from your Xero chart of accounts.</Field>+ <Field name="Source types">Posted journals with these source types always sync. A per-type **Daily summary** toggle groups a day's journals of that type into one provider entry instead of sending each individually.</Field>+ <Field name="AR / AP representation">How receivables and payables reach the ledger. Each is either **Documents** (push the invoice or bill itself) or **Off — handled outside the sync**.</Field>+ <Field name="Books lock date">A manual date before which Carbon will not push new entries, so a closed period stays closed.</Field></FieldTable>-<Callout type="warn">-Xero only appears when its OAuth client is configured server-side (`XERO_CLIENT_ID`). Without it the-integration is hidden — see [Environment variables](/docs/platform/self-hosting/environment-variables).+## Watch it run++The **Sync Activity** tab is an inbox of every sync operation, with **Status**, **Entity**, **Direction**+(push or pull), **Trigger**, **Attempts**, **Last Attempt**, and any **Error**. Filter by status, **Retry** or+**Skip** a failed operation, **Re-send** a completed one, or **Retry all** at once. When failed operations+remain after an outbound sweep, Carbon raises an in-app notification so the sync never fails silently.++Reconciliation runs weekly and writes the **Sync Tie-Out** report (**Accounting → Reports → Sync Tie-Out**).+It lays out one row per accounting period, account, and integration, comparing what Carbon **Posted** against+what actually **Synced**, and against the **Provider** balance. Any **Internal** or **External Delta** is+flagged so a drift between the two ledgers is visible before it becomes a month-end surprise.++<Callout type="tip" title="Sync Activity is for operators, Tie-Out is for the books">+Sync Activity answers "did this record make it across?" one operation at a time. Tie-Out answers "do the two+ledgers agree?" per account and period. The Sync Activity tab links straight to the tie-out summary for the+integration.</Callout>## Exchange rates@@ -58,9 +117,9 @@ then converted into each company's base currency, so every currency you trade in<Cards><Card title="Accounting reference" href="/docs/reference/accounting">- How Carbon posts to the ledger — what Xero mirrors.+ How Carbon posts to the ledger — what the sync mirrors.</Card><Card title="Invoices" href="/docs/reference/invoices">- The sales and purchase invoices that sync to Xero.+ The sales and purchase invoices that sync to your ledger.</Card></Cards>diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonindex 230f232fbe..ef8136894c 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -22,8 +22,6 @@"no-derived-percent-column::20250204164256_numeric-increase-2.sql::ALTER TABLE \"supplierQuoteLinePrice\" ADD COLUMN \"taxPercent\" NUMERIC GENERATED ALWAYS AS (","no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx::maximumFractionDigits: 2","no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx::minimumFractionDigits: 2,",- "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyBalanceMatrix.tsx::maximumFractionDigits: 0",- "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyBalanceMatrix.tsx::minimumFractionDigits: 0,","no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx::maximumFractionDigits: 2","no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx::minimumFractionDigits: 2,","no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/ExecutivePnlSummary.tsx::maximumFractionDigits: 1",@@ -64,6 +62,8 @@"no-inline-fraction-digits::apps/erp/app/modules/quality/ui/Inspections/InspectionMeasurementGrid.tsx::{ formatOptions: { maximumFractionDigits: 6 } },","no-inline-fraction-digits::apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx::maximumFractionDigits: 10","no-inline-fraction-digits::apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx::minimumFractionDigits: 0,",+ "no-inline-fraction-digits::apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx::maximumFractionDigits: 2",+ "no-inline-fraction-digits::apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx::minimumFractionDigits: 2,","no-inline-fraction-digits::apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx::maximumFractionDigits: 0,","no-inline-fraction-digits::apps/erp/app/routes/onboarding+/plan.tsx::maximumFractionDigits: 0","no-inline-fraction-digits::apps/erp/app/routes/onboarding+/plan.tsx::minimumFractionDigits: 0,",@@ -76,8 +76,6 @@"no-inline-fraction-digits::apps/mes/app/components/JobOperation/components/QuantityModal.tsx::minimumFractionDigits: 0,","no-inline-fraction-digits::apps/mes/app/routes/display+/$workCenterId.maintenance.tsx::maximumFractionDigits: 0","no-inline-fraction-digits::apps/mes/app/routes/display+/$workCenterId.maintenance.tsx::style: \"currency\",",- "no-inline-fraction-digits::packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx::maximumFractionDigits: line.unitPricePrecision ?? 2",- "no-inline-fraction-digits::packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx::minimumFractionDigits: line.unitPricePrecision ?? 2,","no-inline-fraction-digits::packages/jobs/src/inngest/functions/notifications/content.ts::return amount.toLocaleString(\"en-US\", { minimumFractionDigits: 2 });","no-inline-fraction-digits::packages/jobs/src/inngest/functions/notifications/content.ts::style: \"currency\"","no-legacy-rls::20230123004206_claims.sql::has_company_permission(",@@ -165,7 +163,7 @@"no-legacy-rls::20250128094053_traceability.sql::has_company_permission(","no-legacy-rls::20260115143000_purchasing-rfq.sql::has_company_permission(","no-legacy-rls::20260430000001_tax-status.sql::has_company_permission(",- "no-local-timezone::apps/erp/app/modules/accounting/accounting.service.ts::new Date().toISOString().split(\"T\")[0]",+ "no-local-timezone::apps/erp/app/modules/accounting/accounting.ee.service.ts::new Date().toISOString().split(\"T\")[0]","no-local-timezone::apps/erp/app/modules/items/items.service.ts::new Date().toISOString().split(\"T\")[0]","no-local-timezone::apps/erp/app/modules/sales/sales.service.ts::new Date().toISOString().split(\"T\")[0]","no-local-timezone::packages/database/supabase/functions/get-method/index.ts::new Date().toISOString().slice(0, 10)",@@ -301,7 +299,7 @@"no-raw-rounding::apps/erp/app/components/TimeCardWarning.tsx::const hoursElapsed = Math.floor(","no-raw-rounding::apps/erp/app/hooks/useScrollPosition.tsx::Math.ceil(el.scrollLeft + el.clientWidth) < el.scrollWidth","no-raw-rounding::apps/erp/app/hooks/useScrollPosition.tsx::setCanScrollRight(Math.ceil(scrollLeft + clientWidth) < scrollWidth);",- "no-raw-rounding::apps/erp/app/modules/accounting/accounting.service.ts::const year = firstYear + Math.floor((startMonth - 1 + (p - 1)) / 12);",+ "no-raw-rounding::apps/erp/app/modules/accounting/accounting.ee.service.ts::const year = firstYear + Math.floor((startMonth - 1 + (p - 1)) / 12);","no-raw-rounding::apps/erp/app/modules/accounting/accounting.utils.ts::const quarterPlaced = Math.ceil((startDate.getMonth() + 1) / 3);","no-raw-rounding::apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassesTable.tsx::const years = life ? Math.round((life / 12) * 10) / 10 : null;","no-raw-rounding::apps/erp/app/modules/agent/ui/greetings.ts::return GREETINGS[Math.floor(Math.random() * GREETINGS.length)]();",@@ -387,6 +385,7 @@"no-raw-rounding::apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx::const m = Math.floor(s / 60);","no-raw-rounding::apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx::const s = Math.max(0, Math.floor(ms / 1000));","no-raw-rounding::apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx::).toFixed(2)}MB`",+ "no-raw-rounding::apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx::const totalPages = Math.max(1, Math.ceil(count / pageSize));","no-raw-rounding::apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx::? Math.max(0.5, Math.round((Number(llMatch[1]) / dpi) * 10) / 10)","no-raw-rounding::apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx::? Math.max(0.5, Math.round((Number(pwMatch[1]) / dpi) * 10) / 10)","no-raw-rounding::apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx::const dpmm = Math.round(dpi / 25.4);",@@ -480,11 +479,30 @@"no-raw-rounding::packages/documents/src/pdf/KanbanLabelPDF.tsx::const pageCount = Math.ceil(labels.length / labelsPerPage);","no-raw-rounding::packages/documents/src/pdf/ProductLabelPDF.tsx::const pageCount = Math.ceil(items.length / labelsPerPage);","no-raw-rounding::packages/documents/src/pdf/components/labelGeometry.ts::const qrModuleSize = Math.max(2, Math.min(8, Math.round(4 * scale)));",+ "no-raw-rounding::packages/ee/src/accounting/core/document-costing.ts::(sum, line) => sum + Math.round(line.amount * 100),",+ "no-raw-rounding::packages/ee/src/accounting/core/document-costing.ts::const targetCents = Math.round(baseTotalCents / exchangeRate);",+ "no-raw-rounding::packages/ee/src/accounting/core/payment-application.ts::const settledCents = Math.round(args.settledTotal * 100);",+ "no-raw-rounding::packages/ee/src/accounting/core/payment-application.ts::const totalCents = Math.round(args.invoiceTotal * 100);",+ "no-raw-rounding::packages/ee/src/accounting/core/posting.ts::(centsByAccount.get(key) ?? 0) + Math.round(line.amount * 100)",+ "no-raw-rounding::packages/ee/src/accounting/core/posting.ts::(sum, line) => sum + Math.round(line.amount * 100),",+ "no-raw-rounding::packages/ee/src/accounting/core/posting.ts::const cents = Math.round(line.amount * 100);",+ "no-raw-rounding::packages/ee/src/accounting/core/posting.ts::const residueCapCents = Math.ceil(allLines.length / 2);",+ "no-raw-rounding::packages/ee/src/accounting/core/posting.ts::const rounded = Math.round(amount * 100) / 100;",+ "no-raw-rounding::packages/ee/src/accounting/core/remote-journal.ts::Math.round((Number(line.LineAmount) || 0) * 100)",+ "no-raw-rounding::packages/ee/src/accounting/core/remote-journal.ts::const magnitude = Math.round((Number(item.amount?.amount) || 0) * 100);",+ "no-raw-rounding::packages/ee/src/accounting/core/remote-journal.ts::const magnitude = Math.round((Number(line.Amount) || 0) * 100);",+ "no-raw-rounding::packages/ee/src/accounting/providers/rillet/entities/journal-entry.ts::amount: roundCurrency(Math.abs(signedAmount)).toFixed(2),",+ "no-raw-rounding::packages/ee/src/accounting/providers/rillet/entities/shared.ts::return { amount: roundCurrency(amount).toFixed(2), currency };",+ "no-raw-rounding::packages/ee/src/accounting/providers/xero/provider.ts::Number.isNaN(sinceMs) ? Date.now() : Math.floor(sinceMs / 1000) * 1000","no-raw-rounding::packages/ee/src/onshape/lib/client.ts::`Onshape external data ${foreignId} exceeds the ${Math.round(","no-raw-rounding::packages/ee/src/slack/lib/client.ts::const currentTime = Math.floor(Date.now() / 1000);","no-raw-rounding::packages/ee/src/slack/lib/messages.ts::? `on <!date^${Math.floor(","no-raw-rounding::packages/ee/src/slack/lib/messages.ts::? `• Completed <!date^${Math.floor(","no-raw-rounding::packages/ee/src/slack/lib/messages.ts::text: `Updated by <@${update.updatedBy}> at <!date^${Math.floor(",+ "no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts::Math.round(amount * 100)",+ "no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts::const cents = Math.round(",+ "no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts::const cents = Math.round(amount * 100);",+ "no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts::const cents = Math.round(line.amount * 100);","no-raw-rounding::packages/jobs/src/inngest/functions/scheduled/cleanup.ts::await step.sleep(\"jitter\", `${Math.floor(Math.random() * 3600)}s`);","no-raw-rounding::packages/react/src/BarProgress.tsx::<span className=\"sr-only\">{Math.round(percentage)}%</span>","no-raw-rounding::packages/react/src/BarProgress.tsx::const activeBars = Math.round((clampedProgress / max) * barCount);",diff --git a/packages/checks/src/conformance/module-shape.test.ts b/packages/checks/src/conformance/module-shape.test.tsindex f8e9f5c317..3762e73400 100644--- a/packages/checks/src/conformance/module-shape.test.ts+++ b/packages/checks/src/conformance/module-shape.test.ts@@ -42,6 +42,34 @@ describe("moduleShape", () => {);});+ it("accepts the .ee-licensed service/server variant as the primary file", () => {+ const v = moduleShape.inspect(+ mod("accounting", [+ "accounting.ee.service.ts",+ "accounting.models.ts",+ "types.ts",+ "ui",+ "index.ts",+ "accounting.ee.server.ts"+ ])+ );+ expect(v).toHaveLength(0);+ });++ it("still flags a second service file alongside the .ee variant", () => {+ const v = moduleShape.inspect(+ mod("accounting", [+ "accounting.ee.service.ts",+ "accounting.models.ts",+ "types.ts",+ "ui",+ "index.ts",+ "extra.service.ts"+ ])+ );+ expect(v.map((x) => x.snippet)).toContain("extra-service:extra.service.ts");+ });+it("flags a missing primary service file", () => {const v = moduleShape.inspect(mod("sales", ["sales.models.ts", "types.ts", "ui", "index.ts"])diff --git a/packages/checks/src/conformance/module-shape.ts b/packages/checks/src/conformance/module-shape.tsindex 2e23547379..d6598c82a2 100644--- a/packages/checks/src/conformance/module-shape.ts+++ b/packages/checks/src/conformance/module-shape.ts@@ -6,7 +6,7 @@ const REQUIRED_ENTRIES = ["types.ts", "ui", "index.ts"];export const moduleShape: StructureCheck = {id: "module-shape",description:- "Each ERP module: one <name>.service.ts, one <name>.models.ts, types.ts, ui/, index.ts.",+ "Each ERP module: one <name>.service.ts (or <name>.ee.service.ts), one <name>.models.ts, types.ts, ui/, index.ts.",provenance: {deprecates: "scattered service/models files",replacedBy: "one <module>.service.ts + one <module>.models.ts"@@ -23,18 +23,23 @@ export const moduleShape: StructureCheck = {}for (const kind of ["service", "models"] as const) {- const expected = `${module.name}.${kind}.ts`;+ const canonical = `${module.name}.${kind}.ts`;+ // A `.ee` infix marks a file as commercial-licensed (see root LICENSE);+ // a module may keep its single service/models file under that name.+ const eeVariant = `${module.name}.ee.${kind}.ts`;const found = module.entries.filter((e) => e.endsWith(`.${kind}.ts`));- if (!found.includes(expected)) {+ if (!found.includes(canonical) && !found.includes(eeVariant)) {add(- `missing:${expected}`,- `Module "${module.name}" must have ${expected}.`+ `missing:${canonical}`,+ `Module "${module.name}" must have ${canonical} (or ${eeVariant}).`);}- for (const extra of found.filter((e) => e !== expected)) {+ for (const extra of found.filter(+ (e) => e !== canonical && e !== eeVariant+ )) {add(`extra-${kind}:${extra}`,- `Extra ${kind} file "${extra}" — fold into ${expected}.`+ `Extra ${kind} file "${extra}" — fold into ${canonical}.`);}}diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.tsindex 0b07abb419..1eaa54bb65 100644--- a/packages/database/src/seed-dev.ts+++ b/packages/database/src/seed-dev.ts@@ -52,6 +52,15 @@ async function main() {// Must run before resetSequences, and before any nextSequence() call.await ensureSequences(client, companyId);+ // Dev/test convenience: enable accounting so posting flows create GL+ // journals out of the box. Runs for pre-existing companies too (the+ // bootstrap path also sets it for brand-new ones). Production keeps+ // the column default (false) — this script is dev-seed only.+ await client.query(+ `UPDATE "companySettings" SET "accountingEnabled" = true WHERE id = $1`,+ [companyId]+ );+if (skipWipe) {console.log("Skipping wipe (--skip-wipe).");} else {diff --git a/packages/database/src/seed-dev/bootstrap.ts b/packages/database/src/seed-dev/bootstrap.tsindex eb2067d5b6..2dd89bfebd 100644--- a/packages/database/src/seed-dev/bootstrap.ts+++ b/packages/database/src/seed-dev/bootstrap.ts@@ -104,6 +104,16 @@ export async function bootstrap([companyId, DEV_COMPANY_NAME, companyGroupId]);+ // Dev/test convenience: enable accounting so posting flows create GL+ // journals out of the box (the companySettings row was just created by+ // the company-insert trigger with the column default, false). Production+ // deliberately keeps accountingEnabled=false by default — this runs only+ // through the dev seed.+ await client.query(+ `UPDATE "companySettings" SET "accountingEnabled" = true WHERE id = $1`,+ [companyId]+ );+await client.query(`INSERT INTO storage.buckets (id, name, public) VALUES ($1, $2, false)`,[companyId, companyId]diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 029d79ba65..def09654a1 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -597,6 +597,276 @@ export default {tags: ["noQuoteReason"]}},+ "/accountingSyncOperation": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.id"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.integration"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.entityType"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.entityId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.direction"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.trigger"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.status"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.idempotencyKey"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.attemptCount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.lastAttemptAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.completedAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.errorCode"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.errorMessage"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.externalId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.metadata"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.updatedAt"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/accountingSyncOperation"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["accountingSyncOperation"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.accountingSyncOperation"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["accountingSyncOperation"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.id"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.integration"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.entityType"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.entityId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.direction"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.trigger"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.status"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.idempotencyKey"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.attemptCount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.lastAttemptAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.completedAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.errorCode"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.errorMessage"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.externalId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.metadata"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.updatedAt"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["accountingSyncOperation"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.id"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.integration"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.entityType"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.entityId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.direction"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.trigger"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.status"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.idempotencyKey"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.attemptCount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.lastAttemptAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.completedAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.errorCode"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.errorMessage"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.externalId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.metadata"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncOperation.updatedAt"+ },+ {+ $ref: "#/parameters/body.accountingSyncOperation"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["accountingSyncOperation"]+ }+ },"/workflowVersion": {get: {parameters: [@@ -75405,107 +75675,368 @@ export default {tags: ["passkeyCredential"]}},- "/fixedAsset": {+ "/accountingSyncTieOut": {get: {parameters: [{- $ref: "#/parameters/rowFilter.fixedAsset.id"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.fixedAssetId"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.fixedAssetClassId"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.name"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.description"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.serialNumber"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.status"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.depreciationMethod"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.usefulLifeMonths"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.residualValuePercent"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.taxDepreciationMethod"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.id"},{- $ref: "#/parameters/rowFilter.fixedAsset.taxUsefulLifeMonths"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.companyId"},{- $ref: "#/parameters/rowFilter.fixedAsset.taxResidualValuePercent"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.integration"},{- $ref: "#/parameters/rowFilter.fixedAsset.macrsPropertyClass"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.accountingPeriodId"},{- $ref: "#/parameters/rowFilter.fixedAsset.macrsConvention"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.accountId"},{- $ref: "#/parameters/rowFilter.fixedAsset.bonusDepreciationPercent"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.carbonPostedAmount"},{- $ref: "#/parameters/rowFilter.fixedAsset.acquisitionCost"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.syncedAmount"},{- $ref: "#/parameters/rowFilter.fixedAsset.acquisitionDate"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.docBackedAmount"},{- $ref: "#/parameters/rowFilter.fixedAsset.depreciationStartDate"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.excludedAmount"},{- $ref: "#/parameters/rowFilter.fixedAsset.accumulatedDepreciation"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.pendingAmount"},{- $ref: "#/parameters/rowFilter.fixedAsset.accumulatedTaxDepreciation"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.blockedAmount"},{- $ref: "#/parameters/rowFilter.fixedAsset.assetLifetimeUsage"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.providerAmount"},{- $ref: "#/parameters/rowFilter.fixedAsset.locationId"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.internalDelta"},{- $ref: "#/parameters/rowFilter.fixedAsset.disposalDate"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.externalDelta"},{- $ref: "#/parameters/rowFilter.fixedAsset.disposalMethod"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.computedAt"},{- $ref: "#/parameters/rowFilter.fixedAsset.saleProceeds"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.companyId"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.createdAt"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.createdBy"- },- {- $ref: "#/parameters/rowFilter.fixedAsset.updatedAt"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.createdBy"},{- $ref: "#/parameters/rowFilter.fixedAsset.updatedBy"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.createdAt"},{- $ref: "#/parameters/rowFilter.fixedAsset.notes"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.updatedBy"},{- $ref: "#/parameters/rowFilter.fixedAsset.customFields"+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.updatedAt"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/accountingSyncTieOut"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["accountingSyncTieOut"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.accountingSyncTieOut"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["accountingSyncTieOut"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.id"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.integration"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.accountingPeriodId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.accountId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.carbonPostedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.syncedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.docBackedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.excludedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.pendingAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.blockedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.providerAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.internalDelta"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.externalDelta"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.computedAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.updatedAt"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["accountingSyncTieOut"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.id"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.integration"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.accountingPeriodId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.accountId"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.carbonPostedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.syncedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.docBackedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.excludedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.pendingAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.blockedAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.providerAmount"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.internalDelta"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.externalDelta"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.computedAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.accountingSyncTieOut.updatedAt"+ },+ {+ $ref: "#/parameters/body.accountingSyncTieOut"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["accountingSyncTieOut"]+ }+ },+ "/fixedAsset": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.fixedAsset.id"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.fixedAssetId"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.fixedAssetClassId"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.name"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.description"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.serialNumber"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.status"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.depreciationMethod"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.usefulLifeMonths"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.residualValuePercent"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.taxDepreciationMethod"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.taxUsefulLifeMonths"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.taxResidualValuePercent"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.macrsPropertyClass"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.macrsConvention"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.bonusDepreciationPercent"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.acquisitionCost"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.acquisitionDate"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.depreciationStartDate"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.accumulatedDepreciation"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.accumulatedTaxDepreciation"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.assetLifetimeUsage"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.locationId"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.disposalDate"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.disposalMethod"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.saleProceeds"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.updatedAt"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.notes"+ },+ {+ $ref: "#/parameters/rowFilter.fixedAsset.customFields"},{$ref: "#/parameters/select"@@ -98120,6 +98651,124 @@ export default {},type: "object"},+ accountingSyncOperation: {+ required: [+ "id",+ "companyId",+ "integration",+ "entityType",+ "entityId",+ "direction",+ "trigger",+ "status",+ "idempotencyKey",+ "attemptCount",+ "createdBy",+ "createdAt"+ ],+ properties: {+ id: {+ default: "public.id('syncop'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ integration: {+ format: "text",+ type: "string"+ },+ entityType: {+ format: "text",+ type: "string"+ },+ entityId: {+ format: "text",+ type: "string"+ },+ direction: {+ format: "text",+ type: "string"+ },+ trigger: {+ format: "text",+ type: "string"+ },+ status: {+ default: "Pending",+ enum: [+ "Pending",+ "In Flight",+ "Completed",+ "Failed",+ "Warning",+ "Skipped",+ "Excluded"+ ],+ format: 'public."syncOperationStatus"',+ type: "string"+ },+ idempotencyKey: {+ format: "text",+ type: "string"+ },+ attemptCount: {+ default: 0,+ format: "integer",+ type: "integer"+ },+ lastAttemptAt: {+ format: "timestamp with time zone",+ type: "string"+ },+ completedAt: {+ format: "timestamp with time zone",+ type: "string"+ },+ errorCode: {+ format: "text",+ type: "string"+ },+ errorMessage: {+ format: "text",+ type: "string"+ },+ externalId: {+ format: "text",+ type: "string"+ },+ metadata: {+ format: "jsonb"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string"+ }+ },+ type: "object"+ },workflowVersion: {required: ["id",@@ -133395,6 +134044,125 @@ export default {},type: "object"},+ accountingSyncTieOut: {+ required: [+ "id",+ "companyId",+ "integration",+ "accountingPeriodId",+ "accountId",+ "carbonPostedAmount",+ "syncedAmount",+ "docBackedAmount",+ "excludedAmount",+ "pendingAmount",+ "blockedAmount",+ "internalDelta",+ "computedAt",+ "createdBy",+ "createdAt"+ ],+ properties: {+ id: {+ default: "public.id('tieout'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ integration: {+ format: "text",+ type: "string"+ },+ accountingPeriodId: {+ description:+ "Note:\nThis is a Foreign Key to `accountingPeriod.id`.<fk table='accountingPeriod' column='id'/>",+ format: "text",+ type: "string"+ },+ accountId: {+ description:+ "Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",+ format: "text",+ type: "string"+ },+ carbonPostedAmount: {+ default: 0,+ format: "numeric",+ type: "number"+ },+ syncedAmount: {+ default: 0,+ format: "numeric",+ type: "number"+ },+ docBackedAmount: {+ default: 0,+ format: "numeric",+ type: "number"+ },+ excludedAmount: {+ default: 0,+ format: "numeric",+ type: "number"+ },+ pendingAmount: {+ default: 0,+ format: "numeric",+ type: "number"+ },+ blockedAmount: {+ default: 0,+ format: "numeric",+ type: "number"+ },+ providerAmount: {+ format: "numeric",+ type: "number"+ },+ internalDelta: {+ default: 0,+ format: "numeric",+ type: "number"+ },+ externalDelta: {+ format: "numeric",+ type: "number"+ },+ computedAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string"+ }+ },+ type: "object"+ },fixedAsset: {required: ["id",@@ -139279,6 +140047,135 @@ export default {in: "query",type: "string"},+ "body.accountingSyncOperation": {+ name: "accountingSyncOperation",+ description: "accountingSyncOperation",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/accountingSyncOperation"+ }+ },+ "rowFilter.accountingSyncOperation.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.integration": {+ name: "integration",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.entityType": {+ name: "entityType",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.entityId": {+ name: "entityId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.direction": {+ name: "direction",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.trigger": {+ name: "trigger",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.status": {+ name: "status",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.idempotencyKey": {+ name: "idempotencyKey",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.attemptCount": {+ name: "attemptCount",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.lastAttemptAt": {+ name: "lastAttemptAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.completedAt": {+ name: "completedAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.errorCode": {+ name: "errorCode",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.errorMessage": {+ name: "errorMessage",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.externalId": {+ name: "externalId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.metadata": {+ name: "metadata",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncOperation.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string"+ },"body.workflowVersion": {name: "workflowVersion",description: "workflowVersion",@@ -178699,6 +179596,129 @@ export default {in: "query",type: "string"},+ "body.accountingSyncTieOut": {+ name: "accountingSyncTieOut",+ description: "accountingSyncTieOut",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/accountingSyncTieOut"+ }+ },+ "rowFilter.accountingSyncTieOut.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.integration": {+ name: "integration",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.accountingPeriodId": {+ name: "accountingPeriodId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.accountId": {+ name: "accountId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.carbonPostedAmount": {+ name: "carbonPostedAmount",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.syncedAmount": {+ name: "syncedAmount",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.docBackedAmount": {+ name: "docBackedAmount",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.excludedAmount": {+ name: "excludedAmount",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.pendingAmount": {+ name: "pendingAmount",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.blockedAmount": {+ name: "blockedAmount",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.providerAmount": {+ name: "providerAmount",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.internalDelta": {+ name: "internalDelta",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.externalDelta": {+ name: "externalDelta",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.computedAt": {+ name: "computedAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.accountingSyncTieOut.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string"+ },"body.fixedAsset": {name: "fixedAsset",description: "fixedAsset",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex b414c38e84..2c5476cb03 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -1641,6 +1641,360 @@ export type Database = {},]}+ accountingSyncOperation: {+ Row: {+ attemptCount: number+ companyId: string+ completedAt: string | null+ createdAt: string+ createdBy: string+ direction: string+ entityId: string+ entityType: string+ errorCode: string | null+ errorMessage: string | null+ externalId: string | null+ id: string+ idempotencyKey: string+ integration: string+ lastAttemptAt: string | null+ metadata: Json | null+ status: Database["public"]["Enums"]["syncOperationStatus"]+ trigger: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ attemptCount?: number+ companyId: string+ completedAt?: string | null+ createdAt?: string+ createdBy: string+ direction: string+ entityId: string+ entityType: string+ errorCode?: string | null+ errorMessage?: string | null+ externalId?: string | null+ id?: string+ idempotencyKey: string+ integration: string+ lastAttemptAt?: string | null+ metadata?: Json | null+ status?: Database["public"]["Enums"]["syncOperationStatus"]+ trigger: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ attemptCount?: number+ companyId?: string+ completedAt?: string | null+ createdAt?: string+ createdBy?: string+ direction?: string+ entityId?: string+ entityType?: string+ errorCode?: string | null+ errorMessage?: string | null+ externalId?: string | null+ id?: string+ idempotencyKey?: string+ integration?: string+ lastAttemptAt?: string | null+ metadata?: Json | null+ status?: Database["public"]["Enums"]["syncOperationStatus"]+ trigger?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "accountingSyncOperation_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingSyncOperation_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ accountingSyncTieOut: {+ Row: {+ accountId: string+ accountingPeriodId: string+ blockedAmount: number+ carbonPostedAmount: number+ companyId: string+ computedAt: string+ createdAt: string+ createdBy: string+ docBackedAmount: number+ excludedAmount: number+ externalDelta: number | null+ id: string+ integration: string+ internalDelta: number+ pendingAmount: number+ providerAmount: number | null+ syncedAmount: number+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ accountId: string+ accountingPeriodId: string+ blockedAmount?: number+ carbonPostedAmount?: number+ companyId: string+ computedAt?: string+ createdAt?: string+ createdBy: string+ docBackedAmount?: number+ excludedAmount?: number+ externalDelta?: number | null+ id?: string+ integration: string+ internalDelta?: number+ pendingAmount?: number+ providerAmount?: number | null+ syncedAmount?: number+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ accountId?: string+ accountingPeriodId?: string+ blockedAmount?: number+ carbonPostedAmount?: number+ companyId?: string+ computedAt?: string+ createdAt?: string+ createdBy?: string+ docBackedAmount?: number+ excludedAmount?: number+ externalDelta?: number | null+ id?: string+ integration?: string+ internalDelta?: number+ pendingAmount?: number+ providerAmount?: number | null+ syncedAmount?: number+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "accountingSyncTieOut_accountId_fkey"+ columns: ["accountId"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_accountId_fkey"+ columns: ["accountId"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_accountingPeriodId_fkey"+ columns: ["accountingPeriodId"]+ isOneToOne: false+ referencedRelation: "accountingPeriod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }address: {Row: {addressLine1: string | null@@ -71392,6 +71746,13 @@ export type Database = {shipmentStateProvince: string | null}Relationships: [+ {+ foreignKeyName: "address_countryCode_fkey"+ columns: ["customerCountryCode"]+ isOneToOne: false+ referencedRelation: "country"+ referencedColumns: ["alpha2"]+ },{foreignKeyName: "address_countryCode_fkey"columns: ["shipmentCountryCode"]@@ -71401,7 +71762,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -78578,6 +78939,14 @@ export type Database = {| "Cancelled"supplierStatusType: "Active" | "Inactive" | "Pending" | "Rejected"supplySourceType: "Purchase Order" | "Production Order"+ syncOperationStatus:+ | "Pending"+ | "In Flight"+ | "Completed"+ | "Failed"+ | "Warning"+ | "Skipped"+ | "Excluded"tableViewType: "Public" | "Private"taxDepreciationMethod: "Straight Line" | "Declining Balance" | "MACRS"taxExemptionReason:@@ -79997,6 +80366,15 @@ export const Constants = {],supplierStatusType: ["Active", "Inactive", "Pending", "Rejected"],supplySourceType: ["Purchase Order", "Production Order"],+ syncOperationStatus: [+ "Pending",+ "In Flight",+ "Completed",+ "Failed",+ "Warning",+ "Skipped",+ "Excluded",+ ],tableViewType: ["Public", "Private"],taxDepreciationMethod: ["Straight Line", "Declining Balance", "MACRS"],taxExemptionReason: [diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.tsindex bf579991ae..6fbaac8f0f 100644--- a/packages/database/supabase/functions/lib/seed.data.ts+++ b/packages/database/supabase/functions/lib/seed.data.ts@@ -865,7 +865,7 @@ export const fiscalYearSettings = {* Default period-close checklist (NetSuite-style). Seeded per company as system* task definitions; getPeriodCloseChecklist instantiates a periodCloseTask per* period from the active definitions. `autoCheckKey` binds Auto tasks to a- * readiness evaluator in accounting.service.ts (computePeriodReadiness).+ * readiness evaluator in accounting.ee.service.ts (computePeriodReadiness).*/export const periodCloseTaskDefinitions = [{@@ -947,6 +947,16 @@ export const periodCloseTaskDefinitions = [severity: null,active: true,isSystem: true+ },+ {+ name: "External GL sync complete",+ taskType: "Auto",+ autoCheckKey: "external-gl-sync",+ sortOrder: 9,+ required: true,+ severity: "Blocker",+ active: true,+ isSystem: true}];diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex b414c38e84..2c5476cb03 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -1641,6 +1641,360 @@ export type Database = {},]}+ accountingSyncOperation: {+ Row: {+ attemptCount: number+ companyId: string+ completedAt: string | null+ createdAt: string+ createdBy: string+ direction: string+ entityId: string+ entityType: string+ errorCode: string | null+ errorMessage: string | null+ externalId: string | null+ id: string+ idempotencyKey: string+ integration: string+ lastAttemptAt: string | null+ metadata: Json | null+ status: Database["public"]["Enums"]["syncOperationStatus"]+ trigger: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ attemptCount?: number+ companyId: string+ completedAt?: string | null+ createdAt?: string+ createdBy: string+ direction: string+ entityId: string+ entityType: string+ errorCode?: string | null+ errorMessage?: string | null+ externalId?: string | null+ id?: string+ idempotencyKey: string+ integration: string+ lastAttemptAt?: string | null+ metadata?: Json | null+ status?: Database["public"]["Enums"]["syncOperationStatus"]+ trigger: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ attemptCount?: number+ companyId?: string+ completedAt?: string | null+ createdAt?: string+ createdBy?: string+ direction?: string+ entityId?: string+ entityType?: string+ errorCode?: string | null+ errorMessage?: string | null+ externalId?: string | null+ id?: string+ idempotencyKey?: string+ integration?: string+ lastAttemptAt?: string | null+ metadata?: Json | null+ status?: Database["public"]["Enums"]["syncOperationStatus"]+ trigger?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "accountingSyncOperation_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingSyncOperation_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncOperation_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ accountingSyncTieOut: {+ Row: {+ accountId: string+ accountingPeriodId: string+ blockedAmount: number+ carbonPostedAmount: number+ companyId: string+ computedAt: string+ createdAt: string+ createdBy: string+ docBackedAmount: number+ excludedAmount: number+ externalDelta: number | null+ id: string+ integration: string+ internalDelta: number+ pendingAmount: number+ providerAmount: number | null+ syncedAmount: number+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ accountId: string+ accountingPeriodId: string+ blockedAmount?: number+ carbonPostedAmount?: number+ companyId: string+ computedAt?: string+ createdAt?: string+ createdBy: string+ docBackedAmount?: number+ excludedAmount?: number+ externalDelta?: number | null+ id?: string+ integration: string+ internalDelta?: number+ pendingAmount?: number+ providerAmount?: number | null+ syncedAmount?: number+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ accountId?: string+ accountingPeriodId?: string+ blockedAmount?: number+ carbonPostedAmount?: number+ companyId?: string+ computedAt?: string+ createdAt?: string+ createdBy?: string+ docBackedAmount?: number+ excludedAmount?: number+ externalDelta?: number | null+ id?: string+ integration?: string+ internalDelta?: number+ pendingAmount?: number+ providerAmount?: number | null+ syncedAmount?: number+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "accountingSyncTieOut_accountId_fkey"+ columns: ["accountId"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_accountId_fkey"+ columns: ["accountId"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_accountingPeriodId_fkey"+ columns: ["accountingPeriodId"]+ isOneToOne: false+ referencedRelation: "accountingPeriod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountingSyncTieOut_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }address: {Row: {addressLine1: string | null@@ -71392,6 +71746,13 @@ export type Database = {shipmentStateProvince: string | null}Relationships: [+ {+ foreignKeyName: "address_countryCode_fkey"+ columns: ["customerCountryCode"]+ isOneToOne: false+ referencedRelation: "country"+ referencedColumns: ["alpha2"]+ },{foreignKeyName: "address_countryCode_fkey"columns: ["shipmentCountryCode"]@@ -71401,7 +71762,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -78578,6 +78939,14 @@ export type Database = {| "Cancelled"supplierStatusType: "Active" | "Inactive" | "Pending" | "Rejected"supplySourceType: "Purchase Order" | "Production Order"+ syncOperationStatus:+ | "Pending"+ | "In Flight"+ | "Completed"+ | "Failed"+ | "Warning"+ | "Skipped"+ | "Excluded"tableViewType: "Public" | "Private"taxDepreciationMethod: "Straight Line" | "Declining Balance" | "MACRS"taxExemptionReason:@@ -79997,6 +80366,15 @@ export const Constants = {],supplierStatusType: ["Active", "Inactive", "Pending", "Rejected"],supplySourceType: ["Purchase Order", "Production Order"],+ syncOperationStatus: [+ "Pending",+ "In Flight",+ "Completed",+ "Failed",+ "Warning",+ "Skipped",+ "Excluded",+ ],tableViewType: ["Public", "Private"],taxDepreciationMethod: ["Straight Line", "Declining Balance", "MACRS"],taxExemptionReason: [diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.tsindex 808ce2e678..e214a4e2d9 100644--- a/packages/database/supabase/functions/seed-company/index.ts+++ b/packages/database/supabase/functions/seed-company/index.ts@@ -312,7 +312,7 @@ serve(async (req: Request) => {// period-close checklist definitions (system template rows). The table is// new on this branch and not yet in the cloud-generated Kysely types, so- // the insert goes through a cast (mirrors accounting.service.ts).+ // the insert goes through a cast (mirrors accounting.ee.service.ts).await (trx as any).insertInto("periodCloseTaskDefinition").values(diff --git a/packages/database/supabase/migrations/20260709142743_accounting-sync-operations.sql b/packages/database/supabase/migrations/20260709142743_accounting-sync-operations.sqlnew file mode 100644index 0000000000..24dd13b27a--- /dev/null+++ b/packages/database/supabase/migrations/20260709142743_accounting-sync-operations.sql@@ -0,0 +1,69 @@+-- Accounting sync engine v2: durable per-record sync-operation ledger+-- Spec: .ai/specs/2026-07-09-accounting-sync-engine.md (Phase A)++DO $$ BEGIN+ CREATE TYPE "syncOperationStatus" AS ENUM+ ('Pending', 'In Flight', 'Completed', 'Failed', 'Warning', 'Skipped');+EXCEPTION WHEN duplicate_object THEN NULL; END $$;++CREATE TABLE IF NOT EXISTS "accountingSyncOperation" (+ "id" TEXT NOT NULL DEFAULT id('syncop'),+ "companyId" TEXT NOT NULL,+ "integration" TEXT NOT NULL,+ "entityType" TEXT NOT NULL,+ "entityId" TEXT NOT NULL,+ "direction" TEXT NOT NULL CHECK ("direction" IN ('push-to-accounting','pull-from-accounting')),+ "trigger" TEXT NOT NULL CHECK ("trigger" IN ('event','webhook','backfill','manual','posting','retry')),+ "status" "syncOperationStatus" NOT NULL DEFAULT 'Pending',+ "idempotencyKey" TEXT NOT NULL,+ "attemptCount" INTEGER NOT NULL DEFAULT 0,+ "lastAttemptAt" TIMESTAMP WITH TIME ZONE,+ "completedAt" TIMESTAMP WITH TIME ZONE,+ "errorCode" TEXT,+ "errorMessage" TEXT,+ "externalId" TEXT,+ "metadata" JSONB,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ CONSTRAINT "accountingSyncOperation_pkey" PRIMARY KEY ("id", "companyId"),+ CONSTRAINT "accountingSyncOperation_companyId_fkey" FOREIGN KEY ("companyId")+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE+);++-- One live operation per record+direction+integration: re-triggers are absorbed+CREATE UNIQUE INDEX IF NOT EXISTS "accountingSyncOperation_live_uq"+ ON "accountingSyncOperation" ("companyId", "integration", "entityType", "entityId", "direction")+ WHERE "status" IN ('Pending', 'In Flight');+CREATE UNIQUE INDEX IF NOT EXISTS "accountingSyncOperation_idempotency_uq"+ ON "accountingSyncOperation" ("companyId", "integration", "idempotencyKey");+CREATE INDEX IF NOT EXISTS "accountingSyncOperation_inbox_idx"+ ON "accountingSyncOperation" ("companyId", "integration", "status", "updatedAt");+CREATE INDEX IF NOT EXISTS "accountingSyncOperation_companyId_idx"+ ON "accountingSyncOperation" ("companyId");+CREATE INDEX IF NOT EXISTS "accountingSyncOperation_createdBy_idx"+ ON "accountingSyncOperation" ("createdBy");+CREATE INDEX IF NOT EXISTS "accountingSyncOperation_updatedBy_idx"+ ON "accountingSyncOperation" ("updatedBy");++ALTER TABLE "accountingSyncOperation" ENABLE ROW LEVEL SECURITY;++DROP POLICY IF EXISTS "SELECT" ON "public"."accountingSyncOperation";+CREATE POLICY "SELECT" ON "public"."accountingSyncOperation" FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_role())::text[]+ )+);++DROP POLICY IF EXISTS "UPDATE" ON "public"."accountingSyncOperation";+CREATE POLICY "UPDATE" ON "public"."accountingSyncOperation" FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]+ )+);++-- No INSERT/DELETE policies: rows are created and removed by jobs via service role only.++-- Posting-sync trigger source: journal UPDATEs flow into the event system (PGMQ)+SELECT attach_event_trigger('journal', ARRAY[]::TEXT[], ARRAY[]::TEXT[]);diff --git a/packages/database/supabase/migrations/20260731073327_rillet-integration.sql b/packages/database/supabase/migrations/20260731073327_rillet-integration.sqlnew file mode 100644index 0000000000..baa710e15a--- /dev/null+++ b/packages/database/supabase/migrations/20260731073327_rillet-integration.sql@@ -0,0 +1,6 @@+-- Seed the Rillet integration registry row. companyIntegration.id has an FK+-- to integration.id (20240119095150_integrations.sql), so installing the+-- integration fails without this row.+INSERT INTO "integration" ("id", "jsonschema")+VALUES ('rillet', '{"type": "object", "properties": {}}'::json)+ON CONFLICT ("id") DO NOTHING;diff --git a/packages/database/supabase/migrations/20260802221004_sync-operation-excluded-status.sql b/packages/database/supabase/migrations/20260802221004_sync-operation-excluded-status.sqlnew file mode 100644index 0000000000..f3a83ebd50--- /dev/null+++ b/packages/database/supabase/migrations/20260802221004_sync-operation-excluded-status.sql@@ -0,0 +1,4 @@+-- Posting-sync dispositions (spec: .ai/specs/2026-08-02-accounting-sync-engine-v3.md):+-- 'Excluded' is the terminal status for journals the posting policy decides not to push+-- (doc-backed, family off, source type disabled). Distinct from 'Skipped' (human opt-out).+ALTER TYPE "syncOperationStatus" ADD VALUE IF NOT EXISTS 'Excluded';diff --git a/packages/database/supabase/migrations/20260807152238_payment-event-trigger.sql b/packages/database/supabase/migrations/20260807152238_payment-event-trigger.sqlnew file mode 100644index 0000000000..c07d905271--- /dev/null+++ b/packages/database/supabase/migrations/20260807152238_payment-event-trigger.sql@@ -0,0 +1,16 @@+-- Phase G — outbound payment write-back.+--+-- Attach the event-system trigger to the `payment` table so a Carbon-born+-- payment reaching Posted/Voided enqueues an outbound push operation (see+-- events/sync.ts → getPaymentPushDecision). Provider-recorded payments still+-- flow INTO Carbon via the Rillet webhook + pull sweep; the push syncer skips+-- those (their mapping marks them provider-owned), so this trigger does not+-- create a loop.+--+-- The per-company SYNC subscription for the `payment` table is created by the+-- Rillet install hook (rilletOnInstall, via createEventSystemSubscription) —+-- not backfilled here. Rillet is a new integration with no pre-existing installs+-- to patch, and the trigger is a cheap no-op until a matching subscription+-- exists. Idempotent: attach_event_trigger drops and recreates its triggers.++SELECT attach_event_trigger('payment', ARRAY[]::TEXT[], ARRAY[]::TEXT[]);diff --git a/packages/database/supabase/migrations/20260811223145_accounting-sync-tieout.sql b/packages/database/supabase/migrations/20260811223145_accounting-sync-tieout.sqlnew file mode 100644index 0000000000..51184aa1df--- /dev/null+++ b/packages/database/supabase/migrations/20260811223145_accounting-sync-tieout.sql@@ -0,0 +1,91 @@+-- Accounting sync tie-out (v3 spec §5 / v4 Pillar E):+--+-- 1) "accountingSyncTieOut" — one row per (integration × accounting period ×+-- account), written by the weekly accounting-reconciliation cron via the+-- service role. Per cell:+-- carbonPostedAmount = synced + docBacked + excluded + pending + blocked+-- (internal completeness), and+-- syncedAmount = providerAmount (external fidelity; NULL until fetched).+-- 2) Reconcile the "External GL sync complete" period-close auto-check into+-- every existing company's checklist (new companies get it from+-- seed.data.ts).+--+-- Every statement is idempotent (IF NOT EXISTS / DROP POLICY IF EXISTS /+-- ON CONFLICT DO NOTHING) so the deploy runner can safely re-run the whole+-- file over a committed partial state.++CREATE TABLE IF NOT EXISTS "accountingSyncTieOut" (+ "id" TEXT NOT NULL DEFAULT id('tieout'),+ "companyId" TEXT NOT NULL,+ "integration" TEXT NOT NULL,+ "accountingPeriodId" TEXT NOT NULL,+ "accountId" TEXT NOT NULL,++ -- Net debit-signed sums per cell+ "carbonPostedAmount" NUMERIC NOT NULL DEFAULT 0,+ "syncedAmount" NUMERIC NOT NULL DEFAULT 0,+ "docBackedAmount" NUMERIC NOT NULL DEFAULT 0,+ "excludedAmount" NUMERIC NOT NULL DEFAULT 0,+ "pendingAmount" NUMERIC NOT NULL DEFAULT 0,+ "blockedAmount" NUMERIC NOT NULL DEFAULT 0,+ "providerAmount" NUMERIC, -- NULL until the provider fetch succeeds+ "internalDelta" NUMERIC NOT NULL DEFAULT 0, -- carbonPosted − (synced+docBacked+excluded+pending+blocked)+ "externalDelta" NUMERIC, -- synced − provider (NULL when providerAmount is NULL)+ "computedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "accountingSyncTieOut_pkey" PRIMARY KEY ("id", "companyId"),+ CONSTRAINT "accountingSyncTieOut_companyId_fkey" FOREIGN KEY ("companyId")+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ -- "accountingPeriod" has a SINGLE-column PK ("id"), so this is a+ -- single-column FK — same as periodCloseTask (20260702044133). A composite+ -- ("accountingPeriodId","companyId") FK would be invalid.+ CONSTRAINT "accountingSyncTieOut_accountingPeriodId_fkey" FOREIGN KEY ("accountingPeriodId")+ REFERENCES "accountingPeriod"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ -- "account" also has a single-column PK ("id")+ CONSTRAINT "accountingSyncTieOut_accountId_fkey" FOREIGN KEY ("accountId")+ REFERENCES "account"("id")+);++-- Latest-per-cell upsert target+-- (onConflict: "companyId,integration,accountingPeriodId,accountId")+CREATE UNIQUE INDEX IF NOT EXISTS "accountingSyncTieOut_cell_uq"+ ON "accountingSyncTieOut" ("companyId", "integration", "accountingPeriodId", "accountId");+CREATE INDEX IF NOT EXISTS "accountingSyncTieOut_period_idx"+ ON "accountingSyncTieOut" ("companyId", "integration", "accountingPeriodId");++CREATE INDEX IF NOT EXISTS "accountingSyncTieOut_companyId_idx" ON "accountingSyncTieOut" ("companyId");+CREATE INDEX IF NOT EXISTS "accountingSyncTieOut_accountingPeriodId_idx" ON "accountingSyncTieOut" ("accountingPeriodId");+CREATE INDEX IF NOT EXISTS "accountingSyncTieOut_accountId_idx" ON "accountingSyncTieOut" ("accountId");+CREATE INDEX IF NOT EXISTS "accountingSyncTieOut_createdBy_idx" ON "accountingSyncTieOut" ("createdBy");++-- RLS: controllers read tie-outs under accounting_view; NO insert/update/+-- delete policies — rows are written only by the reconciliation job through+-- the service role.+ALTER TABLE "public"."accountingSyncTieOut" ENABLE ROW LEVEL SECURITY;++DROP POLICY IF EXISTS "SELECT" ON "public"."accountingSyncTieOut";+CREATE POLICY "SELECT" ON "public"."accountingSyncTieOut"+ FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_view'))::text[])+ );++-- ==========================================================================+-- Reconcile the period-close checklist for EXISTING companies: add the+-- "External GL sync complete" Auto check (the v3 §5 close gate) after the+-- seeded 8-task set. Idempotent via the (companyId, name) unique key — a+-- targeted add, never a wipe-and-reseed. New companies are covered by+-- seed.data.ts (periodCloseTaskDefinitions).+-- ==========================================================================++INSERT INTO "periodCloseTaskDefinition"+ ("companyId", "name", "taskType", "autoCheckKey", "sortOrder", "required", "severity", "active", "isSystem", "createdBy")+SELECT+ c."id", 'External GL sync complete', 'Auto', 'external-gl-sync', 9, true, 'Blocker', true, true, 'system'+FROM "company" c+WHERE EXISTS (SELECT 1 FROM "user" u WHERE u."id" = 'system')+ON CONFLICT ("companyId", "name") DO NOTHING;diff --git a/packages/database/supabase/migrations/20260811224732_scoped-sync-trigger-suppression.sql b/packages/database/supabase/migrations/20260811224732_scoped-sync-trigger-suppression.sqlnew file mode 100644index 0000000000..f25658f9ae--- /dev/null+++ b/packages/database/supabase/migrations/20260811224732_scoped-sync-trigger-suppression.sql@@ -0,0 +1,197 @@+-- Scoped sync-trigger suppression (v4 spec, Pillar G / F13).+--+-- `withTriggersDisabled` sets the txn-local GUC `app.sync_in_progress = 'true'`+-- while the accounting sync engine writes to the database. Previously+-- dispatch_event_batch() returned immediately when that GUC was set, so a sync+-- transaction emitted NO events for ANY handler type. That blanket suppression+-- is now scoped to only the loop/echo-prone handler types:+--+-- - SYNC: the loop the GUC exists to break (sync write -> event -> sync).+-- - WEBHOOK: echoes the customer's own accounting pull back to their systems.+-- - WORKFLOW: can ping-pong with the provider (sync write -> workflow ->+-- entity edit -> push -> webhook -> pull -> workflow ...).+--+-- SEARCH / AUDIT / EMBEDDING are idempotent observers and now see sync-written+-- rows (previously silently suppressed — v4 spec F13).+--+-- Forked verbatim from 20260810100000_workflows-run-tag.sql with exactly that+-- one behavioral change: the top-of-function early return is replaced by a+-- per-subscription handlerType predicate in both the has_subs EXISTS check and+-- the subscription loop.++CREATE OR REPLACE FUNCTION public.dispatch_event_batch()+RETURNS TRIGGER+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public, pgmq, extensions+AS $$+DECLARE+ sub RECORD;+ msg_batch JSONB[];+ rec_company_id TEXT;+ has_subs BOOLEAN;+ current_actor_id TEXT;+ current_workflow_run_id TEXT;+ pk_column TEXT;+ pk_join TEXT;+ query_text TEXT;+ did_enqueue BOOLEAN := FALSE;+BEGIN+ current_actor_id := auth.uid()::TEXT;+ current_workflow_run_id :=+ (nullif(current_setting('request.jwt.claims', true), '')::jsonb)->>'workflow_run_id';+ pk_column := public.get_primary_key_column(TG_TABLE_NAME);++ -- Pair UPDATE rows on the full key: single-column pairing cross-joins rows+ -- on tables with composite identity.+ SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')+ INTO pk_join+ FROM unnest(public.get_primary_key_columns(TG_TABLE_NAME)) AS col;++ IF TG_OP = 'DELETE' THEN+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;+ ELSIF TG_OP = 'INSERT' THEN+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;+ ELSE+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;+ END IF;++ IF rec_company_id IS NULL THEN RETURN NULL; END IF;++ SELECT EXISTS (+ SELECT 1 FROM "eventSystemSubscription"+ WHERE "table" = TG_TABLE_NAME+ AND "companyId" = rec_company_id+ AND "active" = TRUE+ AND TG_OP = ANY("operations")+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')+ ) INTO has_subs;++ IF NOT has_subs THEN RETURN NULL; END IF;++ FOR sub IN+ SELECT * FROM "eventSystemSubscription"+ WHERE "table" = TG_TABLE_NAME+ AND "companyId" = rec_company_id+ AND "active" = TRUE+ AND TG_OP = ANY("operations")+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')+ LOOP++ IF TG_OP = 'INSERT' THEN+ query_text := format('+ SELECT array_agg(+ jsonb_build_object(+ ''subscriptionId'', $1,+ ''triggerType'', $2,+ ''handlerType'', $3,+ ''handlerConfig'', $4,+ ''companyId'', $5,+ ''actorId'', $6,+ ''workflowRunId'', $10,+ ''event'', jsonb_build_object(+ ''table'', $7,+ ''operation'', $8,+ ''recordId'', t.%I::TEXT,+ ''new'', row_to_json(t)::jsonb,+ ''old'', null,+ ''timestamp'', clock_timestamp()+ )+ )+ )+ FROM batched_new t+ WHERE t."companyId" = $5+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)+ ', pk_column);++ EXECUTE query_text INTO msg_batch+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,+ current_workflow_run_id;++ ELSIF TG_OP = 'DELETE' THEN+ query_text := format('+ SELECT array_agg(+ jsonb_build_object(+ ''subscriptionId'', $1,+ ''triggerType'', $2,+ ''handlerType'', $3,+ ''handlerConfig'', $4,+ ''companyId'', $5,+ ''actorId'', $6,+ ''workflowRunId'', $10,+ ''event'', jsonb_build_object(+ ''table'', $7,+ ''operation'', $8,+ ''recordId'', t.%I::TEXT,+ ''new'', null,+ ''old'', row_to_json(t)::jsonb,+ ''timestamp'', clock_timestamp()+ )+ )+ )+ FROM batched_old t+ WHERE t."companyId" = $5+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)+ ', pk_column);++ EXECUTE query_text INTO msg_batch+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,+ current_workflow_run_id;++ ELSIF TG_OP = 'UPDATE' THEN+ query_text := format('+ SELECT array_agg(+ jsonb_build_object(+ ''subscriptionId'', $1,+ ''triggerType'', $2,+ ''handlerType'', $3,+ ''handlerConfig'', $4,+ ''companyId'', $5,+ ''actorId'', $6,+ ''workflowRunId'', $10,+ ''event'', jsonb_build_object(+ ''table'', $7,+ ''operation'', $8,+ ''recordId'', n.%I::TEXT,+ ''new'', row_to_json(n)::jsonb,+ ''old'', row_to_json(o)::jsonb,+ ''timestamp'', clock_timestamp()+ )+ )+ )+ FROM batched_new n+ JOIN batched_old o ON %s+ WHERE n."companyId" = $5+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)+ ', pk_column, pk_join);++ EXECUTE query_text INTO msg_batch+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,+ current_workflow_run_id;+ END IF;++ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN+ PERFORM pgmq.send_batch('event_system', msg_batch);+ did_enqueue := TRUE;+ END IF;++ END LOOP;++ -- Wake the Inngest drainer once per transaction: the GUC is txn-local, so a+ -- bulk import posts a single doorbell instead of one per statement.+ IF did_enqueue+ AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN+ PERFORM util.wake_event_queue();+ PERFORM set_config('carbon.event_wake_sent', 'true', true);+ END IF;++ RETURN NULL;+END;+$$;++COMMENT ON FUNCTION public.dispatch_event_batch() IS 'Dispatches database events to PGMQ and wakes the Inngest drainer via wake_event_queue() (once per transaction). Uses clock_timestamp() so each event has a unique microsecond timestamp even when batched. Stamps workflowRunId from the workflow_run_id JWT claim so workflow-made writes are distinguishable. During sync writes (app.sync_in_progress = true) only SYNC/WEBHOOK/WORKFLOW subscriptions are suppressed (loop/echo break); SEARCH/AUDIT/EMBEDDING observers still see sync-written rows.';diff --git a/packages/database/supabase/migrations/20260812093418_sync-operation-reconcile-trigger.sql b/packages/database/supabase/migrations/20260812093418_sync-operation-reconcile-trigger.sqlnew file mode 100644index 0000000000..bc3e429024--- /dev/null+++ b/packages/database/supabase/migrations/20260812093418_sync-operation-reconcile-trigger.sql@@ -0,0 +1,9 @@+-- v5 reconciler unification (.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md):+-- operations enqueued by the unified reconcile path carry trigger 'reconcile'+-- (state-derived — never cooldown-gated, distinct from the event/webhook+-- machine triggers in Sync Activity). Widen the CHECK constraint.+ALTER TABLE "accountingSyncOperation"+ DROP CONSTRAINT IF EXISTS "accountingSyncOperation_trigger_check";+ALTER TABLE "accountingSyncOperation"+ ADD CONSTRAINT "accountingSyncOperation_trigger_check"+ CHECK ("trigger" IN ('event','webhook','backfill','manual','posting','retry','reconcile'));diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.mdindex d972b46d67..3b032bf82d 100644--- a/packages/ee/AGENTS.md+++ b/packages/ee/AGENTS.md@@ -1,6 +1,6 @@# @carbon/ee-Enterprise edition — integrations registry, accounting sync (Xero), plan gating, exchange rates, Slack, email, Jira, Linear, Onshape, and storage rules.+Enterprise edition — integrations registry, accounting sync (Xero, QuickBooks Online, Rillet), plan gating, exchange rates, Slack, email, Jira, Linear, Onshape, and storage rules.## Always@@ -8,7 +8,7 @@ Enterprise edition — integrations registry, accounting sync (Xero), plan gatin- **Use `FEATURE_PLANS` as the single source of truth for plan gating** — both client (`usePlanGate`) and server (`plan.server.ts`) read from it- **All external ID linking goes through `externalIntegrationMapping` table** — use `createMappingService()`, not per-entity `externalId` columns (deprecated)- **Gating is a no-op off Cloud** — `companyHasPlan`/`requirePlan` short-circuit true when `CarbonEdition !== Edition.Cloud` or company is bypass-listed-- **Register server hooks in `hooks.server.ts`** — integration lifecycle hooks (healthcheck, install, uninstall) that need server-only imports go here, not in config files+- **Register server hooks in `hooks.server.ts`** — integration lifecycle hooks (healthcheck, install, update, uninstall) that need server-only imports go here, not in config files. `onUpdate` fires on every settings save of an installed integration; the accounting providers use it to re-converge event subscriptions (QBO's hooks are real now — install/update converge, uninstall cleans up)## Ask First@@ -31,11 +31,15 @@ pnpm --filter @carbon/ee typecheck # tsgo --noEmit## Key Patterns-- **Accounting sync**: class-per-entity syncers in `accounting/providers/xero/entities/`; `SyncFactory.getSyncer()` dispatches-- **60s cooldown**: `SYNC_COOLDOWN_MS` skips recently-synced entities+- **Accounting sync**: class-per-entity syncers in `accounting/providers/{xero,quickbooks-online,rillet}/entities/`; `SyncFactory.getSyncer()` dispatches+- **Subscriptions are code-derived**: `accounting/core/subscriptions.ts` — `REQUIRED_SYNC_SUBSCRIPTIONS` + idempotent `ensureProviderSubscriptions()` (exported from `./accounting`), converged from the install/`onUpdate` hooks and the outbound sweep — never a write-once install artifact, never a migration backfill+- **60s cooldown**: `SYNC_OPERATION_COOLDOWN_MS` (`accounting/core/operations.ts`) — a just-Completed ledger op absorbs `event`/`webhook` re-enqueues for 60s. Status-transition events bypass it via the non-cooldown `posting` trigger: a state change is never dropped by the cooldown+- **Truthful ledger**: a drain no-op with no remote copy closes `Skipped` via `skipOperation()` (reason in `errorMessage`), never `Completed`; `Skipped → Pending` retry is allowed+- **Rillet idempotency keys are entity-scoped**: `buildRilletIdempotencyKey({companyId, operation, localId})` — the payload is deliberately NOT hashed, so a crash-retry with a drifted payload cannot double-create the remote document+- **Tie-out remote reads**: `accounting/core/remote-journal.ts` `fetchRemoteJournalTotals()` — provider-agnostic debit-signed per-account journal totals for the reconciliation tie-out- **Dependency sync**: transaction syncers use `ensureDependencySynced()` for JIT deps (e.g. push customer before invoice)- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions-- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./exchange-rates.server`, `./slack.server`, `./hooks.server`, `./jira`, `./linear`, `./xero`, etc.+- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./exchange-rates.server`, `./slack.server`, `./hooks.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, etc.## Cross-Referencesdiff --git a/packages/ee/package.json b/packages/ee/package.jsonindex 743b244ec4..4bf2295037 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -21,7 +21,8 @@"./slack.server": "./src/slack.server.ts","./slack/messages": "./src/slack/lib/messages.ts","./hooks.server": "./src/hooks.server.ts",- "./xero": "./src/accounting/providers/xero.ts",+ "./quickbooks/hooks.server": "./src/quickbooks/hooks.server.ts",+ "./rillet/hooks.server": "./src/rillet/hooks.server.ts","./xero/hooks.server": "./src/xero/hooks.server.ts"},"private": true,@@ -67,6 +68,8 @@},"devDependencies": {"@carbon/config": "workspace:*",+ "@logtape/logtape": "catalog:",+ "@logtape/testing": "catalog:","@types/nodemailer": "6.4.21","@types/react": "catalog:","typescript": "catalog:",diff --git a/packages/ee/src/accounting/core/account-mapping-ai.test.ts b/packages/ee/src/accounting/core/account-mapping-ai.test.tsnew file mode 100644index 0000000000..6302483bc0--- /dev/null+++ b/packages/ee/src/accounting/core/account-mapping-ai.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from "vitest";+import { buildAiAccountProposals } from "./account-mapping-ai";++const accounts = [+ { id: "acc-ar", number: "1200", name: "Accounts Receivable" },+ { id: "acc-sales", number: "4000", name: "Sales Revenue" },+ { id: "acc-no-number", number: null, name: "Rounding" }+];++const providerAccounts = [+ { id: "p-ar", code: "1200", name: "Trade Debtors" },+ { id: "p-sales", code: "200", name: "Sales" },+ { id: "p-nameless", code: "999", name: null }+];++describe("buildAiAccountProposals", () => {+ it("resolves provider code/name from the provider account", () => {+ const proposals = buildAiAccountProposals({+ matches: [+ { accountId: "acc-ar", externalId: "p-ar" },+ { accountId: "acc-sales", externalId: "p-sales" }+ ],+ accounts,+ providerAccounts+ });++ expect(proposals).toEqual([+ {+ accountId: "acc-ar",+ accountNumber: "1200",+ accountName: "Accounts Receivable",+ externalId: "p-ar",+ externalCode: "1200",+ externalName: "Trade Debtors"+ },+ {+ accountId: "acc-sales",+ accountNumber: "4000",+ accountName: "Sales Revenue",+ externalId: "p-sales",+ externalCode: "200",+ externalName: "Sales"+ }+ ]);+ });++ it("drops matches with an empty externalId (no confident match)", () => {+ const proposals = buildAiAccountProposals({+ matches: [{ accountId: "acc-ar", externalId: "" }],+ accounts,+ providerAccounts+ });++ expect(proposals).toEqual([]);+ });++ it("drops hallucinated account or provider ids", () => {+ const proposals = buildAiAccountProposals({+ matches: [+ { accountId: "acc-ghost", externalId: "p-ar" },+ { accountId: "acc-ar", externalId: "p-ghost" }+ ],+ accounts,+ providerAccounts+ });++ expect(proposals).toEqual([]);+ });++ it("keeps only the first proposal per Carbon account", () => {+ const proposals = buildAiAccountProposals({+ matches: [+ { accountId: "acc-ar", externalId: "p-ar" },+ { accountId: "acc-ar", externalId: "p-sales" }+ ],+ accounts,+ providerAccounts+ });++ expect(proposals).toHaveLength(1);+ expect(proposals[0]?.externalId).toBe("p-ar");+ });++ it("falls back to empty number and null name when absent", () => {+ const proposals = buildAiAccountProposals({+ matches: [{ accountId: "acc-no-number", externalId: "p-nameless" }],+ accounts,+ providerAccounts+ });++ expect(proposals[0]).toEqual({+ accountId: "acc-no-number",+ accountNumber: "",+ accountName: "Rounding",+ externalId: "p-nameless",+ externalCode: "999",+ externalName: null+ });+ });+});diff --git a/packages/ee/src/accounting/core/account-mapping-ai.ts b/packages/ee/src/accounting/core/account-mapping-ai.tsnew file mode 100644index 0000000000..fadd5a2dfc--- /dev/null+++ b/packages/ee/src/accounting/core/account-mapping-ai.ts@@ -0,0 +1,144 @@+import { openai } from "@ai-sdk/openai";+import { getLogger } from "@carbon/logger";+import { openAiCategorizationModel } from "@carbon/utils";+import { generateObject } from "ai";+import { z } from "zod";+import type {+ AccountMatchProposal,+ ProviderChartAccount+} from "./account-mapping";++/**+ * LLM-assisted account matching. Given the Carbon accounts still awaiting a+ * provider mapping and the provider's chart of accounts, ask gpt-4o for a+ * best-guess pairing so the user isn't mapping every row by hand.+ *+ * Deliberately a pure function over already-loaded lists (no DB access): the+ * route passes the unmapped Carbon accounts and the provider chart it already+ * fetched for the Account Mapping tab. Nothing is written here — the returned+ * proposals are reviewed and confirmed through the same+ * `bulk-upsert-account-mappings` path the Match-by-code drawer uses.+ *+ * Best-effort: any failure (missing API key, model error, malformed output)+ * resolves to an empty proposal list with the error surfaced, never throws.+ */++const logger = getLogger("ee", "account-mapping-ai");++const aiMatchSchema = z.object({+ matches: z+ .array(+ z.object({+ accountId: z+ .string()+ .describe("The id of the Carbon account being mapped"),+ externalId: z+ .string()+ .describe(+ "The id of the provider account that best matches, or an empty string if none is a confident match"+ )+ })+ )+ .describe("One entry per Carbon account you can confidently match")+});++export async function suggestAccountMatchesWithAI(args: {+ accounts: Array<{ id: string; number: string | null; name: string }>;+ providerAccounts: ProviderChartAccount[];+}): Promise<{ data: AccountMatchProposal[] | null; error: string | null }> {+ const { accounts, providerAccounts } = args;++ if (accounts.length === 0 || providerAccounts.length === 0) {+ return { data: [], error: null };+ }++ try {+ const carbonList = accounts+ .map(+ (account) =>+ `${account.id} | ${account.number ?? "(no number)"} | ${account.name}`+ )+ .join("\n");++ const providerList = providerAccounts+ .map(+ (account) =>+ `${account.id} | ${account.code ?? "(no code)"} | ${account.name ?? "(no name)"}`+ )+ .join("\n");++ const { object } = await generateObject({+ model: openai(openAiCategorizationModel),+ schema: aiMatchSchema,+ prompt: `You are mapping a manufacturing ERP's general-ledger accounts to an external accounting system's chart of accounts. For each Carbon account, pick the single best matching provider account.++Match on the account's purpose — use the account number/code and name. A close number match is a strong signal, but the name's meaning matters most (e.g. "Accounts Receivable" should map to the provider's receivables account even if the numbers differ). Only return a match when you are reasonably confident; if no provider account is a good fit, return an empty string for externalId. Never invent ids — every id you return must come verbatim from the lists below.++Each row is formatted as: id | number/code | name++Carbon accounts to map:+${carbonList}++Provider chart of accounts:+${providerList}`,+ temperature: 0.2+ });++ const proposals = buildAiAccountProposals({+ matches: object.matches,+ accounts,+ providerAccounts+ });++ return { data: proposals, error: null };+ } catch (err) {+ const error = err instanceof Error ? err.message : String(err);+ logger.error("Failed to suggest account matches with AI", { error });+ return { data: null, error };+ }+}++/**+ * Turn the model's raw {accountId, externalId} guesses into confirmable+ * proposals. Pure so it can be unit-tested without the LLM. Guards:+ * - drops empty externalId (the model's "no confident match" signal)+ * - drops hallucinated ids not present in the inputs+ * - one proposal per Carbon account (first guess wins)+ * externalCode/externalName are resolved from the provider account so the+ * confirm step stores the same display metadata the manual path does.+ */+export function buildAiAccountProposals(args: {+ matches: Array<{ accountId: string; externalId: string }>;+ accounts: Array<{ id: string; number: string | null; name: string }>;+ providerAccounts: ProviderChartAccount[];+}): AccountMatchProposal[] {+ const accountById = new Map(+ args.accounts.map((account) => [account.id, account])+ );+ const providerById = new Map(+ args.providerAccounts.map((account) => [account.id, account])+ );++ const proposals: AccountMatchProposal[] = [];+ const usedAccountIds = new Set<string>();++ for (const match of args.matches) {+ if (!match.externalId) continue;+ const account = accountById.get(match.accountId);+ const provider = providerById.get(match.externalId);+ if (!account || !provider) continue;+ if (usedAccountIds.has(account.id)) continue;+ usedAccountIds.add(account.id);++ proposals.push({+ accountId: account.id,+ accountNumber: account.number ?? "",+ accountName: account.name,+ externalId: provider.id,+ externalCode: provider.code ?? "",+ externalName: provider.name ?? null+ });+ }++ return proposals;+}diff --git a/packages/ee/src/accounting/core/account-mapping.test.ts b/packages/ee/src/accounting/core/account-mapping.test.tsnew file mode 100644index 0000000000..a81064b78b--- /dev/null+++ b/packages/ee/src/accounting/core/account-mapping.test.ts@@ -0,0 +1,221 @@+import { describe, expect, it } from "vitest";+import {+ buildAccountMappingMetadata,+ collectAccountDefaultAccountIds,+ getAccountMappingDisplayMetadata,+ proposeAccountMatchesByCode+} from "./account-mapping";++describe("collectAccountDefaultAccountIds", () => {+ it("collects ids from *Account and *AccountId columns only", () => {+ const ids = collectAccountDefaultAccountIds({+ companyId: "company-1",+ updatedBy: "user-1",+ salesAccount: "acc-sales",+ inventoryAccount: "acc-inventory",+ receivablesAccount: "acc-ar",+ deferredTaxExpenseAccountId: "acc-deferred-tax",+ intercompanyReceivablesAccount: null+ });++ expect(ids.sort()).toEqual([+ "acc-ar",+ "acc-deferred-tax",+ "acc-inventory",+ "acc-sales"+ ]);+ // Non-account columns are never collected+ expect(ids).not.toContain("company-1");+ expect(ids).not.toContain("user-1");+ });++ it("dedupes when several defaults point at the same account", () => {+ const ids = collectAccountDefaultAccountIds({+ salesAccount: "acc-1",+ salesDiscountAccount: "acc-1",+ roundingAccount: "acc-2"+ });++ expect(ids.sort()).toEqual(["acc-1", "acc-2"]);+ });++ it("skips null and empty values and handles a missing row", () => {+ expect(+ collectAccountDefaultAccountIds({+ salesAccount: null,+ inventoryAccount: "",+ payablesAccount: "acc-ap"+ })+ ).toEqual(["acc-ap"]);+ expect(collectAccountDefaultAccountIds(null)).toEqual([]);+ expect(collectAccountDefaultAccountIds(undefined)).toEqual([]);+ });+});++describe("buildAccountMappingMetadata", () => {+ it("shapes provided fields into metadata", () => {+ expect(+ buildAccountMappingMetadata({+ externalCode: "200",+ externalName: "Sales"+ })+ ).toEqual({ externalCode: "200", externalName: "Sales" });+ expect(buildAccountMappingMetadata({ externalCode: "200" })).toEqual({+ externalCode: "200"+ });+ expect(buildAccountMappingMetadata({ externalName: "Sales" })).toEqual({+ externalName: "Sales"+ });+ });++ it("returns undefined when neither field is provided", () => {+ expect(buildAccountMappingMetadata({})).toBeUndefined();+ expect(+ buildAccountMappingMetadata({ externalCode: undefined })+ ).toBeUndefined();+ });+});++describe("getAccountMappingDisplayMetadata", () => {+ it("round-trips metadata written by buildAccountMappingMetadata", () => {+ const metadata = buildAccountMappingMetadata({+ externalCode: "200",+ externalName: "Sales"+ });++ expect(getAccountMappingDisplayMetadata(metadata)).toEqual({+ externalCode: "200",+ externalName: "Sales"+ });+ });++ it("returns nulls for missing or malformed metadata", () => {+ expect(getAccountMappingDisplayMetadata(null)).toEqual({+ externalCode: null,+ externalName: null+ });+ expect(getAccountMappingDisplayMetadata(undefined)).toEqual({+ externalCode: null,+ externalName: null+ });+ expect(getAccountMappingDisplayMetadata("garbage")).toEqual({+ externalCode: null,+ externalName: null+ });+ expect(getAccountMappingDisplayMetadata([1, 2])).toEqual({+ externalCode: null,+ externalName: null+ });+ expect(+ getAccountMappingDisplayMetadata({ externalCode: 200, externalName: {} })+ ).toEqual({ externalCode: null, externalName: null });+ });+});++describe("proposeAccountMatchesByCode", () => {+ const accounts = [+ { id: "acc-1", number: "1210", name: "Inventory" },+ { id: "acc-2", number: "4010", name: "Sales" },+ { id: "acc-3", number: "5010", name: "Cost of Goods Sold - Direct" }+ ];++ it("proposes exact number-to-code matches only", () => {+ const proposals = proposeAccountMatchesByCode({+ accounts,+ providerAccounts: [+ { id: "xero-1", code: "1210", name: "Inventory Asset" },+ { id: "xero-2", code: "4010 ", name: "Sales" }, // trailing space: not exact+ { id: "xero-3", code: "501", name: "COGS" } // prefix: not exact+ ]+ });++ expect(proposals).toEqual([+ {+ accountId: "acc-1",+ accountNumber: "1210",+ accountName: "Inventory",+ externalId: "xero-1",+ externalCode: "1210",+ externalName: "Inventory Asset"+ }+ ]);+ });++ it("proposes nothing when no code matches", () => {+ const proposals = proposeAccountMatchesByCode({+ accounts,+ providerAccounts: [{ id: "xero-1", code: "9999", name: "Other" }]+ });++ expect(proposals).toEqual([]);+ });++ it("skips Carbon accounts sharing a duplicate number", () => {+ const proposals = proposeAccountMatchesByCode({+ accounts: [+ { id: "acc-1", number: "1210", name: "Inventory A" },+ { id: "acc-2", number: "1210", name: "Inventory B" },+ { id: "acc-3", number: "4010", name: "Sales" }+ ],+ providerAccounts: [+ { id: "xero-1", code: "1210", name: "Inventory" },+ { id: "xero-2", code: "4010", name: "Sales" }+ ]+ });++ expect(proposals.map((p) => p.accountId)).toEqual(["acc-3"]);+ });++ it("skips provider codes offered by more than one provider account", () => {+ const proposals = proposeAccountMatchesByCode({+ accounts,+ providerAccounts: [+ { id: "xero-1", code: "1210", name: "Inventory A" },+ { id: "xero-2", code: "1210", name: "Inventory B" },+ { id: "xero-3", code: "4010", name: "Sales" }+ ]+ });++ expect(proposals.map((p) => p.externalId)).toEqual(["xero-3"]);+ });++ it("skips already-mapped accounts and already-used provider accounts", () => {+ const proposals = proposeAccountMatchesByCode({+ accounts,+ providerAccounts: [+ { id: "xero-1", code: "1210", name: "Inventory" },+ { id: "xero-2", code: "4010", name: "Sales" },+ { id: "xero-3", code: "5010", name: "COGS" }+ ],+ mappedAccountIds: ["acc-1"],+ mappedExternalIds: ["xero-2"]+ });++ expect(proposals.map((p) => p.accountId)).toEqual(["acc-3"]);+ });++ it("skips unnumbered accounts and uncoded provider accounts", () => {+ const proposals = proposeAccountMatchesByCode({+ accounts: [+ { id: "acc-1", number: null, name: "Group Header" },+ { id: "acc-2", number: "4010", name: "Sales" }+ ],+ providerAccounts: [+ { id: "xero-1", code: null, name: "Uncoded" },+ { id: "xero-2", name: "No code at all" },+ { id: "xero-3", code: "4010", name: "Sales" }+ ]+ });++ expect(proposals).toEqual([+ {+ accountId: "acc-2",+ accountNumber: "4010",+ accountName: "Sales",+ externalId: "xero-3",+ externalCode: "4010",+ externalName: "Sales"+ }+ ]);+ });+});diff --git a/packages/ee/src/accounting/core/account-mapping.ts b/packages/ee/src/accounting/core/account-mapping.tsnew file mode 100644index 0000000000..0013addd63--- /dev/null+++ b/packages/ee/src/accounting/core/account-mapping.ts@@ -0,0 +1,486 @@+import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";+import type z from "zod";+import type { ExternalIntegrationMapping } from "./external-mapping";+import { createMappingService } from "./external-mapping";+import type {+ ProviderChartAccountSchema,+ UpsertAccountMappingSchema+} from "./models";++/**+ * Account-mapping service: thin wrappers over+ * ExternalIntegrationMappingService with entityType = "account", linking+ * Carbon GL accounts to the provider's chart of accounts.+ *+ * The Carbon side of a mapping is always account.id — never the account+ * number. account.number is only ever compared against the provider-side+ * code in matchAccountsByCode (external-code matching is the documented+ * legitimate use of numbers).+ */++export const ACCOUNT_MAPPING_ENTITY_TYPE = "account";++export type ProviderChartAccount = z.infer<typeof ProviderChartAccountSchema>;+export type UpsertAccountMappingInput = z.infer<+ typeof UpsertAccountMappingSchema+>;++type Db = Kysely<KyselyDatabase> | KyselyTx;++/**+ * An account mapping row joined with the Carbon account for display.+ * accountNumber/accountName are null when the mapped account no longer+ * exists (or has no number).+ */+export interface AccountMapping {+ id: string;+ accountId: string;+ accountNumber: string | null;+ accountName: string | null;+ externalId: string | null;+ externalCode: string | null;+ externalName: string | null;+ lastSyncedAt: string | null;+ metadata: Record<string, unknown> | null;+}++/**+ * A Carbon account referenced by an accountDefault column that has no mapping+ * for the integration yet. Automated (synced) postings always run through an+ * accountDefault account, so this is the complete set that needs mapping —+ * accounts seen only on historical/manual journal lines are intentionally+ * excluded (they never sync).+ */+export interface UnmappedPostingAccount {+ id: string;+ number: string | null;+ name: string;+}++/**+ * A proposed (not written) match between a Carbon account and a provider+ * account. The UI confirms proposals and calls upsertAccountMapping.+ */+export interface AccountMatchProposal {+ accountId: string;+ accountNumber: string;+ accountName: string;+ externalId: string;+ externalCode: string;+ externalName: string | null;+}++function toErrorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++async function getCompanyGroupId(+ db: Db,+ companyId: string+): Promise<string | null> {+ const company = await db+ .selectFrom("company")+ .select("companyGroupId")+ .where("id", "=", companyId)+ .executeTakeFirst();++ return company?.companyGroupId ?? null;+}++/**+ * Compile-time totality guard for collectAccountDefaultAccountIds: every+ * column of the generated accountDefault Row type except the two+ * non-account columns must match the /Account(Id)?$/ suffix the collector+ * relies on. A future default-account column named differently fails+ * typecheck here instead of silently escaping the required mapping set.+ * (Spec Appendix: .ai/specs/2026-08-02-accounting-sync-engine-v3.md.)+ */+type AccountDefaultRow = Database["public"]["Tables"]["accountDefault"]["Row"];+type AccountDefaultNonAccountColumns = "companyId" | "updatedBy";+type AccountDefaultAccountColumns = Exclude<+ keyof AccountDefaultRow,+ AccountDefaultNonAccountColumns+>;+type AssertAccountSuffix<T extends `${string}Account` | `${string}AccountId`> =+ T;+// biome-ignore lint/correctness/noUnusedVariables: compile-time assertion+type _accountDefaultColumnsAllMatchCollectorPattern =+ AssertAccountSuffix<AccountDefaultAccountColumns>;++/**+ * Every account reference on the accountDefault row lives in a column+ * ending in "Account" (or "AccountId" for the deferred-tax pair), and since+ * the chart-of-accounts reset every one of them stores an account.id FK.+ * Collects the distinct non-empty ids; robust to future column additions.+ */+export function collectAccountDefaultAccountIds(+ row: Record<string, unknown> | null | undefined+): string[] {+ if (!row) return [];++ const ids = new Set<string>();+ for (const [column, value] of Object.entries(row)) {+ if (!/Account(Id)?$/.test(column)) continue;+ if (typeof value === "string" && value.length > 0) ids.add(value);+ }++ return [...ids];+}++/**+ * Shape the display-only provider fields into mapping metadata. Returns+ * undefined when neither field is provided so the mapping stores null.+ */+export function buildAccountMappingMetadata(args: {+ externalCode?: string;+ externalName?: string;+}): Record<string, unknown> | undefined {+ const metadata: Record<string, unknown> = {};+ if (args.externalCode) metadata.externalCode = args.externalCode;+ if (args.externalName) metadata.externalName = args.externalName;++ return Object.keys(metadata).length > 0 ? metadata : undefined;+}++/**+ * Safely read the display fields back out of stored mapping metadata.+ */+export function getAccountMappingDisplayMetadata(metadata: unknown): {+ externalCode: string | null;+ externalName: string | null;+} {+ if (+ typeof metadata !== "object" ||+ metadata === null ||+ Array.isArray(metadata)+ ) {+ return { externalCode: null, externalName: null };+ }++ const { externalCode, externalName } = metadata as Record<string, unknown>;+ return {+ externalCode: typeof externalCode === "string" ? externalCode : null,+ externalName: typeof externalName === "string" ? externalName : null+ };+}++/**+ * Propose matches where Carbon account.number equals the provider account+ * code exactly (no trimming, no case folding). Ambiguous candidates are+ * skipped: duplicate Carbon numbers, duplicate provider codes, accounts+ * already mapped, and provider accounts already used by a mapping.+ */+export function proposeAccountMatchesByCode(args: {+ accounts: Array<{ id: string; number: string | null; name: string }>;+ providerAccounts: ProviderChartAccount[];+ mappedAccountIds?: Iterable<string>;+ mappedExternalIds?: Iterable<string>;+}): AccountMatchProposal[] {+ const mappedAccountIds = new Set(args.mappedAccountIds ?? []);+ const mappedExternalIds = new Set(args.mappedExternalIds ?? []);++ const providerByCode = new Map<string, ProviderChartAccount>();+ const ambiguousCodes = new Set<string>();+ for (const providerAccount of args.providerAccounts) {+ const code = providerAccount.code;+ if (!code) continue;+ if (providerByCode.has(code)) {+ ambiguousCodes.add(code);+ continue;+ }+ providerByCode.set(code, providerAccount);+ }++ const numberCounts = new Map<string, number>();+ for (const account of args.accounts) {+ if (!account.number) continue;+ numberCounts.set(+ account.number,+ (numberCounts.get(account.number) ?? 0) + 1+ );+ }++ const proposals: AccountMatchProposal[] = [];+ for (const account of args.accounts) {+ if (!account.number) continue;+ if (mappedAccountIds.has(account.id)) continue;+ if ((numberCounts.get(account.number) ?? 0) > 1) continue;+ if (ambiguousCodes.has(account.number)) continue;++ const providerAccount = providerByCode.get(account.number);+ if (!providerAccount) continue;+ if (mappedExternalIds.has(providerAccount.id)) continue;++ proposals.push({+ accountId: account.id,+ accountNumber: account.number,+ accountName: account.name,+ externalId: providerAccount.id,+ externalCode: providerAccount.code ?? account.number,+ externalName: providerAccount.name ?? null+ });+ }++ return proposals;+}++/**+ * Get all account mappings for an integration, joined with the Carbon+ * account (id, number, name) for display, ordered by account number.+ */+export async function getAccountMappings(+ db: Db,+ args: { companyId: string; integration: string }+): Promise<{ data: AccountMapping[] | null; error: string | null }> {+ try {+ const rows = await db+ .selectFrom("externalIntegrationMapping as m")+ .leftJoin("account as a", "a.id", "m.entityId")+ .select([+ "m.id",+ "m.entityId as accountId",+ "m.externalId",+ "m.metadata",+ "m.lastSyncedAt",+ "a.number as accountNumber",+ "a.name as accountName"+ ])+ .where("m.entityType", "=", ACCOUNT_MAPPING_ENTITY_TYPE)+ .where("m.integration", "=", args.integration)+ .where("m.companyId", "=", args.companyId)+ .orderBy("accountNumber", "asc")+ .execute();++ const data = rows.map((row) => {+ const display = getAccountMappingDisplayMetadata(row.metadata);+ return {+ id: row.id,+ accountId: row.accountId,+ accountNumber: row.accountNumber ?? null,+ accountName: row.accountName ?? null,+ externalId: row.externalId ?? null,+ externalCode: display.externalCode,+ externalName: display.externalName,+ lastSyncedAt: (row.lastSyncedAt as string | null) ?? null,+ metadata: (row.metadata as Record<string, unknown> | null) ?? null+ };+ });++ return { data, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}++/**+ * Carbon account.id → provider account CODE from the account-mapping rows+ * (entityType "account"). Providers that address accounts by code (Xero+ * `AccountCode`, Rillet `account_code`) resolve through the mapping's stored+ * `externalCode`; mappings without a code count as unmapped and are omitted.+ * Shared by the Xero bill/invoice syncers (mirrors the journal syncer's+ * `getAccountCodesById` and Rillet's `loadRilletAccountCodesById`).+ */+export async function loadAccountCodesById(+ db: Db,+ args: { companyId: string; integration: string }+): Promise<Map<string, string>> {+ const mappings = await getAccountMappings(db, {+ companyId: args.companyId,+ integration: args.integration+ });++ if (mappings.error) {+ throw new Error(`Failed to load account mappings: ${mappings.error}`);+ }++ const codesById = new Map<string, string>();+ for (const mapping of mappings.data ?? []) {+ if (mapping.externalCode) {+ codesById.set(mapping.accountId, mapping.externalCode);+ }+ }+ return codesById;+}++/**+ * Upsert an account mapping (Carbon account.id → provider account id).+ * externalCode/externalName go into the mapping metadata for display.+ * Consolidation is a legitimate many-to-one: several Carbon detail+ * accounts may map to a single provider account, so duplicate external+ * ids are allowed.+ */+export async function upsertAccountMapping(+ db: Db,+ args: UpsertAccountMappingInput+): Promise<{ data: ExternalIntegrationMapping | null; error: string | null }> {+ try {+ const mappingService = createMappingService(db, args.companyId);++ await mappingService.link(+ ACCOUNT_MAPPING_ENTITY_TYPE,+ args.accountId,+ args.integration,+ args.externalId,+ {+ metadata: buildAccountMappingMetadata(args),+ createdBy: args.userId,+ allowDuplicateExternalId: true+ }+ );++ const data = await mappingService.getByEntity(+ ACCOUNT_MAPPING_ENTITY_TYPE,+ args.accountId,+ args.integration+ );++ return { data, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}++/**+ * The Carbon account ids referenced by the company's accountDefault row —+ * the complete set of accounts automated postings run through, and the only+ * accounts the mapping tab manages. Loads the row and collects every+ * *Account / *AccountId FK on it.+ */+export async function loadAccountDefaultAccountIds(+ db: Db,+ companyId: string+): Promise<string[]> {+ const row = await db+ .selectFrom("accountDefault")+ .selectAll()+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ return collectAccountDefaultAccountIds(row ? { ...row } : null);+}++/**+ * Carbon accounts that automated postings hit but that have no mapping yet:+ * the accounts referenced by accountDefault columns, minus already-mapped+ * ids, minus group headers. accountDefault is the whole mappable set —+ * every synced transaction posts through one of these accounts — so accounts+ * seen only on historical/manual journal lines are intentionally excluded.+ */+export async function getUnmappedPostingAccounts(+ db: Db,+ args: { companyId: string; integration: string }+): Promise<{ data: UnmappedPostingAccount[] | null; error: string | null }> {+ try {+ const accountDefaultIds = await loadAccountDefaultAccountIds(+ db,+ args.companyId+ );+ if (accountDefaultIds.length === 0) {+ return { data: [], error: null };+ }++ const mappedRows = await db+ .selectFrom("externalIntegrationMapping")+ .select("entityId")+ .where("entityType", "=", ACCOUNT_MAPPING_ENTITY_TYPE)+ .where("integration", "=", args.integration)+ .where("companyId", "=", args.companyId)+ .execute();+ const mapped = new Set(mappedRows.map((row) => row.entityId));++ const unmappedIds = accountDefaultIds.filter((id) => !mapped.has(id));+ if (unmappedIds.length === 0) {+ return { data: [], error: null };+ }++ const companyGroupId = await getCompanyGroupId(db, args.companyId);+ if (!companyGroupId) {+ return {+ data: null,+ error: `No company group found for company ${args.companyId}`+ };+ }++ const accounts = await db+ .selectFrom("account")+ .select(["id", "number", "name"])+ .where("companyGroupId", "=", companyGroupId)+ .where("isGroup", "=", false)+ .where("id", "in", unmappedIds)+ .orderBy("number", "asc")+ .execute();++ return { data: accounts, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}++/**+ * Propose (not write) exact matches between Carbon account numbers and the+ * provider's chart-of-accounts codes. Only active, non-group, numbered+ * accountDefault accounts without an existing mapping are considered — the+ * same set getUnmappedPostingAccounts surfaces — so proposals never suggest+ * an account outside the mappable set; the UI confirms each proposal and+ * calls upsertAccountMapping.+ */+export async function matchAccountsByCode(+ db: Db,+ args: {+ companyId: string;+ integration: string;+ providerAccounts: ProviderChartAccount[];+ }+): Promise<{ data: AccountMatchProposal[] | null; error: string | null }> {+ try {+ const companyGroupId = await getCompanyGroupId(db, args.companyId);+ if (!companyGroupId) {+ return {+ data: null,+ error: `No company group found for company ${args.companyId}`+ };+ }++ // Only accountDefault accounts are mappable (automated postings run+ // through them), so an account outside that set is never proposed.+ const accountDefaultIds = await loadAccountDefaultAccountIds(+ db,+ args.companyId+ );+ if (accountDefaultIds.length === 0) {+ return { data: [], error: null };+ }++ const accounts = await db+ .selectFrom("account")+ .select(["id", "number", "name"])+ .where("companyGroupId", "=", companyGroupId)+ .where("isGroup", "=", false)+ .where("active", "=", true)+ .where("number", "is not", null)+ .where("id", "in", accountDefaultIds)+ .execute();++ const mappings = await db+ .selectFrom("externalIntegrationMapping")+ .select(["entityId", "externalId"])+ .where("entityType", "=", ACCOUNT_MAPPING_ENTITY_TYPE)+ .where("integration", "=", args.integration)+ .where("companyId", "=", args.companyId)+ .execute();++ const data = proposeAccountMatchesByCode({+ accounts,+ providerAccounts: args.providerAccounts,+ mappedAccountIds: mappings.map((mapping) => mapping.entityId),+ mappedExternalIds: mappings+ .map((mapping) => mapping.externalId)+ .filter((externalId): externalId is string => externalId !== null)+ });++ return { data, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}diff --git a/packages/ee/src/accounting/core/credentials.test.ts b/packages/ee/src/accounting/core/credentials.test.tsnew file mode 100644index 0000000000..08cac2cd10--- /dev/null+++ b/packages/ee/src/accounting/core/credentials.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from "vitest";+import {+ ProviderIntegrationMetadataSchema,+ parseStoredCredentials+} from "./models";++describe("parseStoredCredentials", () => {+ it("maps the legacy flat oauth2 shape into providerMetadata", () => {+ const legacy = {+ type: "oauth2",+ accessToken: "at-123",+ refreshToken: "rt-456",+ expiresAt: "2026-07-09T00:00:00.000Z",+ tenantId: "tenant-1",+ tenantName: "Acme Inc"+ };++ const parsed = parseStoredCredentials(legacy);++ expect(parsed).toEqual({+ type: "oauth2",+ accessToken: "at-123",+ refreshToken: "rt-456",+ expiresAt: "2026-07-09T00:00:00.000Z",+ providerMetadata: {+ tenantId: "tenant-1",+ tenantName: "Acme Inc"+ }+ });+ });++ it("maps a legacy shape with only tenantId", () => {+ const parsed = parseStoredCredentials({+ type: "oauth2",+ accessToken: "at-123",+ tenantId: "tenant-1"+ });++ expect(parsed).toEqual({+ type: "oauth2",+ accessToken: "at-123",+ providerMetadata: { tenantId: "tenant-1" }+ });+ });++ it("round-trips the new oauth2 shape unchanged", () => {+ const credentials = {+ type: "oauth2",+ accessToken: "at-123",+ refreshToken: "rt-456",+ expiresAt: "2026-07-09T00:00:00.000Z",+ scope: ["accounting.transactions"],+ providerMetadata: {+ tenantId: "tenant-1",+ tenantName: "Acme Inc"+ }+ };++ const parsed = parseStoredCredentials(credentials);++ expect(parsed).toEqual(credentials);+ // Parsing its own output is stable+ expect(parseStoredCredentials(parsed)).toEqual(credentials);+ });++ it("parses apiKey credentials", () => {+ const credentials = {+ type: "apiKey",+ apiKey: "rk_live_abc123",+ environment: "sandbox",+ providerMetadata: { subsidiaryId: "11111111-1111-1111-1111-111111111111" }+ };++ expect(parseStoredCredentials(credentials)).toEqual(credentials);+ });++ it("defaults apiKey environment to production", () => {+ const parsed = parseStoredCredentials({+ type: "apiKey",+ apiKey: "rk_live_abc123"+ });++ expect(parsed).toEqual({+ type: "apiKey",+ apiKey: "rk_live_abc123",+ environment: "production"+ });+ });++ it("rejects an apiKey credential with an empty key", () => {+ expect(() =>+ parseStoredCredentials({ type: "apiKey", apiKey: "" })+ ).toThrow();+ });++ it("parses bridge credentials", () => {+ const credentials = {+ type: "bridge",+ vendor: "conductor",+ externalConnectionId: "end-user-1"+ };++ expect(parseStoredCredentials(credentials)).toEqual(credentials);+ });++ it("throws on garbage input", () => {+ expect(() => parseStoredCredentials(null)).toThrow();+ expect(() => parseStoredCredentials("nope")).toThrow();+ expect(() => parseStoredCredentials({})).toThrow();+ expect(() => parseStoredCredentials({ type: "oauth2" })).toThrow();+ expect(() => parseStoredCredentials({ type: "carrier-pigeon" })).toThrow();+ });+});++describe("ProviderIntegrationMetadataSchema", () => {+ it("upgrades legacy credentials stored on integration metadata", () => {+ const metadata = {+ syncConfig: { entities: { customer: { enabled: true } } },+ credentials: {+ type: "oauth2",+ accessToken: "at-123",+ refreshToken: "rt-456",+ tenantId: "tenant-1",+ tenantName: "Acme Inc"+ }+ };++ const parsed = ProviderIntegrationMetadataSchema.parse(metadata);++ expect(parsed.credentials).toEqual({+ type: "oauth2",+ accessToken: "at-123",+ refreshToken: "rt-456",+ providerMetadata: {+ tenantId: "tenant-1",+ tenantName: "Acme Inc"+ }+ });+ });+});diff --git a/packages/ee/src/accounting/core/dimension-mapping.test.ts b/packages/ee/src/accounting/core/dimension-mapping.test.tsnew file mode 100644index 0000000000..a271619524--- /dev/null+++ b/packages/ee/src/accounting/core/dimension-mapping.test.ts@@ -0,0 +1,350 @@+import { describe, expect, it, vi } from "vitest";+import {+ buildDimensionFieldLookup,+ buildDimensionValueMappingEntityId,+ buildDimensionValueMappingLookup,+ ensureDimensionValueExternalIds,+ matchDimensionValuesByName,+ parseDimensionValueMappingEntityId,+ resolveDimensionSlotAutoCreate,+ validateDimensionSlots+} from "./dimension-mapping";+import type { DimensionTarget } from "./types";++// ── Composite key (entityId = "<dimensionId>:<valueId>") ─────────────────────+// valueId is polymorphic across entity-typed dimensions, so the mapping's+// entityId must carry the dimension too.++describe("dimension value mapping entityId", () => {+ it("builds the composite <dimensionId>:<valueId> key", () => {+ expect(buildDimensionValueMappingEntityId("dim_loc", "loc_MRzDg")).toBe(+ "dim_loc:loc_MRzDg"+ );+ });++ it("round-trips through parse", () => {+ const parsed = parseDimensionValueMappingEntityId("dim_loc:loc_MRzDg");+ expect(parsed).toEqual({ dimensionId: "dim_loc", valueId: "loc_MRzDg" });+ });++ it("returns null for malformed entity ids", () => {+ expect(parseDimensionValueMappingEntityId("no-separator")).toBeNull();+ expect(parseDimensionValueMappingEntityId(":value-only")).toBeNull();+ expect(parseDimensionValueMappingEntityId("dimension-only:")).toBeNull();+ });+});++describe("buildDimensionValueMappingLookup", () => {+ it("keys provider option ids by the composite value key, skipping rows without an externalId", () => {+ const lookup = buildDimensionValueMappingLookup([+ {+ id: "m1",+ dimensionId: "dim_loc",+ valueId: "loc_1",+ externalId: "opt-1",+ externalName: "Atlanta",+ lastSyncedAt: null,+ metadata: null+ },+ {+ id: "m2",+ dimensionId: "dim_loc",+ valueId: "loc_2",+ externalId: null,+ externalName: null,+ lastSyncedAt: null,+ metadata: null+ }+ ]);++ expect(lookup.get("dim_loc:loc_1")).toBe("opt-1");+ expect(lookup.has("dim_loc:loc_2")).toBe(false);+ });+});++// ── Match by name (exact-match proposals only) ───────────────────────────────++describe("buildDimensionFieldLookup", () => {+ it("maps dimensionId → provider Field id, skipping rows with no externalId", () => {+ const lookup = buildDimensionFieldLookup([+ {+ id: "m1",+ dimensionId: "dim_loc",+ externalId: "field-loc",+ externalName: "Location"+ },+ { id: "m2", dimensionId: "dim_cc", externalId: null, externalName: null }+ ]);++ expect(lookup.get("dim_loc")).toBe("field-loc");+ expect(lookup.has("dim_cc")).toBe(false);+ expect(lookup.size).toBe(1);+ });+});++describe("matchDimensionValuesByName", () => {+ const values = [+ { dimensionId: "dim_loc", valueId: "loc_1", label: "Atlanta" },+ { dimensionId: "dim_loc", valueId: "loc_2", label: "Boston" },+ { dimensionId: "dim_loc", valueId: "loc_3", label: "Chicago" }+ ];++ it("proposes exact label ↔ name matches only (no trimming, no case folding)", () => {+ const proposals = matchDimensionValuesByName({+ values,+ providerOptions: [+ { id: "opt-a", name: "Atlanta" },+ { id: "opt-b", name: "boston" }, // case differs — not a match+ { id: "opt-c", name: "Chicago " } // whitespace differs — not a match+ ]+ });++ expect(proposals).toEqual([+ {+ dimensionId: "dim_loc",+ valueId: "loc_1",+ label: "Atlanta",+ externalId: "opt-a",+ externalName: "Atlanta"+ }+ ]);+ });++ it("skips ambiguous candidates: duplicate labels, duplicate option names, and already-mapped sides", () => {+ const proposals = matchDimensionValuesByName({+ values: [+ ...values,+ // duplicate label — ambiguous, both skipped+ { dimensionId: "dim_loc", valueId: "loc_4", label: "Atlanta" }+ ],+ providerOptions: [+ { id: "opt-a", name: "Atlanta" },+ // duplicate provider name — ambiguous, skipped+ { id: "opt-b1", name: "Boston" },+ { id: "opt-b2", name: "Boston" },+ { id: "opt-c", name: "Chicago" }+ ],+ // Chicago's provider option is already used by a mapping+ mappedExternalIds: ["opt-c"]+ });++ expect(proposals).toEqual([]);+ });++ it("skips values that already have a mapping", () => {+ const proposals = matchDimensionValuesByName({+ values,+ providerOptions: [{ id: "opt-a", name: "Atlanta" }],+ mappedValueKeys: ["dim_loc:loc_1"]+ });++ expect(proposals).toEqual([]);+ });++ it("skips values without a resolvable label and nameless options", () => {+ const proposals = matchDimensionValuesByName({+ values: [{ dimensionId: "dim_loc", valueId: "loc_x", label: null }],+ providerOptions: [{ id: "opt-x", name: null }]+ });++ expect(proposals).toEqual([]);+ });+});++// ── Slot-config validation ───────────────────────────────────────────────────++describe("validateDimensionSlots", () => {+ const targets: DimensionTarget[] = [+ { id: "class", label: "Class" },+ { id: "department", label: "Department" }+ ];++ it("accepts a valid config", () => {+ expect(+ validateDimensionSlots({+ slots: [+ { dimensionId: "dim_loc", target: "class" },+ { dimensionId: "dim_cc", target: "department" }+ ],+ targets,+ maxSlots: 2+ })+ ).toEqual([]);+ });++ it("rejects unknown provider targets", () => {+ const errors = validateDimensionSlots({+ slots: [{ dimensionId: "dim_loc", target: "tracking:abc" }],+ targets+ });+ expect(errors).toHaveLength(1);+ expect(errors[0]).toContain('Unknown provider target "tracking:abc"');+ });++ it("rejects a dimension slotted twice", () => {+ const errors = validateDimensionSlots({+ slots: [+ { dimensionId: "dim_loc", target: "class" },+ { dimensionId: "dim_loc", target: "department" }+ ],+ targets+ });+ expect(errors.some((error) => error.includes("slotted 2 times"))).toBe(+ true+ );+ });++ it("enforces per-target capacity (default 1)", () => {+ const errors = validateDimensionSlots({+ slots: [+ { dimensionId: "dim_loc", target: "class" },+ { dimensionId: "dim_cc", target: "class" }+ ],+ targets+ });+ expect(+ errors.some((error) => error.includes('"class" is used by 2 slots'))+ ).toBe(true);+ });++ it("enforces the provider's structural slot cap", () => {+ const errors = validateDimensionSlots({+ slots: [+ { dimensionId: "dim_a", target: "class" },+ { dimensionId: "dim_b", target: "department" },+ { dimensionId: "dim_c", target: "class" }+ ],+ targets,+ maxSlots: 2+ });+ expect(errors.some((error) => error.includes("Too many"))).toBe(true);+ });+});++// ── autoCreate resolution (provider defaults) ────────────────────────────────++describe("resolveDimensionSlotAutoCreate", () => {+ it("honors an explicit flag over the provider default", () => {+ expect(resolveDimensionSlotAutoCreate({ autoCreate: false }, true)).toBe(+ false+ );+ expect(resolveDimensionSlotAutoCreate({ autoCreate: true }, false)).toBe(+ true+ );+ });++ it("falls back to the provider default when the slot has no flag (Rillet on, QBO/Xero off)", () => {+ expect(resolveDimensionSlotAutoCreate({}, true)).toBe(true);+ expect(resolveDimensionSlotAutoCreate({}, false)).toBe(false);+ });+});++// ── autoCreate orchestration ─────────────────────────────────────────────────+// Creation is always BY NAME (the resolved READABLE label); the returned+// provider id lands in the mappings lookup so pre-flight + mapper reuse it.++describe("ensureDimensionValueExternalIds", () => {+ const lines = [+ {+ dimensions: [+ { dimensionId: "dim_loc", valueId: "loc_1" },+ { dimensionId: "dim_item", valueId: "item_1" }+ ]+ },+ { dimensions: [{ dimensionId: "dim_loc", valueId: "loc_1" }] }, // duplicate value+ { dimensions: undefined }+ ];++ it("creates missing provider options by LABEL for autoCreate slots and updates the lookup in place", async () => {+ const mappings = new Map<string, string>();+ const createExternalValue = vi.fn(async () => "opt-created");+ const persistMapping = vi.fn(async () => undefined);++ const { created } = await ensureDimensionValueExternalIds({+ lines,+ slots: [{ dimensionId: "dim_loc", target: "field:f1", autoCreate: true }],+ defaultAutoCreate: false,+ mappings,+ resolveLabels: async () => new Map([["dim_loc:loc_1", "Atlanta"]]),+ createExternalValue,+ persistMapping+ });++ // Duplicate value on a second line creates exactly once, by name+ expect(createExternalValue).toHaveBeenCalledTimes(1);+ expect(createExternalValue).toHaveBeenCalledWith(+ { dimensionId: "dim_loc", target: "field:f1", autoCreate: true },+ "Atlanta"+ );+ expect(persistMapping).toHaveBeenCalledWith(+ { dimensionId: "dim_loc", valueId: "loc_1" },+ "opt-created",+ "Atlanta"+ );+ expect(mappings.get("dim_loc:loc_1")).toBe("opt-created");+ expect(created).toEqual([+ {+ dimensionId: "dim_loc",+ valueId: "loc_1",+ externalId: "opt-created",+ label: "Atlanta"+ }+ ]);+ });++ it("skips slots whose effective autoCreate is off and values already mapped", async () => {+ const mappings = new Map([["dim_loc:loc_1", "opt-existing"]]);+ const createExternalValue = vi.fn(async () => "never");++ const { created } = await ensureDimensionValueExternalIds({+ lines,+ slots: [+ { dimensionId: "dim_loc", target: "field:f1" }, // default off → skipped+ { dimensionId: "dim_item", target: "field:f2", autoCreate: false }+ ],+ defaultAutoCreate: false,+ mappings,+ resolveLabels: async () => new Map(),+ createExternalValue,+ persistMapping: vi.fn(async () => undefined)+ });++ expect(createExternalValue).not.toHaveBeenCalled();+ expect(created).toEqual([]);+ });++ it("applies the provider default (Rillet: on) to slots without an explicit flag", async () => {+ const mappings = new Map<string, string>();++ await ensureDimensionValueExternalIds({+ lines,+ slots: [{ dimensionId: "dim_loc", target: "field:f1" }],+ defaultAutoCreate: true,+ mappings,+ resolveLabels: async () => new Map([["dim_loc:loc_1", "Atlanta"]]),+ createExternalValue: async () => "fv-1",+ persistMapping: async () => undefined+ });++ expect(mappings.get("dim_loc:loc_1")).toBe("fv-1");+ });++ it("leaves values whose label cannot be resolved unmapped (warn/drop handles them downstream)", async () => {+ const mappings = new Map<string, string>();+ const createExternalValue = vi.fn(async () => "never");++ const { created } = await ensureDimensionValueExternalIds({+ lines,+ slots: [{ dimensionId: "dim_loc", target: "field:f1", autoCreate: true }],+ defaultAutoCreate: false,+ mappings,+ resolveLabels: async () => new Map(), // entity deleted — no label+ createExternalValue,+ persistMapping: vi.fn(async () => undefined)+ });++ expect(createExternalValue).not.toHaveBeenCalled();+ expect(created).toEqual([]);+ expect(mappings.size).toBe(0);+ });+});diff --git a/packages/ee/src/accounting/core/dimension-mapping.ts b/packages/ee/src/accounting/core/dimension-mapping.tsnew file mode 100644index 0000000000..cd6fa75f7b--- /dev/null+++ b/packages/ee/src/accounting/core/dimension-mapping.ts@@ -0,0 +1,780 @@+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";+import type { ExternalIntegrationMapping } from "./external-mapping";+import { createMappingService } from "./external-mapping";+import type { PostingSyncDimensionSlot } from "./models";+import type { JournalLineDimensionRef } from "./posting";+import type { DimensionTarget } from "./types";++/**+ * Dimension-value mapping service: thin wrappers over+ * ExternalIntegrationMappingService with entityType = "dimensionValue",+ * linking Carbon dimension VALUES to provider analytics options (QBO+ * Class/Department entities, Xero tracking options, Rillet Field values).+ *+ * The Carbon side of a mapping is the composite `<dimensionId>:<valueId>`+ * — valueId alone is polymorphic across entity-typed dimensions+ * (location.id, supplier.id, item.id, dimensionValue.id, …), so the+ * composite key is required. The provider side is the option id in+ * `externalId`, with the display name in metadata — exactly like account+ * mapping (core/account-mapping.ts).+ *+ * What crosses the wire to a provider is always the RESOLVED provider+ * option id; Carbon's internal value ids never leave. Provider-side+ * creation (autoCreate) is always BY NAME — the READABLE label resolved+ * per the dimension's entityType (resolveDimensionValueLabels, mirroring+ * DimensionSelector.tsx / getEntityValuesByIds in the accounting module).+ */++export const DIMENSION_VALUE_MAPPING_ENTITY_TYPE = "dimensionValue";++type Db = Kysely<KyselyDatabase> | KyselyTx;++/** `<dimensionId>:<valueId>` — the mapping row's entityId. */+export function buildDimensionValueMappingEntityId(+ dimensionId: string,+ valueId: string+): string {+ return `${dimensionId}:${valueId}`;+}++/** Split a mapping entityId back into `{ dimensionId, valueId }` (null when malformed). */+export function parseDimensionValueMappingEntityId(+ entityId: string+): JournalLineDimensionRef | null {+ const separator = entityId.indexOf(":");+ if (separator <= 0 || separator === entityId.length - 1) return null;+ return {+ dimensionId: entityId.slice(0, separator),+ valueId: entityId.slice(separator + 1)+ };+}++function toErrorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++/**+ * A dimension-value mapping row shaped for display / lookup.+ */+export interface DimensionValueMapping {+ id: string;+ dimensionId: string;+ valueId: string;+ externalId: string | null;+ externalName: string | null;+ lastSyncedAt: string | null;+ metadata: Record<string, unknown> | null;+}++/**+ * A Carbon dimension value with its resolved READABLE label (part+ * readable id for Item dimensions, name for everything else).+ */+export interface DimensionValueWithLabel extends JournalLineDimensionRef {+ label: string | null;+}++/**+ * A proposed (not written) match between a Carbon dimension value and a+ * provider option. The UI confirms proposals and calls+ * upsertDimensionValueMapping.+ */+export interface DimensionValueMatchProposal {+ dimensionId: string;+ valueId: string;+ label: string;+ externalId: string;+ externalName: string | null;+}++function getExternalNameFromMetadata(metadata: unknown): string | null {+ if (typeof metadata !== "object" || metadata === null) return null;+ const { externalName } = metadata as Record<string, unknown>;+ return typeof externalName === "string" ? externalName : null;+}++/**+ * All dimension-value mappings for an integration (optionally one+ * dimension), parsed out of the composite entityId. Malformed rows are+ * skipped.+ */+export async function getDimensionValueMappings(+ db: Db,+ args: { companyId: string; integration: string; dimensionId?: string }+): Promise<{ data: DimensionValueMapping[] | null; error: string | null }> {+ try {+ const rows = await db+ .selectFrom("externalIntegrationMapping")+ .select(["id", "entityId", "externalId", "metadata", "lastSyncedAt"])+ .where("entityType", "=", DIMENSION_VALUE_MAPPING_ENTITY_TYPE)+ .where("integration", "=", args.integration)+ .where("companyId", "=", args.companyId)+ .execute();++ const data: DimensionValueMapping[] = [];+ for (const row of rows) {+ const parsed = parseDimensionValueMappingEntityId(row.entityId);+ if (!parsed) continue;+ if (args.dimensionId && parsed.dimensionId !== args.dimensionId) {+ continue;+ }+ data.push({+ id: row.id,+ dimensionId: parsed.dimensionId,+ valueId: parsed.valueId,+ externalId: row.externalId ?? null,+ externalName: getExternalNameFromMetadata(row.metadata),+ lastSyncedAt: (row.lastSyncedAt as string | null) ?? null,+ metadata: (row.metadata as Record<string, unknown> | null) ?? null+ });+ }++ return { data, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}++/**+ * Lookup used by pre-flight and the provider mappers:+ * `<dimensionId>:<valueId>` → provider option id. Mappings without a+ * stored externalId count as unmapped.+ */+export function buildDimensionValueMappingLookup(+ mappings: ReadonlyArray<DimensionValueMapping>+): Map<string, string> {+ const lookup = new Map<string, string>();+ for (const mapping of mappings) {+ if (mapping.externalId) {+ lookup.set(+ buildDimensionValueMappingEntityId(+ mapping.dimensionId,+ mapping.valueId+ ),+ mapping.externalId+ );+ }+ }+ return lookup;+}++/**+ * Upsert a dimension-value mapping (`<dimensionId>:<valueId>` → provider+ * option id). Several Carbon values may legitimately share one provider+ * option (consolidation), so duplicate external ids are allowed — the+ * same stance as account mapping.+ */+export async function upsertDimensionValueMapping(+ db: Db,+ args: {+ companyId: string;+ integration: string;+ dimensionId: string;+ valueId: string;+ externalId: string;+ externalName?: string;+ userId?: string;+ }+): Promise<{ data: ExternalIntegrationMapping | null; error: string | null }> {+ try {+ const mappingService = createMappingService(db, args.companyId);+ const entityId = buildDimensionValueMappingEntityId(+ args.dimensionId,+ args.valueId+ );++ await mappingService.link(+ DIMENSION_VALUE_MAPPING_ENTITY_TYPE,+ entityId,+ args.integration,+ args.externalId,+ {+ ...(args.externalName+ ? { metadata: { externalName: args.externalName } }+ : {}),+ ...(args.userId ? { createdBy: args.userId } : {}),+ allowDuplicateExternalId: true+ }+ );++ const data = await mappingService.getByEntity(+ DIMENSION_VALUE_MAPPING_ENTITY_TYPE,+ entityId,+ args.integration+ );++ return { data, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}++/**+ * Dimension → provider FIELD mapping service (entityType "dimension"),+ * mirroring the value service above. The Carbon side is the plain+ * `dimensionId`; the provider side is the Field/dimension id in `externalId`+ * (Rillet Field uuid). Used by the "send all dimensions" flow to auto-+ * provision a provider Field per Carbon dimension, so a value mapping always+ * has a Field to hang off of.+ */+export const DIMENSION_MAPPING_ENTITY_TYPE = "dimension";++/** A dimension → provider Field mapping row. */+export interface DimensionFieldMapping {+ id: string;+ dimensionId: string;+ externalId: string | null;+ externalName: string | null;+}++/** All dimension → provider Field mappings for an integration. */+export async function getDimensionMappings(+ db: Db,+ args: { companyId: string; integration: string }+): Promise<{ data: DimensionFieldMapping[] | null; error: string | null }> {+ try {+ const rows = await db+ .selectFrom("externalIntegrationMapping")+ .select(["id", "entityId", "externalId", "metadata"])+ .where("entityType", "=", DIMENSION_MAPPING_ENTITY_TYPE)+ .where("integration", "=", args.integration)+ .where("companyId", "=", args.companyId)+ .execute();++ const data = rows.map((row) => ({+ id: row.id,+ dimensionId: row.entityId,+ externalId: row.externalId ?? null,+ externalName: getExternalNameFromMetadata(row.metadata)+ }));++ return { data, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}++/** `dimensionId` → provider Field id. Rows without an externalId are unmapped. */+export function buildDimensionFieldLookup(+ mappings: ReadonlyArray<DimensionFieldMapping>+): Map<string, string> {+ const lookup = new Map<string, string>();+ for (const mapping of mappings) {+ if (mapping.externalId) lookup.set(mapping.dimensionId, mapping.externalId);+ }+ return lookup;+}++/**+ * Upsert a dimension → provider Field mapping (dimensionId → Field id). Two+ * Carbon dimensions that share a name may resolve to one provider Field+ * (auto-provision reuses an existing Field by name), so duplicate external+ * ids are allowed — the same stance as the value + account mappings.+ */+export async function upsertDimensionMapping(+ db: Db,+ args: {+ companyId: string;+ integration: string;+ dimensionId: string;+ externalId: string;+ externalName?: string;+ userId?: string;+ }+): Promise<{ data: ExternalIntegrationMapping | null; error: string | null }> {+ try {+ const mappingService = createMappingService(db, args.companyId);++ await mappingService.link(+ DIMENSION_MAPPING_ENTITY_TYPE,+ args.dimensionId,+ args.integration,+ args.externalId,+ {+ ...(args.externalName+ ? { metadata: { externalName: args.externalName } }+ : {}),+ ...(args.userId ? { createdBy: args.userId } : {}),+ allowDuplicateExternalId: true+ }+ );++ const data = await mappingService.getByEntity(+ DIMENSION_MAPPING_ENTITY_TYPE,+ args.dimensionId,+ args.integration+ );++ return { data, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}++/**+ * `dimensionId` → dimension name, for auto-provisioning provider Fields by+ * name. Queries `dimension` by id (already company-scoped by provenance —+ * the ids come from the company's journal lines), mirroring how+ * resolveDimensionValueLabels reads the dimension table.+ */+export async function loadDimensionNames(+ db: Db,+ args: { dimensionIds: ReadonlyArray<string> }+): Promise<Map<string, string>> {+ const names = new Map<string, string>();+ if (args.dimensionIds.length === 0) return names;++ const rows = await db+ .selectFrom("dimension")+ .select(["id", "name"])+ .where("id", "in", [...args.dimensionIds])+ .execute();++ for (const row of rows) {+ if (typeof row.name === "string" && row.name) names.set(row.id, row.name);+ }+ return names;+}++/**+ * Propose matches where a Carbon dimension value's resolved label equals+ * a provider option name EXACTLY (no trimming, no case folding).+ * Ambiguous candidates are skipped: duplicate labels among the values,+ * duplicate names among the provider options, values already mapped, and+ * provider options already used by a mapping. Pure — the UI confirms+ * proposals and calls upsertDimensionValueMapping.+ */+export function matchDimensionValuesByName(args: {+ values: ReadonlyArray<DimensionValueWithLabel>;+ providerOptions: ReadonlyArray<{ id: string; name: string | null }>;+ mappedValueKeys?: Iterable<string>;+ mappedExternalIds?: Iterable<string>;+}): DimensionValueMatchProposal[] {+ const mappedValueKeys = new Set(args.mappedValueKeys ?? []);+ const mappedExternalIds = new Set(args.mappedExternalIds ?? []);++ const optionsByName = new Map<string, { id: string; name: string }>();+ const ambiguousNames = new Set<string>();+ for (const option of args.providerOptions) {+ if (!option.name) continue;+ if (optionsByName.has(option.name)) {+ ambiguousNames.add(option.name);+ continue;+ }+ optionsByName.set(option.name, { id: option.id, name: option.name });+ }++ const labelCounts = new Map<string, number>();+ for (const value of args.values) {+ if (!value.label) continue;+ labelCounts.set(value.label, (labelCounts.get(value.label) ?? 0) + 1);+ }++ const proposals: DimensionValueMatchProposal[] = [];+ for (const value of args.values) {+ if (!value.label) continue;+ const key = buildDimensionValueMappingEntityId(+ value.dimensionId,+ value.valueId+ );+ if (mappedValueKeys.has(key)) continue;+ if ((labelCounts.get(value.label) ?? 0) > 1) continue;+ if (ambiguousNames.has(value.label)) continue;++ const option = optionsByName.get(value.label);+ if (!option) continue;+ if (mappedExternalIds.has(option.id)) continue;++ proposals.push({+ dimensionId: value.dimensionId,+ valueId: value.valueId,+ label: value.label,+ externalId: option.id,+ externalName: option.name+ });+ }++ return proposals;+}++// /********************************************************\+// * Label resolution (Carbon-side, readable) *+// \********************************************************/++/**+ * The source table + label column per dimension entityType. Mirrors+ * `getEntityValuesByIds` in apps/erp accounting.ee.service.ts and the+ * DimensionSelector's client-store resolution (WorkCenter/Process). The+ * Item label is the READABLE part id (readableIdWithRevision), never the+ * internal id.+ */+type LabelSource = { table: string; labelColumn: string };++const DIMENSION_LABEL_SOURCES: Record<string, LabelSource> = {+ Custom: { table: "dimensionValue", labelColumn: "name" },+ Location: { table: "location", labelColumn: "name" },+ Department: { table: "department", labelColumn: "name" },+ Employee: { table: "employeeSummary", labelColumn: "name" },+ CustomerType: { table: "customerType", labelColumn: "name" },+ SupplierType: { table: "supplierType", labelColumn: "name" },+ ItemPostingGroup: { table: "itemPostingGroup", labelColumn: "name" },+ CostCenter: { table: "costCenter", labelColumn: "name" },+ FixedAssetClass: { table: "fixedAssetClass", labelColumn: "name" },+ Customer: { table: "customer", labelColumn: "name" },+ Supplier: { table: "supplier", labelColumn: "name" },+ Item: { table: "item", labelColumn: "readableIdWithRevision" },+ WorkCenter: { table: "workCenter", labelColumn: "name" },+ Process: { table: "process", labelColumn: "name" }+};++/**+ * Resolve the READABLE labels for a set of dimension values, keyed+ * `<dimensionId>:<valueId>`. The dimension's entityType picks the source+ * table (see DIMENSION_LABEL_SOURCES); Custom dimensions resolve through+ * `dimensionValue`. Values whose entity row no longer exists are simply+ * absent from the result (the caller degrades: unmapped → warn/drop).+ * Throws on DB failure — callers are syncers whose push fails loudly.+ */+export async function resolveDimensionValueLabels(+ db: Db,+ args: { values: ReadonlyArray<JournalLineDimensionRef> }+): Promise<Map<string, string>> {+ const labels = new Map<string, string>();+ if (args.values.length === 0) return labels;++ const dimensionIds = [...new Set(args.values.map((v) => v.dimensionId))];+ const dimensions = await db+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("id", "in", dimensionIds)+ .execute();+ const entityTypeByDimensionId = new Map(+ dimensions.map((dimension) => [dimension.id, String(dimension.entityType)])+ );++ // Group value ids per entityType (one query per source table)+ const valueIdsByEntityType = new Map<string, Set<string>>();+ for (const value of args.values) {+ const entityType = entityTypeByDimensionId.get(value.dimensionId);+ if (!entityType) continue;+ let ids = valueIdsByEntityType.get(entityType);+ if (!ids) {+ ids = new Set<string>();+ valueIdsByEntityType.set(entityType, ids);+ }+ ids.add(value.valueId);+ }++ const labelByValueId = new Map<string, string>();+ for (const [entityType, ids] of valueIdsByEntityType) {+ const source = DIMENSION_LABEL_SOURCES[entityType];+ if (!source) continue;++ const rows = await (db as Kysely<KyselyDatabase>)+ .selectFrom(source.table as never)+ .select([`${source.table}.id` as never, source.labelColumn as never])+ .where(`${source.table}.id` as never, "in" as never, [...ids] as never)+ .execute();++ for (const row of rows as Array<Record<string, unknown>>) {+ const id = row.id;+ const label = row[source.labelColumn];+ if (typeof id === "string" && typeof label === "string" && label) {+ labelByValueId.set(id, label);+ }+ }+ }++ for (const value of args.values) {+ const label = labelByValueId.get(value.valueId);+ if (label !== undefined) {+ labels.set(+ buildDimensionValueMappingEntityId(value.dimensionId, value.valueId),+ label+ );+ }+ }++ return labels;+}++/**+ * The dimensions stamped on a set of journal lines, keyed by+ * journalLine.id — the fetchLocal join every provider journal syncer+ * runs (spec: `fetchLocal` joins `journalLineDimension`).+ */+export async function loadJournalLineDimensions(+ db: Db,+ args: { companyId: string; journalLineIds: ReadonlyArray<string> }+): Promise<Map<string, JournalLineDimensionRef[]>> {+ const byLine = new Map<string, JournalLineDimensionRef[]>();+ if (args.journalLineIds.length === 0) return byLine;++ const rows = await db+ .selectFrom("journalLineDimension")+ .select(["journalLineId", "dimensionId", "valueId"])+ .where("companyId", "=", args.companyId)+ .where("journalLineId", "in", [...args.journalLineIds])+ .orderBy("dimensionId", "asc")+ .execute();++ for (const row of rows) {+ const existing = byLine.get(row.journalLineId);+ const ref = { dimensionId: row.dimensionId, valueId: row.valueId };+ if (existing) {+ existing.push(ref);+ } else {+ byLine.set(row.journalLineId, [ref]);+ }+ }++ return byLine;+}++/**+ * Distinct dimension values present on POSTED journal lines for the+ * slot-configured dimensions, minus already-mapped values, with resolved+ * labels — the settings UI's unmapped-first value-mapping table source.+ */+export async function getUnmappedSlottedDimensionValues(+ db: Db,+ args: {+ companyId: string;+ integration: string;+ slots: ReadonlyArray<Pick<PostingSyncDimensionSlot, "dimensionId">>;+ }+): Promise<{ data: DimensionValueWithLabel[] | null; error: string | null }> {+ try {+ const slottedDimensionIds = [+ ...new Set(args.slots.map((slot) => slot.dimensionId))+ ];+ if (slottedDimensionIds.length === 0) {+ return { data: [], error: null };+ }++ const rows = await db+ .selectFrom("journalLineDimension as jld")+ .innerJoin("journalLine as jl", "jl.id", "jld.journalLineId")+ .innerJoin("journal as j", "j.id", "jl.journalId")+ .select(["jld.dimensionId", "jld.valueId"])+ .distinct()+ .where("jld.companyId", "=", args.companyId)+ .where("j.companyId", "=", args.companyId)+ .where("j.status", "=", "Posted")+ .where("jld.dimensionId", "in", slottedDimensionIds)+ .execute();++ const mappings = await getDimensionValueMappings(db, {+ companyId: args.companyId,+ integration: args.integration+ });+ if (mappings.error) {+ return { data: null, error: mappings.error };+ }+ const mapped = buildDimensionValueMappingLookup(mappings.data ?? []);++ const unmapped: JournalLineDimensionRef[] = rows+ .map((row) => ({ dimensionId: row.dimensionId, valueId: row.valueId }))+ .filter(+ (value) =>+ !mapped.get(+ buildDimensionValueMappingEntityId(value.dimensionId, value.valueId)+ )+ );++ const labels = await resolveDimensionValueLabels(db, { values: unmapped });++ const data = unmapped+ .map((value) => ({+ ...value,+ label:+ labels.get(+ buildDimensionValueMappingEntityId(value.dimensionId, value.valueId)+ ) ?? null+ }))+ .sort(+ (a, b) =>+ a.dimensionId.localeCompare(b.dimensionId) ||+ (a.label ?? "").localeCompare(b.label ?? "")+ );++ return { data, error: null };+ } catch (err) {+ return { data: null, error: toErrorMessage(err) };+ }+}++// /********************************************************\+// * Slot-config validation *+// \********************************************************/++/**+ * Validate a dimension-slot configuration against the provider's declared+ * targets. Errors (empty = valid): a dimension slotted more than once, a+ * target the provider does not declare, a target used beyond its capacity+ * (default 1), and more slots than the provider's structural cap.+ */+export function validateDimensionSlots(args: {+ slots: ReadonlyArray<+ Pick<PostingSyncDimensionSlot, "dimensionId" | "target">+ >;+ targets: ReadonlyArray<DimensionTarget>;+ /** ProviderCapabilities.maxJournalDimensionSlots (or a provider constant). */+ maxSlots?: number;+}): string[] {+ const errors: string[] = [];++ if (args.maxSlots !== undefined && args.slots.length > args.maxSlots) {+ errors.push(+ `Too many dimension slots: ${args.slots.length} configured, the provider supports at most ${args.maxSlots}.`+ );+ }++ const targetsById = new Map(+ args.targets.map((target) => [target.id, target])+ );++ const slotCountByDimension = new Map<string, number>();+ const slotCountByTarget = new Map<string, number>();+ for (const slot of args.slots) {+ slotCountByDimension.set(+ slot.dimensionId,+ (slotCountByDimension.get(slot.dimensionId) ?? 0) + 1+ );+ slotCountByTarget.set(+ slot.target,+ (slotCountByTarget.get(slot.target) ?? 0) + 1+ );+ if (!targetsById.has(slot.target)) {+ errors.push(+ `Unknown provider target "${slot.target}" — the provider does not offer it.`+ );+ }+ }++ for (const [dimensionId, count] of slotCountByDimension) {+ if (count > 1) {+ errors.push(+ `Dimension ${dimensionId} is slotted ${count} times; each dimension may map to at most one provider target.`+ );+ }+ }++ for (const [targetId, count] of slotCountByTarget) {+ const target = targetsById.get(targetId);+ if (!target) continue;+ const capacity = target.capacity ?? 1;+ if (count > capacity) {+ errors.push(+ `Provider target "${targetId}" is used by ${count} slots; it supports at most ${capacity}.`+ );+ }+ }++ return errors;+}++/**+ * Effective autoCreate for a slot: the stored flag when present, else the+ * provider default (Rillet: true — Field-value upsert is the expected+ * flow; QBO/Xero: false — opt-in avoids surprise writes).+ */+export function resolveDimensionSlotAutoCreate(+ slot: Pick<PostingSyncDimensionSlot, "autoCreate">,+ providerDefault: boolean+): boolean {+ return slot.autoCreate ?? providerDefault;+}++// /********************************************************\+// * autoCreate orchestration (per push) *+// \********************************************************/++/**+ * Ensure every slotted dimension value on the journal's lines has a+ * provider option id, creating missing provider options BY NAME for+ * autoCreate slots. Provider-agnostic: the caller injects the provider+ * write (`createExternalValue`) and the mapping persist; `mappings` is+ * updated IN PLACE so the subsequent pre-flight and mapper see the new+ * ids. Values whose label cannot be resolved (source entity deleted) are+ * left unmapped — the warn/drop policy handles them downstream.+ */+export async function ensureDimensionValueExternalIds(args: {+ lines: ReadonlyArray<{+ dimensions?: JournalLineDimensionRef[] | null;+ }>;+ slots: ReadonlyArray<PostingSyncDimensionSlot>;+ /** Provider default for slots without an explicit autoCreate flag. */+ defaultAutoCreate: boolean;+ /** `<dimensionId>:<valueId>` → provider option id; mutated in place. */+ mappings: Map<string, string>;+ resolveLabels: (+ values: ReadonlyArray<JournalLineDimensionRef>+ ) => Promise<Map<string, string>>;+ /** Create the provider option by NAME; returns its provider id. */+ createExternalValue: (+ slot: PostingSyncDimensionSlot,+ label: string+ ) => Promise<string>;+ persistMapping: (+ value: JournalLineDimensionRef,+ externalId: string,+ label: string+ ) => Promise<void>;+}): Promise<{+ created: Array<+ JournalLineDimensionRef & { externalId: string; label: string }+ >;+}> {+ const created: Array<+ JournalLineDimensionRef & { externalId: string; label: string }+ > = [];++ const autoCreateSlotsByDimension = new Map<+ string,+ PostingSyncDimensionSlot+ >();+ for (const slot of args.slots) {+ if (resolveDimensionSlotAutoCreate(slot, args.defaultAutoCreate)) {+ autoCreateSlotsByDimension.set(slot.dimensionId, slot);+ }+ }+ if (autoCreateSlotsByDimension.size === 0) return { created };++ // Distinct unmapped values on autoCreate slots+ const pending = new Map<string, JournalLineDimensionRef>();+ for (const line of args.lines) {+ for (const dimension of line.dimensions ?? []) {+ if (!autoCreateSlotsByDimension.has(dimension.dimensionId)) continue;+ const key = buildDimensionValueMappingEntityId(+ dimension.dimensionId,+ dimension.valueId+ );+ if (args.mappings.get(key)) continue;+ if (!pending.has(key)) {+ pending.set(key, {+ dimensionId: dimension.dimensionId,+ valueId: dimension.valueId+ });+ }+ }+ }+ if (pending.size === 0) return { created };++ const labels = await args.resolveLabels([...pending.values()]);++ for (const [key, value] of pending) {+ const label = labels.get(key);+ if (!label) continue; // unresolvable → warn/drop downstream++ const slot = autoCreateSlotsByDimension.get(value.dimensionId);+ if (!slot) continue;++ const externalId = await args.createExternalValue(slot, label);+ await args.persistMapping(value, externalId, label);+ args.mappings.set(key, externalId);+ created.push({ ...value, externalId, label });+ }++ return { created };+}diff --git a/packages/ee/src/accounting/core/document-costing.test.ts b/packages/ee/src/accounting/core/document-costing.test.tsnew file mode 100644index 0000000000..1128b0a83e--- /dev/null+++ b/packages/ee/src/accounting/core/document-costing.test.ts@@ -0,0 +1,249 @@+import { describe, expect, it } from "vitest";+import {+ type CostingLine,+ loadBillCostingLines,+ toTransactionCurrencyLines+} from "./document-costing";++/**+ * Table-dispatching Kysely fake for loadBillCostingLines. Each configured+ * table resolves `execute()` / `executeTakeFirst()` to its rows; the chain+ * methods are no-ops that return the same builder.+ */+function makeDb(tables: {+ purchaseInvoice?: { currencyCode: string; exchangeRate: number } | null;+ journalLine?: Array<{+ id: string;+ accountId: string | null;+ amount: number;+ description: string | null;+ documentLineReference: string | null;+ accountClass: string | null;+ }>;+ journalLineDimension?: Array<{+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ }>;+ purchaseOrderLine?: Array<{+ poLineId: string;+ itemId: string;+ code: string | null;+ name: string | null;+ }>;+}) {+ const makeBuilder = (table: string) => {+ const builder: any = {+ select: () => builder,+ innerJoin: () => builder,+ leftJoin: () => builder,+ where: () => builder,+ orderBy: () => builder,+ async execute() {+ if (table === "journalLine") return tables.journalLine ?? [];+ if (table === "journalLineDimension")+ return tables.journalLineDimension ?? [];+ if (table === "purchaseOrderLine")+ return tables.purchaseOrderLine ?? [];+ return [];+ },+ async executeTakeFirst() {+ if (table === "purchaseInvoice")+ return tables.purchaseInvoice ?? undefined;+ return undefined;+ }+ };+ return builder;+ };+ return { selectFrom: (t: string) => makeBuilder(t) } as never;+}++describe("loadBillCostingLines", () => {+ it("excludes the AP control line, base-currency debit-signed amounts", async () => {+ const db = makeDb({+ purchaseInvoice: { currencyCode: "USD", exchangeRate: 1 },+ journalLine: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300, // Asset/Expense: natural balance is debit+ description: "GR/IR Clearing",+ documentLineReference: null,+ accountClass: "Asset"+ },+ {+ id: "jl-2",+ accountId: "acct_ap",+ amount: 300, // Liability natural balance → debit-signed negates+ description: "Accounts Payable",+ documentLineReference: null,+ accountClass: "Liability"+ }+ ]+ });++ const result = await loadBillCostingLines(db, {+ companyId: "company-1",+ billId: "pi_1",+ payablesAccountId: "acct_ap"+ });++ expect(result.currencyCode).toBe("USD");+ expect(result.exchangeRate).toBe(1);+ expect(result.lines).toEqual([+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR Clearing"+ }+ ]);+ });++ it("attaches sourceItem for PO-backed lines and leaves variance lines bare", async () => {+ const db = makeDb({+ purchaseInvoice: { currencyCode: "USD", exchangeRate: 1 },+ journalLine: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 280,+ description: "GR/IR Clearing",+ documentLineReference: "purchase-invoice:pol-1",+ accountClass: "Asset"+ },+ {+ id: "jl-2",+ accountId: "acct_ppv",+ amount: 20,+ description: "Purchase Price Variance",+ documentLineReference: null,+ accountClass: "Expense"+ },+ {+ id: "jl-3",+ accountId: "acct_ap",+ amount: 300,+ description: "Accounts Payable",+ documentLineReference: null,+ accountClass: "Liability"+ }+ ],+ purchaseOrderLine: [+ {+ poLineId: "pol-1",+ itemId: "item-1",+ code: "WIDGET-1",+ name: "Widget"+ }+ ]+ });++ const result = await loadBillCostingLines(db, {+ companyId: "company-1",+ billId: "pi_1",+ payablesAccountId: "acct_ap"+ });++ expect(result.lines).toEqual([+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 280,+ description: "GR/IR Clearing",+ sourceItem: { id: "item-1", code: "WIDGET-1", name: "Widget" }+ },+ {+ id: "jl-2",+ accountId: "acct_ppv",+ amount: 20,+ description: "Purchase Price Variance"+ }+ ]);+ });++ it("carries journal line dimensions onto costing lines", async () => {+ const db = makeDb({+ purchaseInvoice: { currencyCode: "USD", exchangeRate: 1 },+ journalLine: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 100,+ description: "GR/IR",+ documentLineReference: null,+ accountClass: "Asset"+ }+ ],+ journalLineDimension: [+ { journalLineId: "jl-1", dimensionId: "dim_loc", valueId: "loc_hq" }+ ]+ });++ const result = await loadBillCostingLines(db, {+ companyId: "company-1",+ billId: "pi_1",+ payablesAccountId: "acct_ap"+ });++ expect(result.lines[0]?.dimensions).toEqual([+ { dimensionId: "dim_loc", valueId: "loc_hq" }+ ]);+ });++ it("returns no lines when the bill has no posted journal", async () => {+ const db = makeDb({+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 1.1 },+ journalLine: []+ });++ const result = await loadBillCostingLines(db, {+ companyId: "company-1",+ billId: "pi_1",+ payablesAccountId: "acct_ap"+ });++ expect(result.lines).toEqual([]);+ expect(result.currencyCode).toBe("EUR");+ expect(result.exchangeRate).toBe(1.1);+ });+});++describe("toTransactionCurrencyLines", () => {+ const line = (id: string, amount: number): CostingLine => ({+ id,+ accountId: `acct_${id}`,+ amount,+ description: id+ });++ it("passes through at rate 1", () => {+ const lines = [line("a", 280), line("b", 20)];+ expect(toTransactionCurrencyLines(lines, 1)).toEqual(lines);+ });++ it("divides by the rate and balances the residue into the largest line", () => {+ // base 100 @ rate 3 → 33.3333; base 10 @ rate 3 → 3.3333.+ // rounded: 33.33 + 3.33 = 36.66; target round(110/3)=36.67; residue +0.01+ // to the largest-|amount| line (a).+ const converted = toTransactionCurrencyLines(+ [line("a", 100), line("b", 10)],+ 3+ );+ expect(converted.map((l) => l.amount)).toEqual([33.34, 3.33]);+ const sum = converted.reduce((s, l) => s + Math.round(l.amount * 100), 0);+ expect(sum).toBe(Math.round((110 / 3) * 100));+ });++ it("preserves negative (credit variance) amounts", () => {+ const converted = toTransactionCurrencyLines(+ [line("a", 300), line("ppv", -20)],+ 2+ );+ expect(converted.map((l) => l.amount)).toEqual([150, -10]);+ });++ it("returns [] for empty input", () => {+ expect(toTransactionCurrencyLines([], 1.5)).toEqual([]);+ });+});diff --git a/packages/ee/src/accounting/core/document-costing.ts b/packages/ee/src/accounting/core/document-costing.tsnew file mode 100644index 0000000000..b3fdce730e--- /dev/null+++ b/packages/ee/src/accounting/core/document-costing.ts@@ -0,0 +1,255 @@+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";+import { loadJournalLineDimensions } from "./dimension-mapping";+import {+ type JournalLineDimensionRef,+ roundCurrency,+ toDebitSignedAmount+} from "./posting";++type Db = Kysely<KyselyDatabase> | KyselyTx;++/**+ * Shared bill-costing core (spec: accounting-document-representation).+ *+ * Every AP bill Carbon pushes to a provider reproduces the accounts its+ * posted "Purchase Invoice" journal computed (GR/IR clearing, price+ * variance, tax folded into cost) — NOT the item's account. The item is a+ * description label only. This module extracts the journal read + AP-control+ * filter that Rillet pioneered so QBO and Xero can share it.+ *+ * A `CostingLine` carries base-currency, debit-signed amounts (positive =+ * debit). Providers convert to the invoice's transaction currency with+ * `toTransactionCurrencyLines` and pin the provider exchange rate.+ */++/** The Carbon-native prefix stamped on `journalLine.documentLineReference`+ * for purchase-invoice lines — `purchase-invoice:<purchaseOrderLineId>`+ * (see `functions/lib/utils.ts` journalReference.to.purchaseInvoice). Direct+ * no-PO invoice lines carry NULL, so they never resolve to a source item. */+const PURCHASE_INVOICE_LINE_REFERENCE_PREFIX = "purchase-invoice:";++/** The source item behind a costing line, resolved via the purchase-order+ * line the journal line references. Absent for direct no-PO lines and for+ * variance/rounding/tax lines (which have no item reference). */+export type CostingLineSourceItem = {+ id: string;+ code: string | null;+ name: string | null;+};++/**+ * One account-costed line of a bill's posted Purchase Invoice journal (AP+ * control line excluded). `amount` is base-currency and debit-signed.+ */+export type CostingLine = {+ id: string;+ accountId: string | null;+ /** Base-currency, debit-signed (positive = debit, negative = credit). */+ amount: number;+ description: string | null;+ /** Resolved item for a PO-backed line; undefined otherwise. */+ sourceItem?: CostingLineSourceItem;+ /** journalLineDimension rows carried onto provider dimension refs. */+ dimensions?: JournalLineDimensionRef[];+};++export type BillCostingResult = {+ /** Costing lines (AP control line excluded), base-currency, debit-signed. */+ lines: CostingLine[];+ /** The invoice's transaction currency (ISO-4217). */+ currencyCode: string;+ /** Base-per-transaction exchange rate (1 for base-currency bills). */+ exchangeRate: number;+};++/**+ * Load a bill's account-costed replay lines from its posted "Purchase+ * Invoice" journal: the journal's lines minus the AP control line ARE the+ * bill's costing (item-backed invoice lines carry no account of their own;+ * posting resolves GR/IR clearing, variances and tax). Amounts are+ * base-currency and debit-signed. Item labels are joined through the+ * purchase-order line the journal line references+ * (`documentLineReference = purchase-invoice:<purchaseOrderLineId>`); direct+ * no-PO lines and variance lines resolve to `sourceItem: undefined`.+ *+ * Returns `lines: []` when the invoice has no posted Purchase Invoice+ * journal (not posted / accounting off) — the caller surfaces the Warning.+ */+export async function loadBillCostingLines(+ db: Db,+ args: { companyId: string; billId: string; payablesAccountId: string | null }+): Promise<BillCostingResult> {+ const invoice = await db+ .selectFrom("purchaseInvoice")+ .select(["currencyCode", "exchangeRate"])+ .where("id", "=", args.billId)+ .where("companyId", "=", args.companyId)+ .executeTakeFirst();++ const currencyCode = invoice?.currencyCode ?? "USD";+ const exchangeRate = Number(invoice?.exchangeRate) || 1;++ const rows = await db+ .selectFrom("journalLine")+ .innerJoin("journal", (join) =>+ join+ .onRef("journal.id", "=", "journalLine.journalId")+ .onRef("journal.companyId", "=", "journalLine.companyId")+ )+ .leftJoin("account", "account.id", "journalLine.accountId")+ .select([+ "journalLine.id",+ "journalLine.accountId",+ "journalLine.amount",+ "journalLine.description",+ "journalLine.documentLineReference",+ "account.class as accountClass"+ ])+ .where("journalLine.documentId", "=", args.billId)+ .where("journalLine.companyId", "=", args.companyId)+ .where("journal.sourceType", "=", "Purchase Invoice")+ .where("journal.status", "=", "Posted")+ .where("journal.companyId", "=", args.companyId)+ .orderBy("journalLine.journalLineReference", "asc")+ .execute();++ // AP control line(s) are re-booked by the provider's own bill mechanics —+ // exclude them; keep null-account lines (they fail preflight as unmapped).+ const costingRows = rows.filter(+ (row) => row.accountId === null || row.accountId !== args.payablesAccountId+ );++ const dimensionsByLine = await loadJournalLineDimensions(db, {+ companyId: args.companyId,+ journalLineIds: costingRows.map((row) => row.id)+ });++ // Item labels: resolve documentLineReference (purchase-invoice:<poLineId>)+ // → purchaseOrderLine.itemId → item.+ const poLineIds = new Set<string>();+ for (const row of costingRows) {+ const poLineId = parsePurchaseInvoiceLineReference(+ row.documentLineReference+ );+ if (poLineId) poLineIds.add(poLineId);+ }++ const sourceItemByPoLine = new Map<string, CostingLineSourceItem>();+ if (poLineIds.size > 0) {+ const itemRows = await db+ .selectFrom("purchaseOrderLine")+ .innerJoin("item", "item.id", "purchaseOrderLine.itemId")+ .select([+ "purchaseOrderLine.id as poLineId",+ "item.id as itemId",+ "item.readableId as code",+ "item.name as name"+ ])+ .where("purchaseOrderLine.companyId", "=", args.companyId)+ .where("purchaseOrderLine.id", "in", [...poLineIds])+ .execute();++ for (const row of itemRows) {+ sourceItemByPoLine.set(row.poLineId, {+ id: row.itemId,+ code: row.code ?? null,+ name: row.name ?? null+ });+ }+ }++ const lines: CostingLine[] = costingRows.map((row) => {+ const dimensions = dimensionsByLine.get(row.id);+ const poLineId = parsePurchaseInvoiceLineReference(+ row.documentLineReference+ );+ const sourceItem = poLineId ? sourceItemByPoLine.get(poLineId) : undefined;++ return {+ id: row.id,+ accountId: row.accountId ?? null,+ amount: toDebitSignedAmount(row.accountClass, Number(row.amount) || 0),+ description: row.description ?? null,+ ...(sourceItem ? { sourceItem } : {}),+ ...(dimensions ? { dimensions } : {})+ };+ });++ return { lines, currencyCode, exchangeRate };+}++/** The item code/name label for a costing line (`"<code> <name>"`), or null+ * when the line has no source item or the item has neither a code nor a name.+ * Providers prepend it to (Rillet) or substitute it for (QBO/Xero) the journal+ * line description so the account-costed bill line still shows what was+ * purchased. */+export function costingLineItemLabel(line: CostingLine): string | null {+ if (!line.sourceItem) return null;+ const label = [line.sourceItem.code, line.sourceItem.name]+ .filter(Boolean)+ .join(" ");+ return label.length > 0 ? label : null;+}++/** Strip the `purchase-invoice:` prefix to recover the purchase-order line+ * id; null for direct no-PO lines (NULL reference) and any other reference+ * type. */+function parsePurchaseInvoiceLineReference(+ reference: string | null+): string | null {+ if (!reference) return null;+ if (!reference.startsWith(PURCHASE_INVOICE_LINE_REFERENCE_PREFIX)) {+ return null;+ }+ const id = reference.slice(PURCHASE_INVOICE_LINE_REFERENCE_PREFIX.length);+ return id.length > 0 ? id : null;+}++/**+ * Convert base-currency costing lines to the invoice's transaction currency:+ * divide each amount by `exchangeRate` (base = transaction × rate), round to+ * 2dp, then book the post-rounding residue into the largest-|amount| line so+ * the lines sum exactly to the invoice's transaction-currency total. Negative+ * amounts (credit variance lines) are preserved. `exchangeRate === 1` is a+ * pass-through (base-currency bills are byte-identical).+ */+export function toTransactionCurrencyLines(+ lines: CostingLine[],+ exchangeRate: number+): CostingLine[] {+ if (exchangeRate === 1 || lines.length === 0) {+ return lines.map((line) => ({ ...line }));+ }++ const converted = lines.map((line) => ({+ ...line,+ amount: roundCurrency(line.amount / exchangeRate)+ }));++ const baseTotalCents = lines.reduce(+ (sum, line) => sum + Math.round(line.amount * 100),+ 0+ );+ const targetCents = Math.round(baseTotalCents / exchangeRate);+ const convertedCents = converted.reduce(+ (sum, line) => sum + Math.round(line.amount * 100),+ 0+ );+ const residueCents = targetCents - convertedCents;++ if (residueCents !== 0) {+ let largestIndex = 0;+ let largestMagnitude = -1;+ for (let i = 0; i < converted.length; i++) {+ const magnitude = Math.abs(converted[i]!.amount);+ if (magnitude > largestMagnitude) {+ largestMagnitude = magnitude;+ largestIndex = i;+ }+ }+ const target = converted[largestIndex]!;+ target.amount = roundCurrency(target.amount + residueCents / 100);+ }++ return converted;+}diff --git a/packages/ee/src/accounting/core/external-mapping.ts b/packages/ee/src/accounting/core/external-mapping.tsindex 6fc0af0d3b..d1590bfc3a 100644--- a/packages/ee/src/accounting/core/external-mapping.ts+++ b/packages/ee/src/accounting/core/external-mapping.ts@@ -283,13 +283,18 @@ export class ExternalIntegrationMappingService {async touchLastSyncedAt(entityType: string,entityId: string,- integration: string+ integration: string,+ remoteUpdatedAt?: Date): Promise<void> {+ const now = new Date().toISOString();await this.db.updateTable("externalIntegrationMapping").set({- lastSyncedAt: new Date().toISOString(),- updatedAt: new Date().toISOString()+ lastSyncedAt: now,+ updatedAt: now,+ ...(remoteUpdatedAt+ ? { remoteUpdatedAt: remoteUpdatedAt.toISOString() }+ : {})}).where("entityType", "=", entityType).where("entityId", "=", entityId)diff --git a/packages/ee/src/accounting/core/models.ts b/packages/ee/src/accounting/core/models.tsindex f0856a18b8..33a4d2fa64 100644--- a/packages/ee/src/accounting/core/models.ts+++ b/packages/ee/src/accounting/core/models.ts@@ -1,3 +1,4 @@+import type { Database } from "@carbon/database";import z from "zod";import type {AccountingEntity,@@ -11,8 +12,9 @@ function withNullable<T extends z.ZodTypeAny>(schema: T) {}export enum ProviderID {- XERO = "xero"- // QUICKBOOKS = "quickbooks"+ XERO = "xero",+ QUICKBOOKS = "quickbooks",+ RILLET = "rillet"// SAGE = "sage",}@@ -27,11 +29,77 @@ export const ProviderCredentialsSchema = z.discriminatedUnion("type", [refreshToken: z.string().optional(),expiresAt: z.string().datetime().optional(),scope: z.array(z.string()).optional(),- tenantId: z.string().optional(),- tenantName: z.string().optional()+ providerMetadata: z.record(z.string(), z.unknown()).optional() // xero: { tenantId, tenantName }; qbo: { realmId }+ }),+ z.object({+ type: z.literal("apiKey"),+ apiKey: z.string().min(1),+ /** Which host the key belongs to — API keys are environment-specific. */+ environment: z.enum(["production", "sandbox"]).default("production"),+ // rillet: { subsidiaryId?, webhookToken? }+ providerMetadata: z.record(z.string(), z.unknown()).optional()+ }),+ z.object({+ type: z.literal("bridge"),+ vendor: z.string(), // e.g. "conductor"+ externalConnectionId: z.string() // e.g. Conductor end-user id})]);+/**+ * Legacy stored oauth2 credentials kept provider-specific fields+ * (`tenantId`/`tenantName`) at the top level. Fold them into+ * `providerMetadata` before parsing — zod strips unknown keys, so parsing+ * the flat shape directly against the union would silently drop the tenant.+ */+function normalizeStoredCredentials(raw: unknown): unknown {+ if (+ typeof raw !== "object" ||+ raw === null ||+ (raw as Record<string, unknown>).type !== "oauth2" ||+ (!("tenantId" in raw) && !("tenantName" in raw))+ ) {+ return raw;+ }++ const { tenantId, tenantName, providerMetadata, ...rest } = raw as Record<+ string,+ unknown+ >;++ return {+ ...rest,+ providerMetadata: {+ ...(tenantId !== undefined ? { tenantId } : {}),+ ...(tenantName !== undefined ? { tenantName } : {}),+ ...(typeof providerMetadata === "object" && providerMetadata !== null+ ? providerMetadata+ : {})+ }+ };+}++/**+ * Credentials as they are stored on `companyIntegration.metadata` — reads the+ * new discriminated union, transparently upgrading the legacy flat oauth2+ * shape. Writes always use the new shape.+ */+export const StoredProviderCredentialsSchema = z.preprocess(+ normalizeStoredCredentials,+ ProviderCredentialsSchema+);++/**+ * Parse credentials read from storage. Accepts the new union and the legacy+ * flat oauth2 shape (mapped into `providerMetadata`). Throws if neither+ * parses.+ */+export function parseStoredCredentials(+ raw: unknown+): z.output<typeof ProviderCredentialsSchema> {+ return StoredProviderCredentialsSchema.parse(raw);+}+/*** Direction of data flow.*/@@ -110,13 +178,25 @@ export const ENTITY_DEFINITIONS: Record<label: "Payments",type: "transaction",dependsOn: ["invoice", "bill"],- supportedDirections: ["pull-from-accounting"]+ // Two-way: provider-recorded payments pull back (Phase F), and Carbon-born+ // Posted payments push out as provider payment documents (Phase G). Routing+ // is per-record by origin (the payment mapping), not a static direction.+ supportedDirections: [+ "two-way",+ "pull-from-accounting",+ "push-to-accounting"+ ]},inventoryAdjustment: {label: "Inventory Adjustments",type: "transaction",dependsOn: ["item"],supportedDirections: ["push-to-accounting"]+ },+ journalEntry: {+ label: "Journal Entries",+ type: "transaction",+ supportedDirections: ["push-to-accounting"]}};@@ -158,10 +238,394 @@ export const DEFAULT_SYNC_CONFIG: GlobalSyncConfig = {enabled: false,direction: "push-to-accounting",owner: "carbon"+ },+ journalEntry: {+ // Always-on: automated postings ARE the sync (the always-on model) —+ // connecting an accounting integration means Carbon's automated GL+ // postings mirror to it. Manual journals are excluded by POSTING_POLICY+ // (syncable: false), not by this flag.+ enabled: true,+ direction: "push-to-accounting",+ owner: "carbon"}}};+// /********************************************************\+// * Posting Sync (journalEntry) *+// \********************************************************/++export type JournalEntrySourceType =+ Database["public"]["Enums"]["journalEntrySourceType"];++/** How a source type CAN be represented in the provider (structural). */+export type JournalRepresentation = "journal" | "document";++export type PostingGranularity = "individual" | "daily-summary";++/**+ * Which per-company family setting decides a document-represented type:+ * AR (invoice-side), AP (bill-side), or resolved per journal from its+ * control-account lines (Payment spans both sides).+ */+export type PostingSourceFamily = "ar" | "ap" | "per-line";++export type PostingPolicyEntry = {+ representation: JournalRepresentation;+ /** Only document-represented types carry a family. */+ family?: PostingSourceFamily;+ /**+ * For document-represented types: the entity whose DOCUMENT sync carries+ * the journal's amounts into the provider ("invoice" | "bill" | "payment"),+ * or null when no document representation exists yet (memos/returns) —+ * those park loudly in documents mode instead of excluding silently.+ */+ backingEntityType?: "invoice" | "bill" | "payment" | null;+ /**+ * `false` ONLY for `Manual` — manual journals are NEVER synced in any engine.+ * They can touch arbitrary/unmapped accounts, and the external ledger owns+ * manual journals (payroll, etc.); Carbon syncs only its automated postings.+ * Omitted ⇒ syncable (every automated posting type).+ */+ syncable?: boolean;+ defaultEnabled: boolean;+ defaultGranularity: PostingGranularity;+};++/**+ * The total posting policy: EVERY "journalEntrySourceType" enum value has a+ * row (Record<> makes omission a compile error — adding an enum value+ * without deciding its policy breaks typecheck, not production).+ * Spec: .ai/specs/2026-08-02-accounting-sync-engine-v3.md §2.+ */+export const POSTING_POLICY: Record<+ JournalEntrySourceType,+ PostingPolicyEntry+> = {+ Manual: {+ representation: "journal",+ syncable: false,+ defaultEnabled: false,+ defaultGranularity: "individual"+ },+ "Purchase Receipt": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Transfer Receipt": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Sales Shipment": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Inventory Adjustment": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Production Order": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Production Event": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "daily-summary"+ },+ "Job Consumption": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "daily-summary"+ },+ "Job Receipt": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Job Close": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Asset Depreciation": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Asset Disposal": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Non-Conformance": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Inbound Inspection": {+ representation: "journal",+ defaultEnabled: true,+ defaultGranularity: "individual"+ },+ "Sales Invoice": {+ representation: "document",+ family: "ar",+ backingEntityType: "invoice",+ defaultEnabled: false,+ defaultGranularity: "individual"+ },+ "Credit Memo": {+ representation: "document",+ family: "ar",+ backingEntityType: null,+ defaultEnabled: false,+ defaultGranularity: "individual"+ },+ "Sales Return": {+ representation: "document",+ family: "ar",+ backingEntityType: null,+ defaultEnabled: false,+ defaultGranularity: "individual"+ },+ "Purchase Invoice": {+ representation: "document",+ family: "ap",+ backingEntityType: "bill",+ defaultEnabled: false,+ defaultGranularity: "individual"+ },+ "Debit Memo": {+ representation: "document",+ family: "ap",+ backingEntityType: null,+ defaultEnabled: false,+ defaultGranularity: "individual"+ },+ "Purchase Return": {+ representation: "document",+ family: "ap",+ backingEntityType: null,+ defaultEnabled: false,+ defaultGranularity: "individual"+ },+ Payment: {+ representation: "document",+ family: "per-line",+ backingEntityType: "payment",+ defaultEnabled: false,+ defaultGranularity: "individual"+ }+};++export const JOURNAL_ENTRY_SOURCE_TYPES = Object.keys(+ POSTING_POLICY+) as JournalEntrySourceType[];++/**+ * Machine reasons recorded on terminal `Excluded` operations — the policy+ * decided a posted journal is not pushed as a journal, and why.+ */+export const POSTING_DECISION_REASON_CODES = [+ "DOC_BACKED",+ "FAMILY_OFF",+ "SOURCE_TYPE_DISABLED",+ "MANUAL_DISABLED"+] as const;++export type PostingDecisionReasonCode =+ (typeof POSTING_DECISION_REASON_CODES)[number];++/**+ * @deprecated Derived from POSTING_POLICY (journal-represented types enabled+ * by default). Read the policy directly for new code.+ */+export const POSTING_SYNC_DEFAULT_SOURCE_TYPES =+ JOURNAL_ENTRY_SOURCE_TYPES.filter(+ (sourceType) =>+ POSTING_POLICY[sourceType].representation === "journal" &&+ POSTING_POLICY[sourceType].defaultEnabled+ );++/**+ * @deprecated Derived from POSTING_POLICY (document-represented types).+ * Whether a document-represented journal is DOC_BACKED, parked, or pushed+ * now depends on the company's family representation setting — read the+ * policy + settings through getJournalPostingPolicyDecision instead.+ */+export const POSTING_SYNC_EXCLUDED_SOURCE_TYPES =+ JOURNAL_ENTRY_SOURCE_TYPES.filter(+ (sourceType) => POSTING_POLICY[sourceType].representation === "document"+ );++export const PostingSyncFamilyModeSchema = z.enum([+ "documents",+ "journals",+ "none"+]);++export type PostingSyncFamilyMode = z.infer<typeof PostingSyncFamilyModeSchema>;++export const PostingSyncGranularitySchema = z.enum([+ "individual",+ "daily-summary"+]);++export const PostingSyncDimensionSlotSchema = z.object({+ dimensionId: z.string(),+ /** Provider-specific target id (e.g. "class", "tracking:<id>", "field:<id>"). */+ target: z.string(),+ /**+ * Create missing provider options by name at push time. Optional so a+ * stored slot without the flag resolves to the PROVIDER default at the+ * point of use (Rillet: on — Field-value upsert is the expected flow;+ * QBO/Xero: off — opt-in avoids surprise writes to their lists). See+ * resolveDimensionSlotAutoCreate (core/dimension-mapping.ts).+ */+ autoCreate: z.boolean().optional()+});++export type PostingSyncDimensionSlot = z.infer<+ typeof PostingSyncDimensionSlotSchema+>;++const PostingSyncSourceTypeConfigSchema = z.object({+ enabled: z.boolean(),+ granularity: PostingSyncGranularitySchema+});++/**+ * Upgrade a stored v2 posting-sync fragment (flat `sourceTypes: string[]`,+ * global `consolidation`, `includeManual`) to the v3 per-source-type shape.+ * Behavior parity: the v2 enabled set carries over exactly, the global+ * consolidation becomes every type's granularity, and `includeManual` maps+ * to `sourceTypes.Manual.enabled`. v3 fragments pass through untouched.+ * Write-back in the new shape happens on the next settings save.+ */+function normalizeStoredPostingSyncSettings(raw: unknown): unknown {+ if (typeof raw !== "object" || raw === null) return raw;+ const record = raw as Record<string, unknown>;++ const isV2 =+ Array.isArray(record.sourceTypes) ||+ "consolidation" in record ||+ "includeManual" in record;+ if (!isV2) return raw;++ const enabledList = Array.isArray(record.sourceTypes)+ ? record.sourceTypes.filter((v): v is string => typeof v === "string")+ : (POSTING_SYNC_DEFAULT_SOURCE_TYPES as readonly string[]);+ const granularity =+ record.consolidation === "daily" ? "daily-summary" : "individual";++ const sourceTypes: Record<string, { enabled: boolean; granularity: string }> =+ {};+ for (const sourceType of JOURNAL_ENTRY_SOURCE_TYPES) {+ const policy = POSTING_POLICY[sourceType];+ const enabled =+ sourceType === "Manual"+ ? record.includeManual === true+ : policy.representation === "journal" &&+ enabledList.includes(sourceType);+ sourceTypes[sourceType] = { enabled, granularity };+ }++ const {+ consolidation: _consolidation,+ includeManual: _includeManual,+ sourceTypes: _sourceTypes,+ ...rest+ } = record;+ return { ...rest, sourceTypes };+}++const PostingSyncStoredSchema = z.object({+ /**+ * Kept for backward-compatible parsing of stored fragments ONLY (D2:+ * keep-but-ignore). The decision core no longer reads it — posting sync is+ * always-on when an accounting integration is connected.+ */+ enabled: z.boolean().default(true),+ syncFromDate: z.string().optional(),+ /**+ * AR/AP family representation (spec §2): documents (default — native+ * provider documents; journals are DOC_BACKED), journals (documents NOT+ * pushed; the journals push, forced individual), none (explicit opt-out —+ * journals record FAMILY_OFF). Explicit, never derived from entity sync+ * toggles.+ */+ families: z+ .object({+ ar: PostingSyncFamilyModeSchema.default("documents"),+ ap: PostingSyncFamilyModeSchema.default("documents")+ })+ .default({ ar: "documents", ap: "documents" }),+ /** Partial per-source-type overrides; missing entries fill from POSTING_POLICY. */+ sourceTypes: z+ .record(z.string(), PostingSyncSourceTypeConfigSchema)+ .default({}),+ /** Dimension slot config (Phase 2) — empty until dimension sync ships. */+ dimensionSlots: z.array(PostingSyncDimensionSlotSchema).default([]),+ onUnmappedDimensionValue: z.enum(["warn", "drop"]).default("warn"),+ /** park = journals dated in a locked period land Warning; redate = push at lock date + 1 with the original date in the narration. */+ periodLockPolicy: z.enum(["park", "redate"]).default("park"),+ /** Manually captured provider lock date (YYYY-MM-DD) — required for providers whose API cannot report it (QBO); merged with the provider-reported lock date when both exist. */+ lockDate: z.string().optional()+});++/**+ * Per-company posting-sync settings fragment stored at+ * `companyIntegration.metadata.settings.postingSync`. Resolved with+ * `resolvePostingSyncSettings` (core/posting.ts) — never parsed directly+ * from storage, and a bad stored fragment must never break sync. Reads the+ * v3 shape, transparently upgrading stored v2 fragments (see+ * normalizeStoredPostingSyncSettings). The output's `sourceTypes` is TOTAL+ * over the enum (missing entries filled from POSTING_POLICY).+ *+ * `consolidation` in the output is a transitional derived field for the+ * drain/cron hold: "daily" only when every enabled journal-represented type+ * is daily-summary (pure v2-daily shims). Removed once the per-granularity+ * claim filter lands (plan task 1.5).+ */+export const PostingSyncSettingsSchema = z.preprocess(+ normalizeStoredPostingSyncSettings,+ PostingSyncStoredSchema.transform((value) => {+ const sourceTypes = {} as Record<+ JournalEntrySourceType,+ z.infer<typeof PostingSyncSourceTypeConfigSchema>+ >;+ for (const sourceType of JOURNAL_ENTRY_SOURCE_TYPES) {+ sourceTypes[sourceType] = value.sourceTypes[sourceType] ?? {+ enabled: POSTING_POLICY[sourceType].defaultEnabled,+ granularity: POSTING_POLICY[sourceType].defaultGranularity+ };+ }++ // Always-on: the set of syncing journal types is defined by POSTING_POLICY+ // (journal-represented, non-Manual), never by stored per-type enables.+ const enabledJournalTypes = JOURNAL_ENTRY_SOURCE_TYPES.filter(+ (sourceType) =>+ POSTING_POLICY[sourceType].representation === "journal" &&+ POSTING_POLICY[sourceType].syncable !== false+ );+ const consolidation: "individual" | "daily" =+ enabledJournalTypes.length > 0 &&+ enabledJournalTypes.every(+ (sourceType) => sourceTypes[sourceType].granularity === "daily-summary"+ )+ ? "daily"+ : "individual";++ return { ...value, sourceTypes, consolidation };+ })+);+// ============================================================================// 4. VALIDATION LOGIC// ============================================================================@@ -226,7 +690,8 @@ export const SyncConfigSchema = zsalesOrder: createEntityConfigSchema().optional(),invoice: createEntityConfigSchema().optional(),payment: createEntityConfigSchema().optional(),- inventoryAdjustment: createEntityConfigSchema().optional()+ inventoryAdjustment: createEntityConfigSchema().optional(),+ journalEntry: createEntityConfigSchema().optional()}).optional()})@@ -234,13 +699,140 @@ export const SyncConfigSchema = zexport const ProviderIntegrationMetadataSchema = z.object({syncConfig: SyncConfigSchema.optional(),- credentials: ProviderCredentialsSchema.optional(),+ credentials: StoredProviderCredentialsSchema.optional(),+ // Per-company integration settings (e.g. settings.postingSync). Kept as a+ // permissive record so parsing never strips or rewrites stored keys —+ // fragments are validated where they are consumed (resolvePostingSyncSettings)+ settings: z.record(z.string(), z.unknown()).optional(),// Integration-specific settings (e.g., default account codes for Xero)// These are stored at the top level of metadata and passed through to the providerdefaultSalesAccountCode: z.string().optional(),defaultPurchaseAccountCode: z.string().optional()});+// /********************************************************\+// * Sync Operation Schemas *+// \********************************************************/++/**+ * Status lifecycle of a sync operation (matches the "syncOperationStatus"+ * Postgres enum): Pending → In Flight → Completed | Failed | Warning |+ * Skipped | Excluded. `Excluded` is a terminal disposition decided by the+ * posting policy (doc-backed, family off, source type disabled) — recorded+ * so completeness is a query; `Skipped` remains the human opt-out.+ */+export const SyncOperationStatusSchema = z.enum([+ "Pending",+ "In Flight",+ "Completed",+ "Failed",+ "Warning",+ "Skipped",+ "Excluded"+]);++export const SyncOperationDirectionSchema = z.enum([+ "push-to-accounting",+ "pull-from-accounting"+]);++export const SyncOperationTriggerSchema = z.enum([+ "event",+ "webhook",+ "backfill",+ "manual",+ "posting",+ "retry",+ // v5: state-derived reconcile decisions (never cooldown-gated)+ "reconcile"+]);++/**+ * A row of the "accountingSyncOperation" ledger: one attempted sync of one+ * entity in one direction.+ */+export const SyncOperationSchema = z.object({+ id: z.string(),+ companyId: z.string(),+ integration: z.string(),+ entityType: z.string(),+ entityId: z.string(),+ direction: SyncOperationDirectionSchema,+ trigger: SyncOperationTriggerSchema,+ status: SyncOperationStatusSchema,+ idempotencyKey: z.string(),+ attemptCount: z.number().int(),+ lastAttemptAt: z.string().nullable(),+ completedAt: z.string().nullable(),+ errorCode: z.string().nullable(),+ errorMessage: z.string().nullable(),+ externalId: z.string().nullable(),+ metadata: z.record(z.any()).nullable(),+ createdBy: z.string(),+ createdAt: z.string(),+ updatedBy: z.string().nullable(),+ updatedAt: z.string().nullable()+});++/**+ * UI-driven status transitions: Retry (Failed/Warning/Skipped → Pending+ * — Skipped covers both a human opt-out and the drain's machine no-op+ * close, either of which a user may re-drive), Skip (Failed/Warning/+ * Pending → Skipped), Re-send (Completed/Excluded → Pending — an+ * Excluded journal re-decides against the current policy config).+ * Everything else is invalid.+ */+export const SYNC_OPERATION_ALLOWED_TRANSITIONS: Record<+ z.infer<typeof SyncOperationStatusSchema>,+ ReadonlyArray<z.infer<typeof SyncOperationStatusSchema>>+> = {+ Pending: ["Skipped"],+ "In Flight": [],+ Completed: ["Pending"],+ Failed: ["Pending", "Skipped"],+ Warning: ["Pending", "Skipped"],+ Skipped: ["Pending"],+ Excluded: ["Pending"]+};++export const SyncOperationTransitionSchema = z.object({+ id: z.string(),+ companyId: z.string(),+ to: SyncOperationStatusSchema,+ userId: z.string()+});++// /********************************************************\+// * Account Mapping Schemas *+// \********************************************************/++/**+ * An account in the provider's chart of accounts as fetched from the+ * provider API (e.g. Xero GET /Accounts). `code` is the provider-side+ * account code that matchAccountsByCode compares against Carbon+ * `account.number`.+ */+export const ProviderChartAccountSchema = z.object({+ id: z.string(),+ code: z.string().nullish(),+ name: z.string().nullish()+});++/**+ * Payload for upserting an account mapping (Carbon account.id → provider+ * account id). externalCode/externalName are stored in the mapping+ * metadata for display only — the mapping itself is by id on both sides.+ */+export const UpsertAccountMappingSchema = z.object({+ companyId: z.string(),+ integration: z.string(),+ accountId: z.string(),+ externalId: z.string(),+ externalCode: z.string().optional(),+ externalName: z.string().optional(),+ userId: z.string()+});+// /********************************************************\// * Accounting Entity Schemas *// \********************************************************/@@ -404,6 +996,8 @@ export const BillLineSchema = z.object({unitPrice: z.number(),itemId: withNullable(z.string()),itemCode: withNullable(z.string()),+ /** Carbon account.id FK — needed by providers that resolve G/L lines through the account-mapping service (QBO AccountRef). */+ accountId: withNullable(z.string()),accountNumber: withNullable(z.string()),taxPercent: withNullable(z.number()),taxAmount: withNullable(z.number()),@@ -452,6 +1046,8 @@ export const PurchaseOrderLineSchema = z.object({unitPrice: z.number(),itemId: withNullable(z.string()),itemCode: withNullable(z.string()),+ /** Carbon account.id FK — needed by providers that resolve G/L lines through the account-mapping service (QBO AccountRef). */+ accountId: withNullable(z.string()),accountNumber: withNullable(z.string()),taxPercent: withNullable(z.number()),taxAmount: withNullable(z.number()),@@ -503,13 +1099,16 @@ export const ItemSchema = z.object({name: z.string(),description: withNullable(z.string()),companyId: z.string(),+ // Mirrors the "itemType" Postgres enum. "Service" distinguishes service+ // items for providers whose item objects are typed (QBO Service vs+ // NonInventory).type: z.enum(["Part","Material","Tool",+ "Service","Consumable",- "Fixture",- "Service"+ "Fixture"]),unitOfMeasureCode: withNullable(z.string()),unitCost: z.number(),@@ -540,3 +1139,53 @@ export const InventoryAdjustmentSchema = z.object({updatedAt: z.string().datetime(),raw: z.record(z.any()).optional()});++// ============================================================================+// JOURNAL ENTRY (posting sync — journal + journalLine, push-only)+// ============================================================================++/**+ * One analytical dimension stamped on a journal line+ * (`journalLineDimension` row). `valueId` is Carbon's INTERNAL id and is+ * polymorphic across entity-typed dimensions (location.id, supplier.id,+ * item.id, dimensionValue.id, …) — what crosses the wire to a provider is+ * always the RESOLVED provider option id from the dimension value mapping+ * (entityType "dimensionValue"), never this id.+ */+export const JournalEntryLineDimensionSchema = z.object({+ dimensionId: z.string(),+ valueId: z.string()+});++export const JournalEntryLineSchema = z.object({+ id: z.string(),+ accountId: withNullable(z.string()),+ /** Signed: positive = debit, negative = credit. */+ amount: z.number(),+ description: withNullable(z.string()),+ /** Line dimensions (absent when the line carries none). */+ dimensions: z.array(JournalEntryLineDimensionSchema).optional()+});++export const JournalEntrySchema = z.object({+ /** journal.id (Carbon internal id). */+ id: z.string(),+ companyId: z.string(),+ /** Human-readable journal entry number (journal.journalEntryId). */+ journalEntryId: z.string(),+ description: withNullable(z.string()),+ postingDate: z.string(), // YYYY-MM-DD+ status: z.enum(["Draft", "Posted", "Reversed"]),+ sourceType: withNullable(z.string()), // journalEntrySourceType enum value+ reversalOfId: withNullable(z.string()),+ reversedById: withNullable(z.string()),+ /**+ * True when this fetch is a reversal push (entity id carried the+ * ":reversal" suffix): the syncer pushes negated line amounts for the+ * original journal instead of the journal itself.+ */+ reversal: z.boolean(),+ lines: z.array(JournalEntryLineSchema),+ updatedAt: z.string(),+ raw: z.record(z.any()).optional()+});diff --git a/packages/ee/src/accounting/core/operations.test.ts b/packages/ee/src/accounting/core/operations.test.tsnew file mode 100644index 0000000000..53124d9ee1--- /dev/null+++ b/packages/ee/src/accounting/core/operations.test.ts@@ -0,0 +1,341 @@+import { describe, expect, it } from "vitest";+import { SyncOperationStatusSchema } from "./models";+import {+ getClaimEntityTypeExclusion,+ getClaimEntityTypeFilterError,+ getSyncOperationsByIds,+ getSyncOperationTransitionError,+ isCooldownTrigger,+ isLiveSyncOperationStatus,+ SYNC_OPERATION_COOLDOWN_MS,+ shouldSkipForCooldown,+ updateOperationMetadata+} from "./operations";+import type { SyncOperationStatus, SyncOperationTrigger } from "./types";++const ALL_STATUSES = SyncOperationStatusSchema.options;++describe("getSyncOperationTransitionError", () => {+ // Retry (Failed/Warning/Skipped → Pending — Skipped covers both a human+ // opt-out and the drain's machine no-op close), Skip+ // (Failed/Warning/Pending → Skipped), Re-send (Completed/Excluded →+ // Pending — an Excluded journal re-decides against the current policy+ // config)+ const allowed: Array<[SyncOperationStatus, SyncOperationStatus]> = [+ ["Failed", "Pending"],+ ["Warning", "Pending"],+ ["Completed", "Pending"],+ ["Excluded", "Pending"],+ ["Skipped", "Pending"],+ ["Failed", "Skipped"],+ ["Warning", "Skipped"],+ ["Pending", "Skipped"]+ ];++ it("covers every from → to combination exhaustively", () => {+ for (const from of ALL_STATUSES) {+ for (const to of ALL_STATUSES) {+ const isAllowed = allowed.some(([f, t]) => f === from && t === to);+ const error = getSyncOperationTransitionError(from, to);++ if (isAllowed) {+ expect(error, `${from} → ${to} should be allowed`).toBeNull();+ } else {+ expect(error, `${from} → ${to} should be rejected`).toBe(+ `invalid transition ${from} → ${to}`+ );+ }+ }+ }+ });++ it("rejects transitions out of In Flight entirely", () => {+ for (const to of ALL_STATUSES) {+ expect(getSyncOperationTransitionError("In Flight", to)).not.toBeNull();+ }+ });+});++describe("isLiveSyncOperationStatus", () => {+ it("absorbs re-triggers only into Pending and In Flight rows", () => {+ expect(isLiveSyncOperationStatus("Pending")).toBe(true);+ expect(isLiveSyncOperationStatus("In Flight")).toBe(true);+ expect(isLiveSyncOperationStatus("Completed")).toBe(false);+ expect(isLiveSyncOperationStatus("Failed")).toBe(false);+ expect(isLiveSyncOperationStatus("Warning")).toBe(false);+ expect(isLiveSyncOperationStatus("Skipped")).toBe(false);+ });+});++describe("shouldSkipForCooldown", () => {+ const now = new Date("2026-07-09T12:00:00.000Z");++ const completedAgo = (ms: number) =>+ new Date(now.getTime() - ms).toISOString();++ it("skips event/webhook re-triggers completed inside the cooldown", () => {+ for (const trigger of ["event", "webhook"] as const) {+ expect(+ shouldSkipForCooldown({+ trigger,+ completedAt: completedAgo(1_000),+ now+ })+ ).toBe(true);+ expect(+ shouldSkipForCooldown({+ trigger,+ completedAt: completedAgo(SYNC_OPERATION_COOLDOWN_MS - 1),+ now+ })+ ).toBe(true);+ }+ });++ it("does not skip once the cooldown has elapsed", () => {+ expect(+ shouldSkipForCooldown({+ trigger: "event",+ completedAt: completedAgo(SYNC_OPERATION_COOLDOWN_MS),+ now+ })+ ).toBe(false);+ expect(+ shouldSkipForCooldown({+ trigger: "webhook",+ completedAt: completedAgo(SYNC_OPERATION_COOLDOWN_MS + 1_000),+ now+ })+ ).toBe(false);+ });++ it("never skips backfill/manual/posting/retry triggers", () => {+ for (const trigger of [+ "backfill",+ "manual",+ "posting",+ "retry"+ ] as SyncOperationTrigger[]) {+ expect(isCooldownTrigger(trigger)).toBe(false);+ expect(+ shouldSkipForCooldown({+ trigger,+ completedAt: completedAgo(1_000),+ now+ })+ ).toBe(false);+ }+ });++ it("does not skip without a completed row or with an invalid timestamp", () => {+ expect(+ shouldSkipForCooldown({ trigger: "event", completedAt: null, now })+ ).toBe(false);+ expect(+ shouldSkipForCooldown({ trigger: "event", completedAt: undefined, now })+ ).toBe(false);+ expect(+ shouldSkipForCooldown({+ trigger: "event",+ completedAt: "not-a-date",+ now+ })+ ).toBe(false);+ });+});++describe("getClaimEntityTypeExclusion", () => {+ it("returns null when there is nothing to exclude", () => {+ expect(getClaimEntityTypeExclusion(undefined)).toBeNull();+ expect(getClaimEntityTypeExclusion([])).toBeNull();+ });++ it("formats a single entity type as a quoted PostgREST list", () => {+ // The daily-consolidation hold: journalEntry rows stay Pending for the+ // consolidation cron instead of being claimed by the drain+ expect(getClaimEntityTypeExclusion(["journalEntry"])).toBe(+ '("journalEntry")'+ );+ });++ it("formats multiple entity types comma-separated", () => {+ expect(getClaimEntityTypeExclusion(["journalEntry", "item"])).toBe(+ '("journalEntry","item")'+ );+ });+});++describe("getClaimEntityTypeFilterError", () => {+ it("allows an include-only claim (daily-consolidation cron)", () => {+ expect(+ getClaimEntityTypeFilterError({ entityTypes: ["journalEntry"] })+ ).toBeNull();+ });++ it("allows an exclude-only claim (drain holding journalEntry)", () => {+ expect(+ getClaimEntityTypeFilterError({ excludeEntityTypes: ["journalEntry"] })+ ).toBeNull();+ });++ it("allows an unfiltered claim", () => {+ expect(getClaimEntityTypeFilterError({})).toBeNull();+ expect(+ getClaimEntityTypeFilterError({ entityTypes: [], excludeEntityTypes: [] })+ ).toBeNull();+ });++ it("rejects combining the include and exclude filters", () => {+ expect(+ getClaimEntityTypeFilterError({+ entityTypes: ["journalEntry"],+ excludeEntityTypes: ["item"]+ })+ ).toBe(+ "entityTypes and excludeEntityTypes are mutually exclusive claim filters"+ );+ });+});++// /********************************************************\+// * Stateless-caller additions (byIds + metadata) *+// \********************************************************/+// Minimal chainable stub emulating the exact supabase-js chains these two+// functions use (select().eq().in() thenable; update().eq().eq().select()+// .single()). Rows mutate in place so assertions read the "table" back.++function makeOperationTableStub(rows: Array<Record<string, unknown>>) {+ const client = {+ from(table: string) {+ if (table !== "accountingSyncOperation") {+ throw new Error(`unexpected table ${table}`);+ }++ let matched = rows;+ let patch: Record<string, unknown> | null = null;++ const applyPatch = () => {+ if (!patch) return;+ for (const row of matched) Object.assign(row, patch);+ patch = null;+ };++ const builder = {+ select() {+ return builder;+ },+ update(update: Record<string, unknown>) {+ patch = update;+ return builder;+ },+ eq(column: string, value: unknown) {+ matched = matched.filter((row) => row[column] === value);+ return builder;+ },+ in(column: string, values: readonly unknown[]) {+ matched = matched.filter((row) => values.includes(row[column]));+ return builder;+ },+ single() {+ applyPatch();+ return Promise.resolve(+ matched.length === 1+ ? { data: matched[0], error: null }+ : {+ data: null,+ error: { message: `expected 1 row, got ${matched.length}` }+ }+ );+ },+ then(+ onfulfilled?: (value: {+ data: Array<Record<string, unknown>>;+ error: null;+ }) => unknown+ ) {+ applyPatch();+ return Promise.resolve({ data: matched, error: null }).then(+ onfulfilled+ );+ }+ };++ return builder;+ }+ };++ return client as unknown as Parameters<typeof getSyncOperationsByIds>[0];+}++describe("getSyncOperationsByIds", () => {+ it("returns only the requested ids scoped to the company", async () => {+ const rows = [+ { id: "op-1", companyId: "company-1", status: "In Flight" },+ { id: "op-2", companyId: "company-1", status: "Pending" },+ { id: "op-1", companyId: "company-2", status: "In Flight" }+ ];++ const result = await getSyncOperationsByIds(makeOperationTableStub(rows), {+ companyId: "company-1",+ ids: ["op-1", "op-3"]+ });++ expect(result.error).toBeNull();+ expect(result.data).toEqual([+ { id: "op-1", companyId: "company-1", status: "In Flight" }+ ]);+ });++ it("short-circuits an empty id list without touching the client", async () => {+ const client = {+ from() {+ throw new Error("should not query for an empty id list");+ }+ } as unknown as Parameters<typeof getSyncOperationsByIds>[0];++ const result = await getSyncOperationsByIds(client, {+ companyId: "company-1",+ ids: []+ });+ expect(result).toEqual({ data: [], error: null });+ });+});++describe("updateOperationMetadata", () => {+ it("replaces metadata (not merges) and leaves the status untouched", async () => {+ const rows = [+ {+ id: "op-1",+ companyId: "company-1",+ status: "In Flight",+ metadata: { qbdPhase: "query", stale: true },+ updatedAt: null+ }+ ];++ const result = await updateOperationMetadata(makeOperationTableStub(rows), {+ id: "op-1",+ companyId: "company-1",+ metadata: { qbdPhase: "mod" }+ });++ expect(result.error).toBeNull();+ expect(rows[0]).toMatchObject({+ status: "In Flight",+ metadata: { qbdPhase: "mod" }+ });+ expect(rows[0]?.metadata).not.toHaveProperty("stale");+ expect(rows[0]?.updatedAt).toBeTruthy();+ });++ it("returns an error for a missing operation", async () => {+ const result = await updateOperationMetadata(makeOperationTableStub([]), {+ id: "op-missing",+ companyId: "company-1",+ metadata: { qbdPhase: "add" }+ });++ expect(result.data).toBeNull();+ expect(result.error).toMatch(/expected 1 row, got 0/);+ });+});diff --git a/packages/ee/src/accounting/core/operations.ts b/packages/ee/src/accounting/core/operations.tsnew file mode 100644index 0000000000..ca4d5e5a47--- /dev/null+++ b/packages/ee/src/accounting/core/operations.ts@@ -0,0 +1,739 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import { SYNC_OPERATION_ALLOWED_TRANSITIONS } from "./models";+import type {+ SyncOperation,+ SyncOperationDirection,+ SyncOperationStatus,+ SyncOperationTrigger+} from "./types";++/**+ * Service for the "accountingSyncOperation" ledger: one row per attempted+ * sync of one entity in one direction. Enqueue absorbs re-triggers into the+ * live row, drains claim Pending work, and the UI retries/skips/re-sends+ * through guarded transitions.+ */++/**+ * A Completed operation absorbs event/webhook re-triggers for this long.+ */+export const SYNC_OPERATION_COOLDOWN_MS = 60_000;++/**+ * "In Flight" rows older than this are considered abandoned (e.g. a drain+ * that crashed mid-run) and become claimable again.+ */+export const SYNC_OPERATION_STALE_IN_FLIGHT_MS = 10 * 60_000;++const DEFAULT_CLAIM_LIMIT = 20;+const DEFAULT_PAGE_SIZE = 25;+const UNIQUE_VIOLATION = "23505";++/**+ * Live operations hold the partial unique index on+ * (companyId, integration, entityType, entityId, direction): a new enqueue+ * for the same tuple is absorbed instead of creating a duplicate row.+ */+export function isLiveSyncOperationStatus(+ status: SyncOperationStatus+): boolean {+ return status === "Pending" || status === "In Flight";+}++/**+ * Only machine re-triggers (event/webhook) respect the completed-row+ * cooldown; backfill/manual/posting/retry always enqueue.+ */+export function isCooldownTrigger(trigger: SyncOperationTrigger): boolean {+ return trigger === "event" || trigger === "webhook";+}++/**+ * Decide whether an enqueue should be skipped because a Completed operation+ * for the same tuple finished inside the cooldown window.+ */+export function shouldSkipForCooldown(args: {+ trigger: SyncOperationTrigger;+ completedAt: string | null | undefined;+ now?: Date;+ cooldownMs?: number;+}): boolean {+ if (!isCooldownTrigger(args.trigger)) return false;+ if (!args.completedAt) return false;++ const completedAtMs = new Date(args.completedAt).getTime();+ if (Number.isNaN(completedAtMs)) return false;++ const nowMs = (args.now ?? new Date()).getTime();+ return (+ nowMs - completedAtMs < (args.cooldownMs ?? SYNC_OPERATION_COOLDOWN_MS)+ );+}++/**+ * Guard table for UI-driven transitions. Returns null when the transition+ * is allowed, otherwise a descriptive error string.+ */+export function getSyncOperationTransitionError(+ from: SyncOperationStatus,+ to: SyncOperationStatus+): string | null {+ return SYNC_OPERATION_ALLOWED_TRANSITIONS[from].includes(to)+ ? null+ : `invalid transition ${from} → ${to}`;+}++/**+ * PostgREST list literal for excluding entity types from a claim (used+ * with `.not("entityType", "in", ...)`), or null when there is nothing to+ * exclude. Values are double-quoted per PostgREST list syntax so an entity+ * type containing a reserved character cannot corrupt the list.+ */+export function getClaimEntityTypeExclusion(+ excludeEntityTypes: string[] | undefined+): string | null {+ if (!excludeEntityTypes || excludeEntityTypes.length === 0) return null;+ return `(${excludeEntityTypes.map((type) => `"${type}"`).join(",")})`;+}++/**+ * A claim can be scoped by an include filter (`entityTypes`, e.g. the+ * daily-consolidation cron claims only journalEntry operations) OR an+ * exclude filter (`excludeEntityTypes`, e.g. drains hold journalEntry for+ * the cron), never both — combining them invites contradictory filters.+ * Returns the error string for an invalid combination, else null.+ */+export function getClaimEntityTypeFilterError(args: {+ entityTypes?: string[];+ excludeEntityTypes?: string[];+}): string | null {+ const hasInclude = !!args.entityTypes && args.entityTypes.length > 0;+ const hasExclude =+ !!args.excludeEntityTypes && args.excludeEntityTypes.length > 0;+ return hasInclude && hasExclude+ ? "entityTypes and excludeEntityTypes are mutually exclusive claim filters"+ : null;+}++// Generated types now include "accountingSyncOperation" (regenerated with+// the v3 work), but dropping this cast trades it for Json-vs-Record friction+// on every metadata write in this file — a standalone cleanup. Until then+// the query builder stays untyped; row payloads are typed locally via+// SyncOperation (core/models.ts).+function syncOperationTable(client: SupabaseClient<Database>): any {+ return client.from("accountingSyncOperation" as any);+}++export type EnqueueSyncOperationInput = {+ companyId: string;+ integration: string;+ entityType: string;+ entityId: string;+ direction: SyncOperationDirection;+ trigger: SyncOperationTrigger;+ idempotencyKey: string;+ createdBy: string;+ metadata?: Record<string, unknown>;+};++async function getLiveOperation(+ client: SupabaseClient<Database>,+ op: Pick<+ EnqueueSyncOperationInput,+ "companyId" | "integration" | "entityType" | "entityId" | "direction"+ >+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const result = await syncOperationTable(client)+ .select("*")+ .eq("companyId", op.companyId)+ .eq("integration", op.integration)+ .eq("entityType", op.entityType)+ .eq("entityId", op.entityId)+ .eq("direction", op.direction)+ .in("status", ["Pending", "In Flight"])+ .maybeSingle();++ if (result.error) return { data: null, error: result.error.message };+ return { data: (result.data as SyncOperation | null) ?? null, error: null };+}++async function getOperationByIdempotencyKey(+ client: SupabaseClient<Database>,+ op: Pick<+ EnqueueSyncOperationInput,+ "companyId" | "integration" | "idempotencyKey"+ >+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const result = await syncOperationTable(client)+ .select("*")+ .eq("companyId", op.companyId)+ .eq("integration", op.integration)+ .eq("idempotencyKey", op.idempotencyKey)+ .maybeSingle();++ if (result.error) return { data: null, error: result.error.message };+ return { data: (result.data as SyncOperation | null) ?? null, error: null };+}++/**+ * Enqueue a sync operation.+ *+ * - Same (companyId, integration, idempotencyKey) already exists → returns+ * the existing row (idempotent).+ * - A Pending/In Flight row exists for the same (entityType, entityId,+ * direction) → returns it (absorbed). A concurrent insert losing the race+ * on either unique index (23505) is absorbed the same way.+ * - A Completed row for the same tuple finished < 60s ago and the trigger+ * is event/webhook → returns { data: null, error: null } (skipped).+ */+export async function enqueueSyncOperation(+ client: SupabaseClient<Database>,+ op: EnqueueSyncOperationInput+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const existingByKey = await getOperationByIdempotencyKey(client, op);+ if (existingByKey.error) return existingByKey;+ if (existingByKey.data) return existingByKey;++ const live = await getLiveOperation(client, op);+ if (live.error) return live;+ if (live.data) return live;++ if (isCooldownTrigger(op.trigger)) {+ const lastCompleted = await syncOperationTable(client)+ .select("completedAt")+ .eq("companyId", op.companyId)+ .eq("integration", op.integration)+ .eq("entityType", op.entityType)+ .eq("entityId", op.entityId)+ .eq("direction", op.direction)+ .eq("status", "Completed")+ .order("completedAt", { ascending: false })+ .limit(1)+ .maybeSingle();++ if (lastCompleted.error) {+ return { data: null, error: lastCompleted.error.message };+ }++ const completedAt = (+ lastCompleted.data as Pick<SyncOperation, "completedAt"> | null+ )?.completedAt;++ if (shouldSkipForCooldown({ trigger: op.trigger, completedAt })) {+ return { data: null, error: null };+ }+ }++ const inserted = await syncOperationTable(client)+ .insert({+ companyId: op.companyId,+ integration: op.integration,+ entityType: op.entityType,+ entityId: op.entityId,+ direction: op.direction,+ trigger: op.trigger,+ status: "Pending",+ idempotencyKey: op.idempotencyKey,+ metadata: op.metadata ?? null,+ createdBy: op.createdBy+ })+ .select("*")+ .single();++ if (inserted.error) {+ if (inserted.error.code === UNIQUE_VIOLATION) {+ // A concurrent enqueue won the race on one of the unique indexes —+ // absorb by returning whichever row now holds it+ const byKey = await getOperationByIdempotencyKey(client, op);+ if (byKey.data) return byKey;++ const liveRetry = await getLiveOperation(client, op);+ if (liveRetry.data) return liveRetry;+ }++ return { data: null, error: inserted.error.message };+ }++ return { data: inserted.data as SyncOperation, error: null };+}++export type InsertTerminalSyncOperationInput = EnqueueSyncOperationInput & {+ /** Decision-time disposition: Excluded (policy) or Warning (config hole). */+ status: "Excluded" | "Warning";+ errorCode: string;+ errorMessage: string;+};++async function getLatestOperationForTuple(+ client: SupabaseClient<Database>,+ op: Pick<+ EnqueueSyncOperationInput,+ "companyId" | "integration" | "entityType" | "entityId" | "direction"+ >+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const result = await syncOperationTable(client)+ .select("*")+ .eq("companyId", op.companyId)+ .eq("integration", op.integration)+ .eq("entityType", op.entityType)+ .eq("entityId", op.entityId)+ .eq("direction", op.direction)+ .order("createdAt", { ascending: false })+ .limit(1)+ .maybeSingle();++ if (result.error) return { data: null, error: result.error.message };+ return { data: (result.data as SyncOperation | null) ?? null, error: null };+}++/**+ * Record a decision-time disposition directly in a terminal status+ * (spec I1: every posted journal gets exactly one recorded disposition —+ * `Excluded` for policy exclusions, `Warning` for config holes like+ * DOC_SYNC_DISABLED). Idempotent:+ *+ * - same (companyId, integration, idempotencyKey) → returns the existing row;+ * - ANY existing operation for the (entityType, entityId, direction) tuple →+ * returns it untouched (the journal already has a disposition or a live+ * push — re-deliveries and backfills never churn new terminal rows);+ * - a concurrent insert losing the unique-index race (23505) is absorbed.+ *+ * `completedAt` is stamped as the disposition-recorded time so the inbox+ * sorts terminal rows consistently with Completed pushes.+ */+export async function insertTerminalSyncOperation(+ client: SupabaseClient<Database>,+ op: InsertTerminalSyncOperationInput+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const existingByKey = await getOperationByIdempotencyKey(client, op);+ if (existingByKey.error) return existingByKey;+ if (existingByKey.data) return existingByKey;++ const existingForTuple = await getLatestOperationForTuple(client, op);+ if (existingForTuple.error) return existingForTuple;+ if (existingForTuple.data) return existingForTuple;++ const inserted = await syncOperationTable(client)+ .insert({+ companyId: op.companyId,+ integration: op.integration,+ entityType: op.entityType,+ entityId: op.entityId,+ direction: op.direction,+ trigger: op.trigger,+ status: op.status,+ idempotencyKey: op.idempotencyKey,+ errorCode: op.errorCode,+ errorMessage: op.errorMessage,+ completedAt: new Date().toISOString(),+ metadata: op.metadata ?? null,+ createdBy: op.createdBy+ })+ .select("*")+ .single();++ if (inserted.error) {+ if (inserted.error.code === UNIQUE_VIOLATION) {+ const byKey = await getOperationByIdempotencyKey(client, op);+ if (byKey.data) return byKey;++ const forTuple = await getLatestOperationForTuple(client, op);+ if (forTuple.data) return forTuple;+ }++ return { data: null, error: inserted.error.message };+ }++ return { data: inserted.data as SyncOperation, error: null };+}++/**+ * Claim up to `limit` operations for a drain: Pending rows plus "In Flight"+ * rows whose lastAttemptAt is older than 10 minutes (abandoned by a crashed+ * drain). Claimed rows move to "In Flight" with lastAttemptAt = now and+ * attemptCount incremented. Rows claimed by a concurrent drain in between+ * are skipped (optimistic lock on status + attemptCount).+ *+ * `excludeEntityTypes` leaves matching rows un-claimed (still Pending) —+ * the exclusion is applied inside the queries so held rows never consume+ * the claim limit. The daily-consolidation hold uses this: journalEntry+ * operations for companies whose posting-sync settings resolve to+ * consolidation "daily" are drained by the consolidation cron, never+ * pushed individually.+ *+ * `entityTypes` is the include-only counterpart (the consolidation cron+ * claims ONLY journalEntry operations). Mutually exclusive with+ * `excludeEntityTypes` — see getClaimEntityTypeFilterError.+ */+export async function claimPendingOperations(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ integration: string;+ limit?: number;+ entityTypes?: string[];+ excludeEntityTypes?: string[];+ /**+ * Leave journalEntry operations stamped `metadata.granularity =+ * "daily-summary"` un-claimed (still Pending) — they belong to the+ * daily-consolidation cron. Individual-granularity (and legacy+ * unstamped) journal operations claim normally. The event-path drain+ * sets this whenever it is not holding ALL journal operations via the+ * transitional consolidation flag.+ */+ holdDailySummaryJournalEntries?: boolean;+ }+): Promise<{ data: SyncOperation[]; error: string | null }> {+ const filterError = getClaimEntityTypeFilterError(args);+ if (filterError) return { data: [], error: filterError };++ const limit = args.limit ?? DEFAULT_CLAIM_LIMIT;+ const inclusion =+ args.entityTypes && args.entityTypes.length > 0 ? args.entityTypes : null;+ const exclusion = getClaimEntityTypeExclusion(args.excludeEntityTypes);+ // NOT (entityType = journalEntry AND metadata->>granularity = daily-summary)+ const dailySummaryHold =+ "entityType.neq.journalEntry,metadata->>granularity.is.null,metadata->>granularity.neq.daily-summary";+ const now = new Date();+ const staleBefore = new Date(+ now.getTime() - SYNC_OPERATION_STALE_IN_FLIGHT_MS+ ).toISOString();++ let pendingQuery = syncOperationTable(client)+ .select("*")+ .eq("companyId", args.companyId)+ .eq("integration", args.integration)+ .eq("status", "Pending");++ if (inclusion) {+ pendingQuery = pendingQuery.in("entityType", inclusion);+ } else if (exclusion) {+ pendingQuery = pendingQuery.not("entityType", "in", exclusion);+ }+ if (args.holdDailySummaryJournalEntries) {+ pendingQuery = pendingQuery.or(dailySummaryHold);+ }++ const pending = await pendingQuery+ .order("createdAt", { ascending: true })+ .limit(limit);++ if (pending.error) return { data: [], error: pending.error.message };++ let staleQuery = syncOperationTable(client)+ .select("*")+ .eq("companyId", args.companyId)+ .eq("integration", args.integration)+ .eq("status", "In Flight")+ .lt("lastAttemptAt", staleBefore);++ if (inclusion) {+ staleQuery = staleQuery.in("entityType", inclusion);+ } else if (exclusion) {+ staleQuery = staleQuery.not("entityType", "in", exclusion);+ }+ if (args.holdDailySummaryJournalEntries) {+ staleQuery = staleQuery.or(dailySummaryHold);+ }++ const stale = await staleQuery+ .order("createdAt", { ascending: true })+ .limit(limit);++ if (stale.error) return { data: [], error: stale.error.message };++ const candidates = [+ ...((pending.data ?? []) as SyncOperation[]),+ ...((stale.data ?? []) as SyncOperation[])+ ]+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))+ .slice(0, limit);++ const claimed: SyncOperation[] = [];++ for (const candidate of candidates) {+ const updated = await syncOperationTable(client)+ .update({+ status: "In Flight",+ lastAttemptAt: now.toISOString(),+ attemptCount: candidate.attemptCount + 1,+ updatedAt: now.toISOString()+ })+ .eq("id", candidate.id)+ .eq("companyId", candidate.companyId)+ .eq("status", candidate.status)+ .eq("attemptCount", candidate.attemptCount)+ .select("*");++ if (updated.error) return { data: claimed, error: updated.error.message };++ const claimedRow = ((updated.data ?? []) as SyncOperation[])[0];+ if (claimedRow) claimed.push(claimedRow);+ }++ return { data: claimed, error: null };+}++/**+ * Fetch operations by id, companyId-scoped. Claim state lives in the+ * ledger, not in caller memory, so stateless callers can re-load the+ * operations they hold by id.+ */+export async function getSyncOperationsByIds(+ client: SupabaseClient<Database>,+ args: { companyId: string; ids: string[] }+): Promise<{ data: SyncOperation[]; error: string | null }> {+ if (args.ids.length === 0) return { data: [], error: null };++ const result = await syncOperationTable(client)+ .select("*")+ .eq("companyId", args.companyId)+ .in("id", args.ids);++ if (result.error) return { data: [], error: result.error.message };+ return { data: (result.data ?? []) as SyncOperation[], error: null };+}++/**+ * Replace an operation's metadata without touching its status — for+ * callers that need to persist progression on an "In Flight" operation+ * where completeOperation/failOperation don't apply (they always+ * transition the status). Same replace-not-merge metadata contract as+ * those two.+ */+export async function updateOperationMetadata(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ companyId: string;+ metadata: Record<string, unknown>;+ }+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const updated = await syncOperationTable(client)+ .update({+ metadata: args.metadata,+ updatedAt: new Date().toISOString()+ })+ .eq("id", args.id)+ .eq("companyId", args.companyId)+ .select("*")+ .single();++ if (updated.error) return { data: null, error: updated.error.message };+ return { data: updated.data as SyncOperation, error: null };+}++/**+ * Mark an operation Completed (clears any previous error fields).+ *+ * `metadata`, when provided, replaces the operation's metadata (same+ * contract as failOperation) — the daily-consolidation cron passes the+ * operation's existing metadata merged with `consolidatedInto` so member+ * operations record which batch absorbed them.+ */+export async function completeOperation(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ companyId: string;+ externalId?: string;+ metadata?: Record<string, unknown>;+ }+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const now = new Date().toISOString();++ const updated = await syncOperationTable(client)+ .update({+ status: "Completed",+ completedAt: now,+ errorCode: null,+ errorMessage: null,+ updatedAt: now,+ ...(args.externalId ? { externalId: args.externalId } : {}),+ ...(args.metadata !== undefined ? { metadata: args.metadata } : {})+ })+ .eq("id", args.id)+ .eq("companyId", args.companyId)+ .select("*")+ .single();++ if (updated.error) return { data: null, error: updated.error.message };+ return { data: updated.data as SyncOperation, error: null };+}++/**+ * Mark an operation Failed — or Warning when `warning: true` (pre-flight+ * conditions the user can fix, e.g. unmapped accounts).+ *+ * `metadata`, when provided, replaces the operation's metadata — the drain+ * passes a structured failure's metadata (e.g. unmappedAccountIds) merged+ * over the operation's existing metadata.+ */+export async function failOperation(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ companyId: string;+ errorCode?: string;+ errorMessage: string;+ warning?: boolean;+ metadata?: Record<string, unknown>;+ }+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const now = new Date().toISOString();++ const updated = await syncOperationTable(client)+ .update({+ status: args.warning ? "Warning" : "Failed",+ errorCode: args.errorCode ?? null,+ errorMessage: args.errorMessage,+ updatedAt: now,+ ...(args.metadata !== undefined ? { metadata: args.metadata } : {})+ })+ .eq("id", args.id)+ .eq("companyId", args.companyId)+ .select("*")+ .single();++ if (updated.error) return { data: null, error: updated.error.message };+ return { data: updated.data as SyncOperation, error: null };+}++/**+ * Mark an operation Skipped — the drain's close-out for a syncer no-op+ * with NO remote copy behind it (shouldSync gate, config-disabled entity,+ * parked payment). Truthful-ledger rule (v4 spec, Pillar C): such a no-op+ * must never read Completed; the reason lands in errorMessage (errorCode+ * stays null so the inbox renders it neutrally, not as an error badge).+ * `completedAt` is stamped so terminal rows sort consistently. A no-op+ * whose result carries a remoteId (fast-bailout, already-linked) still+ * closes Completed — the remote copy exists, so Completed is the truth.+ */+export async function skipOperation(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ companyId: string;+ reason: string;+ }+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const now = new Date().toISOString();++ const updated = await syncOperationTable(client)+ .update({+ status: "Skipped",+ errorCode: null,+ errorMessage: args.reason,+ completedAt: now,+ updatedAt: now+ })+ .eq("id", args.id)+ .eq("companyId", args.companyId)+ .select("*")+ .single();++ if (updated.error) return { data: null, error: updated.error.message };+ return { data: updated.data as SyncOperation, error: null };+}++/**+ * UI-driven status transition (Retry / Skip / Re-send) with the guard+ * table: Failed|Warning|Skipped → Pending, Failed|Warning|Pending →+ * Skipped, Completed → Pending. Anything else returns an error string.+ * Stamps updatedBy.+ */+export async function transitionOperation(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ companyId: string;+ to: SyncOperationStatus;+ userId: string;+ }+): Promise<{ data: SyncOperation | null; error: string | null }> {+ const existing = await syncOperationTable(client)+ .select("*")+ .eq("id", args.id)+ .eq("companyId", args.companyId)+ .maybeSingle();++ if (existing.error) return { data: null, error: existing.error.message };+ if (!existing.data) {+ return { data: null, error: `Sync operation ${args.id} not found` };+ }++ const from = (existing.data as SyncOperation).status;+ const transitionError = getSyncOperationTransitionError(from, args.to);+ if (transitionError) return { data: null, error: transitionError };++ const updated = await syncOperationTable(client)+ .update({+ status: args.to,+ updatedBy: args.userId,+ updatedAt: new Date().toISOString()+ })+ .eq("id", args.id)+ .eq("companyId", args.companyId)+ .eq("status", from) // guard against a concurrent transition+ .select("*")+ .single();++ if (updated.error) return { data: null, error: updated.error.message };+ return { data: updated.data as SyncOperation, error: null };+}++/**+ * List sync operations for the activity/error-inbox UI, newest first, with+ * an optional status filter and offset pagination. `count` is the total for+ * the current filter. `entityType` narrows to one entity type — the+ * consolidation and reconciliation crons page journalEntry operations+ * without wading through every other entity's history.+ */+export async function getSyncOperations(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ integration: string;+ status?: SyncOperationStatus | SyncOperationStatus[];+ entityType?: string;+ limit?: number;+ offset?: number;+ }+): Promise<{+ data: SyncOperation[];+ count: number | null;+ error: string | null;+}> {+ const limit = args.limit ?? DEFAULT_PAGE_SIZE;+ const offset = args.offset ?? 0;++ let query = syncOperationTable(client)+ .select("*", { count: "exact" })+ .eq("companyId", args.companyId)+ .eq("integration", args.integration);++ if (args.status) {+ query = Array.isArray(args.status)+ ? query.in("status", args.status)+ : query.eq("status", args.status);+ }++ if (args.entityType) {+ query = query.eq("entityType", args.entityType);+ }++ const result = await query+ .order("createdAt", { ascending: false })+ .range(offset, offset + limit - 1);++ if (result.error) {+ return { data: [], count: null, error: result.error.message };+ }++ return {+ data: (result.data ?? []) as SyncOperation[],+ count: result.count ?? null,+ error: null+ };+}diff --git a/packages/ee/src/accounting/core/payment-application.ts b/packages/ee/src/accounting/core/payment-application.tsnew file mode 100644index 0000000000..15c3c37484--- /dev/null+++ b/packages/ee/src/accounting/core/payment-application.ts@@ -0,0 +1,334 @@+import type { KyselyTx } from "@carbon/database/client";+import { createMappingService } from "./external-mapping";++/**+ * Family-agnostic payment-application core. Providers normalize their native+ * payment object into a `NormalizedPayment`; `upsertLocalPaymentDraft` writes+ * the Carbon `payment` + `invoiceSettlement` rows as a **Draft** (idempotent by+ * the `payment` external mapping under the composite id). The GL journal and the+ * document-status transitions are NOT written here — the caller (PaymentSyncerBase)+ * invokes the native `post-payment` edge function after commit, which owns the+ * journal + status. This is the shared write path AR (invoice → Receipt) and AP+ * (bill → Disbursement) both funnel through: Carbon's `payment`/`invoiceSettlement`+ * tables are already family-symmetric (discriminated by paymentType + party ++ * settlement target), so a bill payment is the exact mirror of an invoice payment.+ */++/**+ * The provider-neutral shape a payment syncer produces from its native payment+ * object. `documentRemoteId` is the settled invoice/bill remote id (single-doc+ * default); `linkedDocuments` carries the fan-out when one provider payment+ * settles several documents (e.g. a QBO BillPayment paying multiple bills).+ */+export type NormalizedPayment = {+ /** Derived from the settled document: invoice → AR, bill → AP. */+ family: "ar" | "ap";+ /** Settled invoice/bill remote id (the single-document default). */+ documentRemoteId: string;+ /** The provider's payment id. */+ paymentRemoteId: string;+ /** Payment amount in the payment currency. */+ amount: number;+ /** Payment currency (falls back to the document currency when absent). */+ currencyCode: string | null;+ /** Payment → base exchange rate (v1 same-currency paths record 1). */+ exchangeRate: number;+ /** YYYY-MM-DD. */+ paidDate: string;+ /** Human/provider reference stored on the payment. */+ reference: string;+ /**+ * settled = record/settle; failed/void = reverse a previously recorded+ * payment. A first-seen failed payment is skipped upstream by shouldSync.+ */+ status: "settled" | "failed" | "void";+ /**+ * Multi-document fan-out. When present and non-empty, one settlement is+ * written per mapped document; otherwise `documentRemoteId`/`amount` are+ * used as the single linked document.+ */+ linkedDocuments?: { remoteId: string; amount: number }[];+};++/**+ * Invoice status implied by its settled total (cents-accurate). Returns null+ * for "don't touch": a zero/negative settled total says nothing about what the+ * status should be, and a degenerate zero-total invoice is never restated.+ *+ * Kept as a shared export because the payment tests assert its boundaries. The+ * runtime pull path no longer calls it — `post-payment` owns document status+ * (the invoice/bill status is derived in the `salesInvoices`/`purchaseInvoices`+ * views from Posted-payment settlements).+ */+export function getSettledInvoiceStatus(args: {+ invoiceTotal: number;+ settledTotal: number;+}): "Paid" | "Partially Paid" | null {+ const totalCents = Math.round(args.invoiceTotal * 100);+ const settledCents = Math.round(args.settledTotal * 100);++ if (totalCents <= 0 || settledCents <= 0) return null;+ if (settledCents >= totalCents) return "Paid";+ return "Partially Paid";+}++/**+ * Separator in the outbound push's per-settlement `payment` mapping key+ * (`<paymentId>:<targetDocumentId>` — see PaymentSyncerBase.pushToAccounting).+ * The pull anchor splits on it to recover the payment row id; payment ids+ * never contain ":".+ */+export const SETTLEMENT_KEY_SEPARATOR = ":";++/** What the caller should do with `post-payment` after the Draft write commits. */+export type PaymentPostAction = "post" | "void" | "none";++export interface UpsertPaymentDraftArgs {+ /** Provider id (mapping integration key), e.g. "rillet". */+ providerId: string;+ companyId: string;+ /** System user id for createdBy/updatedBy (and the post-payment userId). */+ actorId: string;+ /** accountDefault.bankCashAccount — payment.bankAccount is NOT NULL. */+ bankAccount: string;+ /** The composite sync entity id (`<documentRemoteId>:<paymentRemoteId>`). */+ paymentMappingId: string;+ /** Yields the next readable payment id (get_next_sequence). Called on insert. */+ getNextReadableId: () => Promise<string>;+ normalized: NormalizedPayment;+}++export interface UpsertPaymentDraftResult {+ paymentRowId: string;+ family: "ar" | "ap";+ postAction: PaymentPostAction;+}++/**+ * Write (or reconcile) the Carbon Draft payment + settlements for one pulled+ * provider payment, inside the caller's Kysely transaction. Returns the payment+ * row id and the `post-payment` action the caller should invoke:+ *+ * - settled, no existing / non-Posted payment → write a Draft `payment` ++ * one `invoiceSettlement` per mapped document → `postAction: "post"`.+ * - settled, existing payment already Posted → idempotent no-op → `"none"`+ * (avoids re-drafting + double-posting a settled payment).+ * - failed/void, existing Posted payment → leave it Posted → `"void"`+ * (post-payment's void requires status Posted).+ * - failed/void, existing non-Posted (or already Voided) → `"none"`.+ *+ * Unmapped linked documents are silently dropped (ownership skip); if NONE map,+ * throws — shouldSync should have skipped the change before reaching here.+ */+export async function upsertLocalPaymentDraft(+ tx: KyselyTx,+ args: UpsertPaymentDraftArgs+): Promise<UpsertPaymentDraftResult> {+ const {+ providerId,+ companyId,+ actorId,+ bankAccount,+ paymentMappingId,+ getNextReadableId,+ normalized+ } = args;+ const { family, status } = normalized;+ const mapping = createMappingService(tx, companyId);+ const docEntityType = family === "ar" ? "invoice" : "bill";+ const now = new Date().toISOString();++ // Resolve linked documents (default: the single documentRemoteId).+ const linked =+ normalized.linkedDocuments && normalized.linkedDocuments.length > 0+ ? normalized.linkedDocuments+ : [{ remoteId: normalized.documentRemoteId, amount: normalized.amount }];++ const resolved: { invoiceId: string; amount: number }[] = [];+ let partyId: string | null = null;+ let documentCurrency: string | null = null;++ for (const doc of linked) {+ const localDocId = await mapping.getEntityId(+ providerId,+ doc.remoteId,+ docEntityType+ );+ if (!localDocId) continue; // ownership skip: drop unmapped documents++ if (family === "ar") {+ const invoice = await tx+ .selectFrom("salesInvoice")+ .select(["id", "customerId", "currencyCode"])+ .where("id", "=", localDocId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!invoice) continue;+ partyId ??= invoice.customerId;+ documentCurrency ??= invoice.currencyCode;+ resolved.push({ invoiceId: invoice.id, amount: doc.amount });+ } else {+ const invoice = await tx+ .selectFrom("purchaseInvoice")+ .select(["id", "supplierId", "currencyCode"])+ .where("id", "=", localDocId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!invoice) continue;+ partyId ??= invoice.supplierId;+ documentCurrency ??= invoice.currencyCode;+ resolved.push({ invoiceId: invoice.id, amount: doc.amount });+ }+ }++ if (resolved.length === 0) {+ throw new Error(+ `No mapped ${docEntityType} for ${providerId} payment ${normalized.paymentRemoteId} (composite ${paymentMappingId}); the document must be pushed/mapped first`+ );+ }++ // Idempotency anchor: the payment mapping under the composite id.+ const existingMapping = await mapping.getByExternalId(+ providerId,+ paymentMappingId,+ "payment"+ );+ // The mapping's entityId is either a bare payment row id (pull-created, or a+ // single-settlement push) or the multi-settlement push fan-out's+ // `<paymentId>:<targetDocumentId>` key — payment ids never contain ":", so+ // the prefix is always the row id. Without this, pulling back a payment+ // Carbon pushed with several settlements missed the row, re-inserted it, and+ // died on the mapping's unique-externalId constraint.+ const existingPaymentId =+ existingMapping?.entityId?.split(SETTLEMENT_KEY_SEPARATOR)[0] ?? null;+ const existingPayment = existingPaymentId+ ? await tx+ .selectFrom("payment")+ .select(["id", "status"])+ .where("id", "=", existingPaymentId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ : null;++ // ---- failed / void ------------------------------------------------------+ if (status !== "settled") {+ if (!existingPayment) {+ throw new Error(+ `${providerId} payment ${normalized.paymentRemoteId} is ${status} but was never recorded in Carbon — nothing to void`+ );+ }+ if (existingPayment.status === "Posted") {+ return { paymentRowId: existingPayment.id, family, postAction: "void" };+ }+ // Draft (never posted) or already Voided → nothing to reverse.+ return { paymentRowId: existingPayment.id, family, postAction: "none" };+ }++ // ---- settled ------------------------------------------------------------+ // An already-Posted payment is left untouched: re-drafting + re-posting would+ // orphan its journal and double-book Carbon's GL. The fast-bailout in the base+ // pull flow means we only get here when the remote genuinely changed.+ if (existingPayment && existingPayment.status === "Posted") {+ return { paymentRowId: existingPayment.id, family, postAction: "none" };+ }++ const paymentType = family === "ar" ? "Receipt" : "Disbursement";+ const currencyCode = normalized.currencyCode ?? documentCurrency ?? undefined;+ if (!currencyCode) {+ throw new Error(+ `Cannot record ${providerId} payment ${normalized.paymentRemoteId}: no currency on the payment or its document`+ );+ }++ let paymentRowId: string;+ if (existingPayment) {+ paymentRowId = existingPayment.id;+ await tx+ .updateTable("payment")+ .set({+ status: "Draft",+ paymentType,+ customerId: family === "ar" ? partyId : null,+ supplierId: family === "ap" ? partyId : null,+ paymentDate: normalized.paidDate,+ postingDate: normalized.paidDate,+ currencyCode,+ exchangeRate: normalized.exchangeRate,+ totalAmount: normalized.amount,+ bankAccount,+ reference: normalized.reference,+ journalId: null,+ postedAt: null,+ postedBy: null,+ voidedAt: null,+ voidedBy: null,+ updatedBy: actorId,+ updatedAt: now+ })+ .where("id", "=", paymentRowId)+ .where("companyId", "=", companyId)+ .execute();+ } else {+ const readableId = await getNextReadableId();+ const inserted = await tx+ .insertInto("payment")+ .values({+ paymentId: readableId,+ paymentType,+ status: "Draft",+ customerId: family === "ar" ? partyId : null,+ supplierId: family === "ap" ? partyId : null,+ paymentDate: normalized.paidDate,+ postingDate: normalized.paidDate,+ currencyCode,+ exchangeRate: normalized.exchangeRate,+ totalAmount: normalized.amount,+ bankAccount,+ reference: normalized.reference,+ companyId,+ createdBy: actorId,+ createdAt: now+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ paymentRowId = inserted.id;++ // Link the payment mapping under the composite id so a later pull finds it.+ // (The base pull flow also links id → composite remoteId; both are the same+ // upsert, so this is idempotent and keeps the write self-contained.)+ await mapping.link("payment", paymentRowId, providerId, paymentMappingId, {+ createdBy: actorId+ });+ }++ // Replace this payment's settlements (one per mapped document). A zero-amount+ // settlement is skipped — invoiceSettlement requires a positive component sum.+ await tx+ .deleteFrom("invoiceSettlement")+ .where("paymentId", "=", paymentRowId)+ .where("companyId", "=", companyId)+ .execute();++ const settlementRows = resolved+ .filter((r) => r.amount > 0)+ .map((r) => ({+ paymentId: paymentRowId,+ ...(family === "ar"+ ? { targetSalesInvoiceId: r.invoiceId }+ : { targetPurchaseInvoiceId: r.invoiceId }),+ appliedAmount: r.amount,+ discountAmount: 0,+ writeOffAmount: 0,+ sourceExchangeRate: normalized.exchangeRate,+ targetExchangeRate: 1,+ appliedDate: normalized.paidDate,+ companyId,+ createdBy: actorId+ }));++ if (settlementRows.length > 0) {+ await tx.insertInto("invoiceSettlement").values(settlementRows).execute();+ }++ return { paymentRowId, family, postAction: "post" };+}diff --git a/packages/ee/src/accounting/core/payment-syncer.ts b/packages/ee/src/accounting/core/payment-syncer.tsnew file mode 100644index 0000000000..f145705299--- /dev/null+++ b/packages/ee/src/accounting/core/payment-syncer.ts@@ -0,0 +1,801 @@+import type { KyselyTx } from "@carbon/database/client";+import { sql } from "kysely";+import { createMappingService } from "./external-mapping";+import { ProviderID } from "./models";+import {+ type NormalizedPayment,+ SETTLEMENT_KEY_SEPARATOR,+ upsertLocalPaymentDraft+} from "./payment-application";+import {+ isPaymentSyncbackEnabled,+ JournalEntrySyncError,+ toPostingDateString+} from "./posting";+import {+ BaseEntitySyncer,+ type BatchSyncResult,+ type SyncResult+} from "./types";+import { withTriggersDisabled } from "./utils";++/**+ * PaymentSyncerBase — the family-agnostic, PULL-ONLY base for every payment+ * syncer. Providers implement `mapToNormalized` (native payment object →+ * NormalizedPayment) plus the remote-fetch/timestamp/shouldSync methods; the+ * base owns the write half:+ *+ * 1. In the base pull transaction, `upsertLocal` writes an idempotent **Draft**+ * `payment` + `invoiceSettlement` via `upsertLocalPaymentDraft`.+ * 2. AFTER the transaction commits, the pull override invokes the native+ * `post-payment` edge function (`{ type: "post" }` for a settled payment,+ * `{ type: "void" }` for a failed/void one), which builds the GL journal,+ * sets `payment.journalId`, flips the status to Posted/Voided, and lets the+ * invoice/bill status derive from the settlement.+ *+ * Posting is a separate invocation (not the base `withTriggersDisabled` tx) — it+ * runs with triggers ENABLED, exactly like a user posting a payment. Its journal+ * is a DOC_BACKED disposition and is never re-pushed to the provider, so the+ * provider's GL is not double-posted. This is intentional; do not add extra+ * trigger suppression around the post-payment call.+ */++export const PAYMENT_PULL_ONLY_MESSAGE =+ "Payments are pull-only: pushing Carbon payments to the accounting provider is not supported";++/**+ * Providers whose payment syncer overrides `supportsPaymentPush = true` — i.e.+ * they can write a Carbon-born payment back out as a provider payment document+ * (Phase G outbound write-back). The reconciler and the outbound sweep read+ * this to decide whether to page posted payments as candidate push refs.+ *+ * MUST stay in sync with each provider syncer's `supportsPaymentPush` override+ * (RilletPaymentSyncer, XeroPaymentSyncer, QboPaymentSyncer) — a provider in+ * this set whose syncer still rejects push would enqueue ops that only ever+ * Skip, and a provider absent from it whose syncer supports push would never be+ * swept.+ */+export const PAYMENT_PUSH_PROVIDERS: ReadonlySet<ProviderID> = new Set([+ ProviderID.RILLET,+ ProviderID.XERO,+ ProviderID.QUICKBOOKS+]);++type PendingPost = {+ paymentRowId: string;+ postAction: "post" | "void" | "none";+ actorId: string;+};++export abstract class PaymentSyncerBase<TRemote> extends BaseEntitySyncer<+ TRemote,+ TRemote,+ never+> {+ /**+ * Keyed by the composite remote id, populated during `upsertLocal` (inside the+ * base pull tx) and drained after commit to invoke `post-payment`.+ */+ private pendingPosts = new Map<string, PendingPost>();++ /**+ * Per-instance cache of the resolved integration metadata read from+ * `companyIntegration.metadata`. A drain reuses one syncer across its claimed+ * operations, so the read happens at most once per drain (mirrors the+ * journal-entry syncers' `getPostingSyncSettings` cache).+ */+ private integrationMetadataPromise?: Promise<unknown>;++ // =================================================================+ // Provider contract+ // =================================================================++ /** Map the native payment object + composite entity id → NormalizedPayment. */+ protected abstract mapToNormalized(+ remote: TRemote,+ entityId: string+ ): NormalizedPayment;++ // fetchRemote / fetchRemoteBatch / getRemoteUpdatedAt / shouldSync are+ // implemented by concrete providers.++ // =================================================================+ // Write half (shared)+ // =================================================================++ /**+ * Identity passthrough: the real normalization needs the composite entity id,+ * which is only available in `upsertLocal`. The base pull flow calls+ * `mapToLocal(remote)` (no id) then `upsertLocal(tx, data, remoteId)`, so we+ * carry the raw remote through `data` and normalize in `upsertLocal`.+ */+ protected async mapToLocal(remote: TRemote): Promise<Partial<TRemote>> {+ return remote;+ }++ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<TRemote>,+ remoteId: string+ ): Promise<string> {+ const normalized = this.mapToNormalized(data as TRemote, remoteId);+ const actorId = await this.getDefaultUser(tx);+ const bankAccount = await this.getBankCashAccount(tx);++ const result = await upsertLocalPaymentDraft(tx, {+ providerId: this.provider.id,+ companyId: this.companyId,+ actorId,+ bankAccount,+ paymentMappingId: remoteId,+ getNextReadableId: () => this.getNextPaymentReadableId(tx, normalized),+ normalized+ });++ this.pendingPosts.set(remoteId, {+ paymentRowId: result.paymentRowId,+ postAction: result.postAction,+ actorId+ });++ return result.paymentRowId;+ }++ // =================================================================+ // Pull overrides: base upsert (Draft) + post-payment after commit+ // =================================================================++ /**+ * Payment mappings are identity-critical, so the base link is unsafe here:+ * a payment Carbon pushed already carries this remote id — under a+ * settlement-scoped key (`<paymentId>:<docId>`) for a multi-settlement+ * fan-out — with `metadata.origin = "carbon"` (the void-echo routing flag).+ * The base `link` would insert a second row for the same externalId (fatal:+ * the mapping table's unique-externalId constraint) or, on the bare-id+ * upsert path, `doUpdateSet` the metadata to null and wipe the origin.+ * When ANY payment mapping already carries this remote id, refresh its sync+ * timestamps and leave the row alone; only a genuinely new pull links.+ */+ protected async linkEntities(+ tx: KyselyTx,+ localId: string,+ remoteId: string,+ remoteUpdatedAt?: Date+ ): Promise<void> {+ const txMapping = createMappingService(tx, this.companyId);+ const existing = await txMapping.getByExternalId(+ this.provider.id,+ remoteId,+ "payment"+ );+ if (existing) {+ await txMapping.touchLastSyncedAt(+ "payment",+ existing.entityId,+ this.provider.id,+ remoteUpdatedAt+ );+ return;+ }+ await super.linkEntities(tx, localId, remoteId, remoteUpdatedAt);+ }++ async pullFromAccounting(remoteId: string): Promise<SyncResult> {+ const result = await super.pullFromAccounting(remoteId);+ return this.applyPostPayment(remoteId, result);+ }++ async pullBatchFromAccounting(remoteIds: string[]): Promise<BatchSyncResult> {+ const batch = await super.pullBatchFromAccounting(remoteIds);++ const results: SyncResult[] = [];+ for (const result of batch.results) {+ results.push(+ result.remoteId+ ? await this.applyPostPayment(result.remoteId, result)+ : result+ );+ }++ return {+ results,+ successCount: results.filter((r) => r.status === "success").length,+ errorCount: results.filter((r) => r.status === "error").length,+ skippedCount: results.filter((r) => r.status === "skipped").length+ };+ }++ /**+ * After the base upsert commits, invoke `post-payment` for the drained+ * pending write. A post-payment failure surfaces as an `error` result (its+ * message carried through) rather than being swallowed.+ */+ private async applyPostPayment(+ remoteId: string,+ result: SyncResult+ ): Promise<SyncResult> {+ const pending = this.pendingPosts.get(remoteId);+ this.pendingPosts.delete(remoteId);++ if (+ result.status !== "success" ||+ !result.localId ||+ !pending ||+ pending.postAction === "none"+ ) {+ return result;+ }++ const posted = await this.invokePostPayment(+ pending.paymentRowId,+ pending.postAction,+ pending.actorId+ );++ if (posted.error) {+ return {+ status: "error",+ action: "none",+ localId: result.localId,+ remoteId,+ error: posted.message+ };+ }++ return result;+ }++ private async invokePostPayment(+ paymentId: string,+ type: "post" | "void",+ userId: string+ ): Promise<{ error: false } | { error: true; message: string }> {+ // Dynamic import: keeps the server-only auth/env module out of the module+ // graph for consumers (and tests) that never post a payment (mirrors the+ // base's dynamic import of the SyncFactory).+ const { getCarbonServiceRole } = await import("@carbon/auth/client.server");+ const serviceRole = getCarbonServiceRole();+ const response = await serviceRole.functions.invoke("post-payment", {+ body: { type, paymentId, userId, companyId: this.companyId }+ });++ if (response.error) {+ const message =+ (response.data as { message?: string } | undefined)?.message ??+ response.error.message ??+ `Failed to ${type} payment ${paymentId}`;+ return { error: true, message };+ }+ return { error: false };+ }++ // =================================================================+ // Documents-mode sync-back gate (Phase 0.4)+ // =================================================================++ /**+ * The company's raw `companyIntegration.metadata` for this provider, read+ * once per syncer instance. The provider only carries the RESOLVED sync+ * config, not the raw `settings.postingSync` fragment, so the gate reads the+ * metadata directly (same keying + caching as the journal-entry syncers).+ */+ private getIntegrationMetadata(): Promise<unknown> {+ if (!this.integrationMetadataPromise) {+ this.integrationMetadataPromise = (async () => {+ const integration = await this.database+ .selectFrom("companyIntegration")+ .select("metadata")+ .where("id", "=", this.provider.id)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();+ return integration?.metadata;+ })();+ }+ return this.integrationMetadataPromise;+ }++ /**+ * Whether inbound payment sync-back is allowed for the given AR/AP family:+ * true ONLY when that family is in `documents` mode. Providers call this from+ * `shouldSync` to skip the pull for `journals`/`none` families. An+ * absent/invalid config resolves to defaults (documents), so an unconfigured+ * integration keeps sync-back enabled.+ */+ protected async isPaymentSyncbackEnabled(+ family: "ar" | "ap"+ ): Promise<boolean> {+ return isPaymentSyncbackEnabled(+ await this.getIntegrationMetadata(),+ family+ );+ }++ // =================================================================+ // Shared resolution helpers (moved from RilletPaymentSyncer)+ // =================================================================++ /** Next readable payment id via get_next_sequence, with a stable fallback. */+ protected async getNextPaymentReadableId(+ tx: KyselyTx,+ normalized: NormalizedPayment+ ): Promise<string> {+ const sequence = await sql<{ get_next_sequence: string }>`+ SELECT get_next_sequence('payment', ${this.companyId}) as get_next_sequence+ `.execute(tx);+ return (+ sequence.rows[0]?.get_next_sequence ??+ `PAY-${normalized.paymentRemoteId.slice(0, 8)}`+ );+ }++ /** accountDefault.bankCashAccount — payment.bankAccount is NOT NULL. */+ protected async getBankCashAccount(tx: KyselyTx): Promise<string> {+ const defaults = await tx+ .selectFrom("accountDefault")+ .select("bankCashAccount")+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (!defaults?.bankCashAccount) {+ throw new Error(+ `No bank/cash account default (accountDefault.bankCashAccount) configured for company ${this.companyId} — required to record pulled payments`+ );+ }+ return defaults.bankCashAccount;+ }++ /**+ * Default user for system-generated records: company group owner, then first+ * active employee (QBO/Xero bill-syncer parity).+ */+ protected async getDefaultUser(tx: KyselyTx): Promise<string> {+ const group = await tx+ .selectFrom("company")+ .innerJoin("companyGroup", "companyGroup.id", "company.companyGroupId")+ .select("companyGroup.ownerId")+ .where("company.id", "=", this.companyId)+ .executeTakeFirst();++ if (group?.ownerId) {+ return group.ownerId;+ }++ const employee = await tx+ .selectFrom("employeeJob")+ .innerJoin("user", "user.id", "employeeJob.id")+ .select("employeeJob.id")+ .where("employeeJob.companyId", "=", this.companyId)+ .where("user.active", "=", true)+ .orderBy("user.createdAt", "asc")+ .limit(1)+ .executeTakeFirst();++ if (!employee?.id) {+ throw new Error(+ `Cannot record pulled payment: no default user found for company ${this.companyId}`+ );+ }+ return employee.id;+ }++ // =================================================================+ // Push workflow (Phase G — outbound payment write-back)+ // =================================================================++ /**+ * Whether this provider can write a Carbon-born payment back out as a+ * provider payment document. Off by default (QBO/Xero keep rejecting push);+ * RilletPaymentSyncer sets it true. When false, `pushToAccounting` returns+ * the pull-only error and `pushRemotePayment` is never reached.+ */+ protected supportsPaymentPush = false;++ /**+ * Whether this provider can echo a void of a Carbon-pushed payment back out.+ * Off in v1 for every provider (Rillet has no payment-void endpoint) — a+ * voided Carbon-originated payment lands a Skipped op telling the operator to+ * void it in the provider by hand.+ */+ protected supportsPaymentVoidPush = false;++ /**+ * Provider adapter: create ONE provider payment document for the settled+ * Carbon document and return its remote id plus the composite entity id the+ * `payment` mapping is stored under (`<invoiceRemoteId>:<paymentRemoteId>` for+ * AR, `bill:<billRemoteId>:<paymentRemoteId>` for AP). Resolves the settled+ * document's remote id and the bank account's provider code itself, throwing a+ * `JournalEntrySyncError` (warning) when either mapping is missing. Only+ * reached when `supportsPaymentPush` is true.+ */+ protected pushRemotePayment(+ _context: PaymentPushContext+ ): Promise<{ remoteId: string; compositeEntityId: string }> {+ throw new Error(PAYMENT_PULL_ONLY_MESSAGE);+ }++ async pushToAccounting(entityId: string): Promise<SyncResult> {+ if (!this.supportsPaymentPush) {+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: PAYMENT_PULL_ONLY_MESSAGE+ };+ }++ if (!this.config.enabled) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error: "Sync disabled in config"+ };+ }++ try {+ const payment = await this.loadLocalPaymentForPush(entityId);+ if (!payment) {+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: `Payment ${entityId} not found in Carbon`+ };+ }++ // The event trigger only enqueues on transitions to Posted/Voided, but+ // guard anyway — a Draft payment has no settled GL to represent.+ if (payment.status !== "Posted" && payment.status !== "Voided") {+ return skipped(+ entityId,+ `Payment is ${payment.status} — only Posted or Voided payments push`+ );+ }++ const family: "ar" | "ap" =+ payment.paymentType === "Receipt" ? "ar" : "ap";++ // Same gate as inbound pull: outbound push only runs while the family is+ // in documents mode (the provider owns the settled document, so a payment+ // document is what closes it). In journals/none mode Carbon's payment is+ // represented by the v3 journal path, not a document.+ if (!(await this.isPaymentSyncbackEnabled(family))) {+ return skipped(+ entityId,+ `payment push is disabled: the ${family} family is not in documents mode`+ );+ }++ // Origin routing via the payment mapping. A pulled payment links its+ // mapping in the pull upsert BEFORE post-payment flips it to Posted, so+ // its Posted event finds a mapping here and skips — the loop guard.+ const mapping = await this.mappingService.getByEntity(+ "payment",+ entityId,+ this.provider.id+ );++ if (payment.status === "Voided") {+ return this.pushVoid(entityId, mapping);+ }++ if (mapping?.externalId) {+ // Provider-known (pulled) or already pushed — idempotent skip.+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ remoteId: mapping.externalId,+ error: `Payment ${entityId} already linked to ${this.provider.id} — skipping (idempotent)`+ };+ }++ // A Carbon-born payment: push it — ONE provider payment per settled+ // document (a multi-document payment fans out to N provider+ // payments, each for its settlement's appliedAmount). Discounted and+ // FX payments remain parked as Skipped (documented follow-ups).+ const settlements = [...payment.settlements].sort((a, b) => {+ const aTarget =+ (family === "ar"+ ? a.targetSalesInvoiceId+ : a.targetPurchaseInvoiceId) ?? "";+ const bTarget =+ (family === "ar"+ ? b.targetSalesInvoiceId+ : b.targetPurchaseInvoiceId) ?? "";+ return aTarget.localeCompare(bTarget);+ });+ if (settlements.length === 0) {+ return skipped(+ entityId,+ `Payment ${entityId} has no settlements — nothing to push`+ );+ }+ if (+ settlements.some(+ (settlement) =>+ settlement.discountAmount !== 0 || settlement.writeOffAmount !== 0+ )+ ) {+ return skipped(+ entityId,+ `Payment ${entityId} carries a discount or write-off — outbound push of adjusted payments is not supported in v1`+ );+ }+ if (payment.exchangeRate !== 1) {+ return skipped(+ entityId,+ `Payment ${entityId} is foreign-currency (rate ${payment.exchangeRate}) — outbound FX payment push is not supported in v1`+ );+ }++ // One mapping row per settlement makes the fan-out RESUMABLE: each+ // pushed provider payment is linked immediately, so a failure on+ // settlement k (e.g. its document not yet synced) leaves 1..k-1+ // durable, and the retry pushes only what is still uncovered.+ // Mapping entity keys: the bare payment id for single-settlement+ // (back-compat with every existing v1 mapping) and+ // `<paymentId>:<targetDocumentId>` per settlement otherwise.+ const settlementKey = (targetDocumentId: string): string =>+ settlements.length === 1+ ? entityId+ : `${entityId}${SETTLEMENT_KEY_SEPARATOR}${targetDocumentId}`;++ let firstRemoteId: string | null = null;+ for (const settlement of settlements) {+ const targetDocumentId =+ family === "ar"+ ? settlement.targetSalesInvoiceId+ : settlement.targetPurchaseInvoiceId;+ if (!targetDocumentId) {+ return skipped(+ entityId,+ `Payment ${entityId} settlement has no ${+ family === "ar" ? "sales" : "purchase"+ } invoice target`+ );+ }++ const covered = await this.mappingService.getByEntity(+ "payment",+ settlementKey(targetDocumentId),+ this.provider.id+ );+ if (covered?.externalId) {+ firstRemoteId ??= covered.externalId;+ continue;+ }++ const { remoteId, compositeEntityId } = await this.pushRemotePayment({+ carbonPaymentId: entityId,+ family,+ targetDocumentId,+ bankAccountId: payment.bankAccount,+ amount: settlement.appliedAmount,+ currencyCode: payment.currencyCode,+ paidDate: payment.paidDate,+ reference: payment.reference+ });+ firstRemoteId ??= remoteId;++ // Stamp origin:"carbon" so a subsequent void of THIS payment echoes+ // out (pulled payments have no origin and never echo their void+ // back), and so a later pull of the same provider payment+ // recognizes the composite and no-ops. Linked per settlement so+ // partial fan-out progress survives a failure. Trigger-suppressed+ // to break the sync loop.+ await withTriggersDisabled(this.database, async (tx) => {+ await createMappingService(tx, this.companyId).link(+ "payment",+ settlementKey(targetDocumentId),+ this.provider.id,+ compositeEntityId,+ { metadata: { origin: "carbon" } }+ );+ });+ }++ return {+ status: "success",+ action: "created",+ localId: entityId,+ remoteId: firstRemoteId ?? undefined+ };+ } catch (err) {+ if (err instanceof JournalEntrySyncError) {+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err.failure+ };+ }+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err instanceof Error ? err.message : String(err)+ };+ }+ }++ /**+ * A Carbon payment reaching Voided. Echo the void to the provider ONLY for a+ * payment Carbon originated and pushed (mapping stamped origin:"carbon") — a+ * pulled payment voided in the provider already reversed there, so re-pushing+ * would loop. v1 has no provider void endpoint, so this always Skips with a+ * manual-remediation message; it is the seam a provider void hook plugs into.+ */+ private pushVoid(+ entityId: string,+ mapping: { metadata: Record<string, unknown> | null } | null+ ): SyncResult {+ const carbonOrigin =+ mapping?.metadata != null && mapping.metadata.origin === "carbon";+ if (!carbonOrigin) {+ return skipped(+ entityId,+ `Voided payment ${entityId} has no Carbon-originated provider payment to reverse`+ );+ }+ if (!this.supportsPaymentVoidPush) {+ return skipped(+ entityId,+ `Voiding a pushed payment in ${this.provider.id} is not supported in v1 — void it manually in the provider`+ );+ }+ // No provider implements void push in v1; when one does, call its void+ // adapter here.+ return skipped(+ entityId,+ `Voiding a pushed payment in ${this.provider.id} is not supported in v1`+ );+ }++ async pushBatchToAccounting(entityIds: string[]): Promise<BatchSyncResult> {+ const results: SyncResult[] = [];+ for (const entityId of entityIds) {+ results.push(await this.pushToAccounting(entityId));+ }+ return {+ results,+ successCount: results.filter((r) => r.status === "success").length,+ errorCount: results.filter((r) => r.status === "error").length,+ skippedCount: results.filter((r) => r.status === "skipped").length+ };+ }++ /**+ * Load the Carbon payment + its settlements for an outbound push. Numeric+ * columns arrive as strings from Kysely and are coerced. `paidDate` is the+ * posting date when set (accounting on), else the payment date.+ */+ private async loadLocalPaymentForPush(+ paymentId: string+ ): Promise<LocalPaymentForPush | null> {+ const payment = await this.database+ .selectFrom("payment")+ .select([+ "id",+ "status",+ "paymentType",+ "customerId",+ "supplierId",+ "bankAccount",+ "currencyCode",+ "exchangeRate",+ "paymentDate",+ "postingDate",+ "reference"+ ])+ .where("id", "=", paymentId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (!payment) return null;++ const settlements = await this.database+ .selectFrom("invoiceSettlement")+ .select([+ "targetSalesInvoiceId",+ "targetPurchaseInvoiceId",+ "appliedAmount",+ "discountAmount",+ "writeOffAmount"+ ])+ .where("paymentId", "=", paymentId)+ .where("companyId", "=", this.companyId)+ .execute();++ return {+ status: payment.status,+ paymentType: payment.paymentType,+ bankAccount: payment.bankAccount,+ currencyCode: payment.currencyCode,+ exchangeRate: Number(payment.exchangeRate ?? 1),+ // Kysely's pg driver hands DATE columns back as Date objects (local+ // midnight) — toPostingDateString recovers the stored calendar date+ // for both Date and string values; a bare .slice crashed the push.+ paidDate: toPostingDateString(payment.postingDate ?? payment.paymentDate),+ reference: payment.reference,+ settlements: settlements.map((s) => ({+ targetSalesInvoiceId: s.targetSalesInvoiceId,+ targetPurchaseInvoiceId: s.targetPurchaseInvoiceId,+ appliedAmount: Number(s.appliedAmount ?? 0),+ discountAmount: Number(s.discountAmount ?? 0),+ writeOffAmount: Number(s.writeOffAmount ?? 0)+ }))+ };+ }++ // fetchLocal / mapToRemote / upsertRemote are unused by the bespoke push+ // above (which reads the Carbon payment directly), but the abstract base+ // still declares them — keep them as hard rejections.+ async fetchLocal(_id: string): Promise<TRemote | null> {+ throw new Error(PAYMENT_PULL_ONLY_MESSAGE);+ }++ protected async fetchLocalBatch(+ _ids: string[]+ ): Promise<Map<string, TRemote>> {+ throw new Error(PAYMENT_PULL_ONLY_MESSAGE);+ }++ protected async mapToRemote(_local: TRemote): Promise<TRemote> {+ throw new Error(PAYMENT_PULL_ONLY_MESSAGE);+ }++ protected async upsertRemote(+ _data: TRemote,+ _localId: string+ ): Promise<string> {+ throw new Error(PAYMENT_PULL_ONLY_MESSAGE);+ }++ protected async upsertRemoteBatch(+ _data: Array<{ localId: string; payload: TRemote }>+ ): Promise<Map<string, string>> {+ throw new Error(PAYMENT_PULL_ONLY_MESSAGE);+ }+}++/** Context handed to a provider's `pushRemotePayment` adapter (Phase G). */+export interface PaymentPushContext {+ carbonPaymentId: string;+ family: "ar" | "ap";+ /** Carbon salesInvoice (AR) or purchaseInvoice (AP) id being settled. */+ targetDocumentId: string;+ /** Carbon account id (payment.bankAccount) the payment clears through. */+ bankAccountId: string;+ amount: number;+ currencyCode: string;+ /** YYYY-MM-DD. */+ paidDate: string;+ reference: string | null;+}++type LocalPaymentForPush = {+ status: "Draft" | "Posted" | "Voided";+ paymentType: "Receipt" | "Disbursement";+ bankAccount: string;+ currencyCode: string;+ exchangeRate: number;+ paidDate: string;+ reference: string | null;+ settlements: Array<{+ targetSalesInvoiceId: string | null;+ targetPurchaseInvoiceId: string | null;+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+ }>;+};++function skipped(entityId: string, reason: string): SyncResult {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error: reason+ };+}diff --git a/packages/ee/src/accounting/core/payment-tombstone.test.ts b/packages/ee/src/accounting/core/payment-tombstone.test.tsnew file mode 100644index 0000000000..fd9cf91381--- /dev/null+++ b/packages/ee/src/accounting/core/payment-tombstone.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it, vi } from "vitest";+import { findPaymentCompositesByRemoteId } from "./payment-tombstone";++/**+ * Minimal chainable supabase-query mock:+ * `from(...).select(...).eq(...).eq(...).eq(...).like(...)` resolves to+ * `{ data, error }`. `captured` records the terminal query shape for assertions.+ */+function makeClient(+ rows: { externalId: string | null }[] | null,+ error?: { message: string }+) {+ const captured: Record<string, unknown> = {};+ const builder: any = {+ select: () => builder,+ eq: (col: string, val: unknown) => {+ captured[col] = val;+ return builder;+ },+ like: (col: string, pattern: string) => {+ captured.likeColumn = col;+ captured.likePattern = pattern;+ return Promise.resolve(+ error ? { data: null, error } : { data: rows, error: null }+ );+ }+ };+ const client = {+ from: (table: string) => {+ captured.table = table;+ return builder;+ }+ };+ return { client: client as any, captured };+}++describe("findPaymentCompositesByRemoteId", () => {+ it("resolves the AP composite from a bare payment id via suffix match", async () => {+ const { client, captured } = makeClient([+ { externalId: "bill:bill-9:bp-1" }+ ]);++ const composites = await findPaymentCompositesByRemoteId(client, {+ companyId: "company-1",+ integration: "quickbooks",+ paymentRemoteId: "bp-1"+ });++ expect(composites).toEqual(["bill:bill-9:bp-1"]);+ // Scoped to this company's payment mappings for this integration.+ expect(captured.table).toBe("externalIntegrationMapping");+ expect(captured.companyId).toBe("company-1");+ expect(captured.integration).toBe("quickbooks");+ expect(captured.entityType).toBe("payment");+ expect(captured.likeColumn).toBe("externalId");+ expect(captured.likePattern).toBe("%:bp-1");+ });++ it("resolves the prefix-less AR composite too", async () => {+ const { client } = makeClient([{ externalId: "inv-7:pay-1" }]);++ expect(+ await findPaymentCompositesByRemoteId(client, {+ companyId: "c",+ integration: "quickbooks",+ paymentRemoteId: "pay-1"+ })+ ).toEqual(["inv-7:pay-1"]);+ });++ it("drops coarse LIKE matches that do not exactly end with `:<id>`", async () => {+ // The JS endsWith guard rejects a row whose id merely shares the trailing+ // characters (`:xbp-1` does not end with `:bp-1`) and skips null externalIds.+ const { client } = makeClient([+ { externalId: "bill:bill-9:bp-1" },+ { externalId: "bill:bill-3:xbp-1" },+ { externalId: null }+ ]);++ expect(+ await findPaymentCompositesByRemoteId(client, {+ companyId: "c",+ integration: "quickbooks",+ paymentRemoteId: "bp-1"+ })+ ).toEqual(["bill:bill-9:bp-1"]);+ });++ it("returns [] (logged) on a query error rather than fabricating a void", async () => {+ const errorSpy = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);+ const { client } = makeClient(null, { message: "boom" });++ expect(+ await findPaymentCompositesByRemoteId(client, {+ companyId: "c",+ integration: "quickbooks",+ paymentRemoteId: "bp-1"+ })+ ).toEqual([]);+ expect(errorSpy).toHaveBeenCalled();+ errorSpy.mockRestore();+ });++ it("returns [] when nothing maps (never synced / not ours)", async () => {+ const { client } = makeClient([]);++ expect(+ await findPaymentCompositesByRemoteId(client, {+ companyId: "c",+ integration: "quickbooks",+ paymentRemoteId: "bp-1"+ })+ ).toEqual([]);+ });+});diff --git a/packages/ee/src/accounting/core/payment-tombstone.ts b/packages/ee/src/accounting/core/payment-tombstone.tsnew file mode 100644index 0000000000..46cf5cccb8--- /dev/null+++ b/packages/ee/src/accounting/core/payment-tombstone.ts@@ -0,0 +1,49 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";++/**+ * Resolve the composite `payment` external ids for a bare provider payment id.+ *+ * A hard-deleted QBO `Payment`/`BillPayment` arrives as a CDC tombstone that+ * carries only the bare payment id (no lines → no settled document), so the+ * canonical composite (`<documentRemoteId>:<paymentRemoteId>` for AR, or+ * `bill:<documentRemoteId>:<paymentRemoteId>` for AP) can no longer be rebuilt+ * from the wire. But it was persisted when the payment first synced: both+ * composite forms END with `:<paymentRemoteId>`, so a suffix match against the+ * `externalIntegrationMapping` rows recovers the composite(s) the caller needs+ * to enqueue the reversing (void) pull.+ *+ * Returns `[]` when nothing maps (the payment was never synced, or belongs to+ * another Carbon instance) — the caller then skips it exactly as before. A+ * lookup failure also returns `[]` (logged): the sweep leaves the tombstone+ * unhandled rather than fabricating a void.+ *+ * The DB `LIKE` is a coarse prefilter (`%:<paymentRemoteId>`); the JS+ * `endsWith` guard makes the suffix match exact regardless of `LIKE`+ * metacharacters in the id.+ */+export async function findPaymentCompositesByRemoteId(+ client: SupabaseClient<Database>,+ args: { companyId: string; integration: string; paymentRemoteId: string }+): Promise<string[]> {+ const suffix = `:${args.paymentRemoteId}`;++ const result = await client+ .from("externalIntegrationMapping")+ .select("externalId")+ .eq("companyId", args.companyId)+ .eq("integration", args.integration)+ .eq("entityType", "payment")+ .like("externalId", `%${suffix}`);++ if (result.error) {+ console.error(+ `[PAYMENT TOMBSTONE] ${args.companyId}/${args.integration}: failed to resolve composites for payment ${args.paymentRemoteId}: ${result.error.message}`+ );+ return [];+ }++ return (result.data ?? []).flatMap((row) =>+ row.externalId && row.externalId.endsWith(suffix) ? [row.externalId] : []+ );+}diff --git a/packages/ee/src/accounting/core/posting-policy.test.ts b/packages/ee/src/accounting/core/posting-policy.test.tsnew file mode 100644index 0000000000..74cb8438a5--- /dev/null+++ b/packages/ee/src/accounting/core/posting-policy.test.ts@@ -0,0 +1,344 @@+import { describe, expect, it } from "vitest";+import {+ JOURNAL_ENTRY_SOURCE_TYPES,+ POSTING_POLICY,+ POSTING_SYNC_DEFAULT_SOURCE_TYPES,+ POSTING_SYNC_EXCLUDED_SOURCE_TYPES+} from "./models";+import {+ getJournalPostingPolicyDecision,+ type PostingSyncSettings,+ resolvePostingSyncSettings+} from "./posting";++/** Resolve a v3 stored fragment exactly as production reads it. */+const settingsWith = (+ fragment?: Record<string, unknown>+): PostingSyncSettings =>+ resolvePostingSyncSettings({+ settings: { postingSync: { enabled: true, ...fragment } }+ });++const DOC_SYNC_ON = { invoiceEnabled: true, billEnabled: true };+const DOC_SYNC_OFF = { invoiceEnabled: false, billEnabled: false };++// ── POSTING_POLICY totality & structure ──────────────────────────────────────++describe("POSTING_POLICY", () => {+ it("is structurally valid for every source type", () => {+ for (const sourceType of JOURNAL_ENTRY_SOURCE_TYPES) {+ const entry = POSTING_POLICY[sourceType];+ expect(["journal", "document"]).toContain(entry.representation);++ if (entry.representation === "document") {+ expect(+ entry.family,+ `${sourceType} is document-represented and must carry a family`+ ).toBeDefined();+ expect(+ entry.backingEntityType,+ `${sourceType} must declare its backing entity (or explicit null)`+ ).not.toBeUndefined();+ } else {+ expect(entry.family).toBeUndefined();+ }++ if (entry.family === "per-line") {+ expect(sourceType).toBe("Payment");+ }+ }+ });++ it("derives the frozen v2 default/excluded lists exactly (behavior parity)", () => {+ expect([...POSTING_SYNC_DEFAULT_SOURCE_TYPES].sort()).toEqual(+ [+ "Purchase Receipt",+ "Sales Shipment",+ "Transfer Receipt",+ "Inventory Adjustment",+ "Production Order",+ "Production Event",+ "Job Consumption",+ "Job Receipt",+ "Job Close",+ "Asset Depreciation",+ "Asset Disposal",+ "Non-Conformance",+ "Inbound Inspection"+ ].sort()+ );++ expect([...POSTING_SYNC_EXCLUDED_SOURCE_TYPES].sort()).toEqual(+ [+ "Sales Invoice",+ "Purchase Invoice",+ "Payment",+ "Credit Memo",+ "Debit Memo",+ "Sales Return",+ "Purchase Return"+ ].sort()+ );+ });+});++// ── getJournalPostingPolicyDecision ──────────────────────────────────────────++describe("getJournalPostingPolicyDecision", () => {+ it("pushes enabled journal-represented types with their configured granularity", () => {+ const settings = settingsWith();++ expect(+ getJournalPostingPolicyDecision({+ sourceType: "Purchase Receipt",+ settings,+ docSync: DOC_SYNC_ON+ })+ ).toEqual({ kind: "push", granularity: "individual" });++ // Manufacturing defaults: Production Event + Job Consumption summarize+ expect(+ getJournalPostingPolicyDecision({+ sourceType: "Production Event",+ settings,+ docSync: DOC_SYNC_ON+ })+ ).toEqual({ kind: "push", granularity: "daily-summary" });+ });++ it("always-on: a stored enabled:false cannot exclude an automated type; Manual is permanently excluded (MANUAL_DISABLED)", () => {+ // Always-on model: automated journal types push regardless of any stored+ // per-type enable flag (kept in the schema for backward-compatible+ // parsing but never read by the decision).+ const settings = settingsWith({+ sourceTypes: {+ "Purchase Receipt": { enabled: false, granularity: "individual" }+ }+ });++ const stillPushes = getJournalPostingPolicyDecision({+ sourceType: "Purchase Receipt",+ settings,+ docSync: DOC_SYNC_ON+ });+ expect(stillPushes).toMatchObject({ kind: "push" });++ // Manual is the only non-syncable type (POSTING_POLICY syncable: false) —+ // excluded permanently, regardless of stored config.+ const manual = getJournalPostingPolicyDecision({+ sourceType: "Manual",+ settings,+ docSync: DOC_SYNC_ON+ });+ expect(manual).toMatchObject({+ kind: "exclude",+ reason: "MANUAL_DISABLED"+ });+ });++ it("excludes unknown and missing source types", () => {+ const settings = settingsWith();+ expect(+ getJournalPostingPolicyDecision({+ sourceType: "Not A Source Type",+ settings,+ docSync: DOC_SYNC_ON+ })+ ).toMatchObject({ kind: "exclude", reason: "SOURCE_TYPE_DISABLED" });+ expect(+ getJournalPostingPolicyDecision({+ sourceType: null,+ settings,+ docSync: DOC_SYNC_ON+ })+ ).toMatchObject({ kind: "exclude", reason: "SOURCE_TYPE_DISABLED" });+ });++ it("hands Inventory Adjustment to the entity syncer when that sync is enabled", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Inventory Adjustment",+ settings: settingsWith(),+ docSync: DOC_SYNC_ON,+ inventoryAdjustmentEntitySyncEnabled: true+ });+ expect(decision).toMatchObject({+ kind: "exclude",+ reason: "DOC_BACKED",+ backingDocument: { entityType: "inventoryAdjustment" }+ });+ });++ describe("documents mode (default families)", () => {+ it("DOC_BACKED when the backing document sync is enabled", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Sales Invoice",+ settings: settingsWith(),+ docSync: DOC_SYNC_ON+ });+ expect(decision).toMatchObject({+ kind: "exclude",+ reason: "DOC_BACKED",+ backingDocument: { entityType: "invoice" }+ });+ });++ it("parks DOC_SYNC_DISABLED when the backing document sync is off (delivery hole must be loud)", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Purchase Invoice",+ settings: settingsWith(),+ docSync: DOC_SYNC_OFF+ });+ expect(decision).toMatchObject({+ kind: "warn",+ code: "DOC_SYNC_DISABLED"+ });+ });++ it("parks memos/returns as DOC_SYNC_DISABLED (no document representation exists yet)", () => {+ for (const sourceType of [+ "Credit Memo",+ "Debit Memo",+ "Sales Return",+ "Purchase Return"+ ]) {+ const decision = getJournalPostingPolicyDecision({+ sourceType,+ settings: settingsWith(),+ docSync: DOC_SYNC_ON+ });+ expect(decision, sourceType).toMatchObject({+ kind: "warn",+ code: "DOC_SYNC_DISABLED"+ });+ }+ });++ it("DOC_BACKED for Payment regardless of doc flags (cash application is provider-native)", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Payment",+ settings: settingsWith(),+ docSync: DOC_SYNC_OFF,+ paymentFamily: "ar"+ });+ expect(decision).toMatchObject({+ kind: "exclude",+ reason: "DOC_BACKED",+ backingDocument: { entityType: "payment" }+ });+ });+ });++ describe("journals mode", () => {+ const journalsAr = settingsWith({+ families: { ar: "journals", ap: "documents" }+ });++ it("pushes the family's journals with forced individual granularity", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Sales Invoice",+ settings: journalsAr,+ docSync: { invoiceEnabled: false, billEnabled: true }+ });+ expect(decision).toEqual({ kind: "push", granularity: "individual" });++ // memos ride the family too — no document exists to double-post against+ const memo = getJournalPostingPolicyDecision({+ sourceType: "Credit Memo",+ settings: journalsAr,+ docSync: { invoiceEnabled: false, billEnabled: true }+ });+ expect(memo).toEqual({ kind: "push", granularity: "individual" });+ });++ it("parks DOUBLE_REPRESENTATION when the document sync is contradictorily enabled", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Sales Invoice",+ settings: journalsAr,+ docSync: DOC_SYNC_ON+ });+ expect(decision).toMatchObject({+ kind: "warn",+ code: "DOUBLE_REPRESENTATION"+ });+ });++ it("leaves the other family in documents mode untouched", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Purchase Invoice",+ settings: journalsAr,+ docSync: { invoiceEnabled: false, billEnabled: true }+ });+ expect(decision).toMatchObject({+ kind: "exclude",+ reason: "DOC_BACKED",+ backingDocument: { entityType: "bill" }+ });+ });+ });++ describe("none mode", () => {+ it("excludes the family with FAMILY_OFF (explicit, visible opt-out)", () => {+ const settings = settingsWith({+ families: { ar: "none", ap: "documents" }+ });+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Sales Invoice",+ settings,+ docSync: DOC_SYNC_ON+ });+ expect(decision).toMatchObject({ kind: "exclude", reason: "FAMILY_OFF" });+ });+ });++ describe("Payment per-line family resolution", () => {+ const diverging = settingsWith({+ families: { ar: "journals", ap: "documents" }+ });++ it("follows the resolved side when family modes diverge", () => {+ expect(+ getJournalPostingPolicyDecision({+ sourceType: "Payment",+ settings: diverging,+ docSync: { invoiceEnabled: false, billEnabled: true },+ paymentFamily: "ar"+ })+ ).toEqual({ kind: "push", granularity: "individual" });++ expect(+ getJournalPostingPolicyDecision({+ sourceType: "Payment",+ settings: diverging,+ docSync: { invoiceEnabled: false, billEnabled: true },+ paymentFamily: "ap"+ })+ ).toMatchObject({ kind: "exclude", reason: "DOC_BACKED" });+ });++ it("parks PAYMENT_FAMILY_UNRESOLVED when the side is unknown and modes diverge", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Payment",+ settings: diverging,+ docSync: { invoiceEnabled: false, billEnabled: true },+ paymentFamily: null+ });+ expect(decision).toMatchObject({+ kind: "warn",+ code: "PAYMENT_FAMILY_UNRESOLVED"+ });+ });++ it("needs no side when both families share a mode", () => {+ const decision = getJournalPostingPolicyDecision({+ sourceType: "Payment",+ settings: settingsWith(),+ docSync: DOC_SYNC_ON,+ paymentFamily: null+ });+ expect(decision).toMatchObject({+ kind: "exclude",+ reason: "DOC_BACKED"+ });+ });+ });+});diff --git a/packages/ee/src/accounting/core/posting.test.ts b/packages/ee/src/accounting/core/posting.test.tsnew file mode 100644index 0000000000..697b4dd3fa--- /dev/null+++ b/packages/ee/src/accounting/core/posting.test.ts@@ -0,0 +1,676 @@+import { describe, expect, it } from "vitest";+import {+ aggregateJournalEntriesForDate,+ collectUnmappedDimensionValues,+ getDailyConsolidationNarration,+ getDimensionTupleKey,+ getPostingSyncSourceTypeSkipReason,+ isPaymentSyncbackEnabled,+ JournalEntrySyncError,+ netJournalLinesPerAccount,+ resolvePostingSyncSettings,+ runJournalEntryPreflight,+ toDebitSignedAmount+} from "./posting";+import type { Accounting } from "./types";++// ── Daily-consolidation aggregation (Task 12) ────────────────────────────────+// One aggregated journal per posting date: signed amounts summed per account+// across the member journals, zero-net accounts dropped, balance asserted.++function journal(+ id: string,+ postingDate: string,+ lines: Array<{+ accountId: string | null;+ amount: number;+ dimensions?: Array<{ dimensionId: string; valueId: string }>;+ }>+): Accounting.JournalEntry {+ return {+ id,+ companyId: "co_1",+ journalEntryId: `JE-${id}`,+ description: null,+ postingDate,+ status: "Posted",+ sourceType: "Purchase Receipt",+ reversalOfId: null,+ reversedById: null,+ reversal: false,+ lines: lines.map((line, index) => ({+ id: `${id}-line-${index}`,+ accountId: line.accountId,+ amount: line.amount,+ description: null,+ ...(line.dimensions ? { dimensions: line.dimensions } : {})+ })),+ updatedAt: "2026-07-08T12:00:00.000Z"+ };+}++describe("netJournalLinesPerAccount", () => {+ it("sums signed amounts per account with cents math", () => {+ const netted = netJournalLinesPerAccount([+ { accountId: "acct_a", amount: 0.1 },+ { accountId: "acct_a", amount: 0.2 },+ { accountId: "acct_b", amount: -0.3 }+ ]);+ // 0.1 + 0.2 must be exactly 0.3, not 0.30000000000000004+ expect(netted.get("acct_a")).toBe(0.3);+ expect(netted.get("acct_b")).toBe(-0.3);+ });++ it("nets lines without an account into the null bucket", () => {+ const netted = netJournalLinesPerAccount([+ { accountId: null, amount: 5 },+ { accountId: null, amount: 2.5 }+ ]);+ expect(netted.get(null)).toBe(7.5);+ });++ it("normalizes a fully-cancelled account to exactly 0", () => {+ const netted = netJournalLinesPerAccount([+ { accountId: "acct_a", amount: 10 },+ { accountId: "acct_a", amount: -10 }+ ]);+ expect(Object.is(netted.get("acct_a"), 0)).toBe(true);+ });+});++describe("aggregateJournalEntriesForDate", () => {+ it("aggregates 3 journals over 2 accounts into one balanced payload with summed lines", () => {+ const aggregate = aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 100 },+ { accountId: "acct_b", amount: -100 }+ ]),+ journal("j2", "2026-07-08", [+ { accountId: "acct_a", amount: 50.25 },+ { accountId: "acct_b", amount: -50.25 }+ ]),+ journal("j3", "2026-07-08", [+ { accountId: "acct_a", amount: 25.5 },+ { accountId: "acct_b", amount: -25.5 }+ ])+ ]+ });++ expect(aggregate.journal.id).toBe("daily:xero:2026-07-08");+ expect(aggregate.journal.postingDate).toBe("2026-07-08");+ expect(aggregate.journal.status).toBe("Posted");+ expect(aggregate.journalIds).toEqual(["j1", "j2", "j3"]);+ expect(aggregate.narration).toBe(+ "Carbon daily summary 2026-07-08 — 3 journals"+ );++ expect(aggregate.journal.lines).toHaveLength(2);+ expect(aggregate.journal.lines).toEqual([+ expect.objectContaining({ accountId: "acct_a", amount: 175.75 }),+ expect.objectContaining({ accountId: "acct_b", amount: -175.75 })+ ]);++ // The aggregate itself balances+ const total = aggregate.journal.lines.reduce(+ (sum, line) => sum + Math.round(line.amount * 100),+ 0+ );+ expect(total).toBe(0);+ });++ it("drops accounts that net to zero across journals", () => {+ const aggregate = aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 100 },+ { accountId: "acct_c", amount: -100 }+ ]),+ journal("j2", "2026-07-08", [+ { accountId: "acct_a", amount: -100 },+ { accountId: "acct_b", amount: 100 }+ ])+ ]+ });++ // acct_a nets to zero and is dropped; b and c survive+ expect(aggregate.journal.lines.map((line) => line.accountId)).toEqual([+ "acct_b",+ "acct_c"+ ]);+ expect(aggregate.journal.lines.map((line) => line.amount)).toEqual([+ 100, -100+ ]);+ });++ it("produces an empty-line aggregate when every account fully cancels (net-zero day)", () => {+ const aggregate = aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 100 },+ { accountId: "acct_b", amount: -100 }+ ]),+ journal("j2", "2026-07-08", [+ { accountId: "acct_a", amount: -100 },+ { accountId: "acct_b", amount: 100 }+ ])+ ]+ });++ expect(aggregate.journal.lines).toEqual([]);+ });++ it("throws JournalEntrySyncError UNBALANCED_JOURNAL on unbalanced input", () => {+ const build = () =>+ aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 100 },+ { accountId: "acct_b", amount: -90 }+ ])+ ]+ });++ expect(build).toThrowError(JournalEntrySyncError);+ try {+ build();+ } catch (error) {+ const failure = (error as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNBALANCED_JOURNAL");+ expect(failure.warning).toBe(false);+ expect(failure.metadata).toEqual({+ postingDate: "2026-07-08",+ journalIds: ["j1"]+ });+ }+ });++ it("throws a plain Error when a member journal is dated off the batch date", () => {+ expect(() =>+ aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ journal("j1", "2026-07-09", [+ { accountId: "acct_a", amount: 100 },+ { accountId: "acct_b", amount: -100 }+ ])+ ]+ })+ ).toThrowError(/dated 2026-07-09, not 2026-07-08/);+ });++ it("throws a plain Error on an empty member list", () => {+ expect(() =>+ aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: []+ })+ ).toThrowError(/zero journals/);+ });+});++describe("getDailyConsolidationNarration", () => {+ it("matches the spec narration format", () => {+ expect(getDailyConsolidationNarration("2026-07-08", 12)).toBe(+ "Carbon daily summary 2026-07-08 — 12 journals"+ );+ });++ it("carries the source type for v3 per-source-type batches", () => {+ expect(+ getDailyConsolidationNarration("2026-07-08", 3, "Production Event")+ ).toBe("Carbon daily summary 2026-07-08 — Production Event — 3 journals");+ });+});++// ── Source-type gate ─────────────────────────────────────────────────────────++describe("getPostingSyncSourceTypeSkipReason", () => {+ const settings = resolvePostingSyncSettings(null);++ it("pushes the quality-scrap source types by default", () => {+ expect(+ getPostingSyncSourceTypeSkipReason("Non-Conformance", settings)+ ).toBeNull();+ expect(+ getPostingSyncSourceTypeSkipReason("Inbound Inspection", settings)+ ).toBeNull();+ });++ it("pushes Inventory Adjustment journals by default", () => {+ expect(+ getPostingSyncSourceTypeSkipReason("Inventory Adjustment", settings)+ ).toBeNull();+ expect(+ getPostingSyncSourceTypeSkipReason("Inventory Adjustment", settings, {+ inventoryAdjustmentEntitySyncEnabled: false+ })+ ).toBeNull();+ });++ it("skips Inventory Adjustment journals while the entity syncer owns them", () => {+ const reason = getPostingSyncSourceTypeSkipReason(+ "Inventory Adjustment",+ settings,+ { inventoryAdjustmentEntitySyncEnabled: true }+ );+ expect(reason).toContain("double-post");+ });++ it("keeps document-backed source types excluded regardless of the guard", () => {+ expect(+ getPostingSyncSourceTypeSkipReason("Sales Invoice", settings, {+ inventoryAdjustmentEntitySyncEnabled: true+ })+ ).toContain("document-backed");+ });++ it("skips unknown source types with a not-enabled reason", () => {+ expect(+ getPostingSyncSourceTypeSkipReason("Not A Source Type", settings)+ ).toContain("not enabled");+ });+});++// ── Natural-balance → debit-signed conversion ───────────────────────────────+// Carbon's post-* edge functions sign journalLine.amount by the account's+// NATURAL balance (credit("liability", x) stores +x), so the engine converts+// at fetch time; see toDebitSignedAmount.++describe("toDebitSignedAmount", () => {+ it("keeps Asset/Expense signs (natural balance is debit)", () => {+ expect(toDebitSignedAmount("Asset", 300)).toBe(300);+ expect(toDebitSignedAmount("Expense", 42.5)).toBe(42.5);+ expect(toDebitSignedAmount("Asset", -300)).toBe(-300);+ });++ it("negates Liability/Equity/Revenue (natural balance is credit)", () => {+ expect(toDebitSignedAmount("Liability", 300)).toBe(-300);+ expect(toDebitSignedAmount("Equity", 100)).toBe(-100);+ expect(toDebitSignedAmount("Revenue", 50)).toBe(-50);+ expect(toDebitSignedAmount("Liability", -300)).toBe(300);+ });++ it("passes unknown/missing classes through unchanged", () => {+ expect(toDebitSignedAmount(null, 10)).toBe(10);+ expect(toDebitSignedAmount(undefined, 10)).toBe(10);+ });++ it("balances a real receipt journal: inventory debit + GR/IR credit", () => {+ // As stored by post-receipt: both lines +300 (natural balance)+ const converted = [+ toDebitSignedAmount("Asset", 300), // Raw Materials+ toDebitSignedAmount("Liability", 300) // Goods Received Not Invoiced+ ];+ expect(converted.reduce((a, b) => a + b, 0)).toBe(0);+ });+});++// ── Dimension pre-flight (Phase 2, spec §3) ─────────────────────────────────++const LOCATION_DIM = "dim_loc";+const ATLANTA = { dimensionId: LOCATION_DIM, valueId: "loc_atl" };+const BOSTON = { dimensionId: LOCATION_DIM, valueId: "loc_bos" };++function dimensionSettings(onUnmapped: "warn" | "drop") {+ return resolvePostingSyncSettings({+ settings: {+ postingSync: {+ enabled: true,+ dimensionSlots: [{ dimensionId: LOCATION_DIM, target: "class" }],+ onUnmappedDimensionValue: onUnmapped+ }+ }+ });+}++describe("collectUnmappedDimensionValues", () => {+ const slots = [{ dimensionId: LOCATION_DIM }];++ it("returns distinct slotted values with no provider mapping", () => {+ const unmapped = collectUnmappedDimensionValues(+ [+ { dimensions: [ATLANTA] },+ { dimensions: [ATLANTA, BOSTON] }, // Atlanta repeats — reported once+ { dimensions: undefined }+ ],+ slots,+ new Map()+ );++ expect(unmapped).toEqual([ATLANTA, BOSTON]);+ });++ it("ignores mapped values and unslotted dimensions entirely", () => {+ const unmapped = collectUnmappedDimensionValues(+ [+ {+ dimensions: [+ ATLANTA,+ { dimensionId: "dim_unslotted", valueId: "x" } // not slotted → untouched+ ]+ }+ ],+ slots,+ new Map([["dim_loc:loc_atl", "opt-1"]])+ );++ expect(unmapped).toEqual([]);+ });++ it("returns [] when no slots are configured", () => {+ expect(+ collectUnmappedDimensionValues([{ dimensions: [ATLANTA] }], [], new Map())+ ).toEqual([]);+ });+});++describe("runJournalEntryPreflight — dimension rule", () => {+ const accountCodesById = new Map([+ ["acct_a", "1400"],+ ["acct_b", "2100"]+ ]);+ const baseArgs = {+ accountCodesById,+ controlAccountIds: new Set<string>(),+ lockDate: null+ };+ const dimensionedJournal = journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 100, dimensions: [ATLANTA] },+ { accountId: "acct_b", amount: -100 }+ ]);++ it("parks with UNMAPPED_DIMENSION_VALUES (Warning) under the warn policy", () => {+ const result = runJournalEntryPreflight({+ ...baseArgs,+ journal: dimensionedJournal,+ settings: dimensionSettings("warn"),+ dimensionValueMappings: new Map()+ });++ expect(result.failure?.errorCode).toBe("UNMAPPED_DIMENSION_VALUES");+ expect(result.failure?.warning).toBe(true);+ expect(result.failure?.metadata).toEqual({+ unmappedDimensionValues: [ATLANTA]+ });+ });++ it("passes and reports the dropped values under the drop policy (recorded, never silent)", () => {+ const result = runJournalEntryPreflight({+ ...baseArgs,+ journal: dimensionedJournal,+ settings: dimensionSettings("drop"),+ dimensionValueMappings: new Map()+ });++ expect(result.failure).toBeNull();+ if (result.failure === null) {+ expect(result.pushDate).toBe("2026-07-08");+ expect(result.droppedDimensionValues).toEqual([ATLANTA]);+ }+ });++ it("passes cleanly when every slotted value is mapped", () => {+ const result = runJournalEntryPreflight({+ ...baseArgs,+ journal: dimensionedJournal,+ settings: dimensionSettings("warn"),+ dimensionValueMappings: new Map([["dim_loc:loc_atl", "opt-1"]])+ });++ expect(result.failure).toBeNull();+ if (result.failure === null) {+ expect(result.droppedDimensionValues).toBeUndefined();+ }+ });++ it("skips the rule entirely for callers that do not load dimension mappings", () => {+ const result = runJournalEntryPreflight({+ ...baseArgs,+ journal: dimensionedJournal,+ settings: dimensionSettings("warn")+ // no dimensionValueMappings — legacy path+ });++ expect(result.failure).toBeNull();+ });+});++// ── Dimension-tuple grouping + rounding residue (spec §4) ───────────────────++describe("getDimensionTupleKey", () => {+ it("is canonical: sorted by dimensionId, independent of input order", () => {+ const a = getDimensionTupleKey([+ { dimensionId: "dim_b", valueId: "2" },+ { dimensionId: "dim_a", valueId: "1" }+ ]);+ const b = getDimensionTupleKey([+ { dimensionId: "dim_a", valueId: "1" },+ { dimensionId: "dim_b", valueId: "2" }+ ]);+ expect(a).toBe(b);+ expect(a).toBe("dim_a=1|dim_b=2");+ });++ it("restricts to the slotted dimensions when provided", () => {+ const key = getDimensionTupleKey(+ [ATLANTA, { dimensionId: "dim_unslotted", valueId: "x" }],+ new Set([LOCATION_DIM])+ );+ expect(key).toBe("dim_loc=loc_atl");+ });++ it("returns the empty tuple for lines without dimensions", () => {+ expect(getDimensionTupleKey(undefined)).toBe("");+ expect(getDimensionTupleKey([])).toBe("");+ });+});++describe("aggregateJournalEntriesForDate — dimension tuples", () => {+ it("groups by (accountId, dimension tuple): two locations produce two lines on the same account", () => {+ const aggregate = aggregateJournalEntriesForDate({+ batchId: "daily:xero:production-event:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ sourceType: "Production Event",+ journals: [+ journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 100, dimensions: [ATLANTA] },+ { accountId: "acct_b", amount: -100 }+ ]),+ journal("j2", "2026-07-08", [+ { accountId: "acct_a", amount: 50, dimensions: [BOSTON] },+ { accountId: "acct_b", amount: -50 }+ ]),+ journal("j3", "2026-07-08", [+ { accountId: "acct_a", amount: 25, dimensions: [ATLANTA] },+ { accountId: "acct_b", amount: -25 }+ ])+ ],+ slottedDimensionIds: [LOCATION_DIM]+ });++ expect(aggregate.journal.lines).toEqual([+ expect.objectContaining({+ accountId: "acct_a",+ amount: 125,+ dimensions: [ATLANTA]+ }),+ expect.objectContaining({+ accountId: "acct_a",+ amount: 50,+ dimensions: [BOSTON]+ }),+ expect.objectContaining({ accountId: "acct_b", amount: -175 })+ ]);+ expect(+ aggregate.journal.lines.reduce(+ (sum, line) => sum + Math.round(line.amount * 100),+ 0+ )+ ).toBe(0);+ });++ it("keeps unslotted dimensions out of the tuple when slottedDimensionIds is provided", () => {+ const aggregate = aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ journal("j1", "2026-07-08", [+ {+ accountId: "acct_a",+ amount: 100,+ dimensions: [{ dimensionId: "dim_item", valueId: "item_1" }]+ },+ {+ accountId: "acct_a",+ amount: 50,+ dimensions: [{ dimensionId: "dim_item", valueId: "item_2" }]+ },+ { accountId: "acct_b", amount: -150 }+ ])+ ],+ slottedDimensionIds: [LOCATION_DIM]+ });++ // Both item-dimensioned lines collapse into one per-account bucket+ expect(aggregate.journal.lines).toEqual([+ expect.objectContaining({ accountId: "acct_a", amount: 150 }),+ expect.objectContaining({ accountId: "acct_b", amount: -150 })+ ]);+ });++ it("books post-2dp rounding residue to the rounding account when provided", () => {+ const aggregate = aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ // Sub-cent input: +10.005 rounds to 10.01, -10.004 rounds to -10.00+ journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 10.005 },+ { accountId: "acct_b", amount: -10.004 }+ ])+ ],+ roundingAccountId: "acct_rounding"+ });++ const roundingLine = aggregate.journal.lines.find(+ (line) => line.accountId === "acct_rounding"+ );+ expect(roundingLine?.amount).toBe(-0.01);+ expect(+ aggregate.journal.lines.reduce(+ (sum, line) => sum + Math.round(line.amount * 100),+ 0+ )+ ).toBe(0);+ });++ it("still throws UNBALANCED_JOURNAL without a rounding account (legacy behavior)", () => {+ expect(() =>+ aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 10.005 },+ { accountId: "acct_b", amount: -10.004 }+ ])+ ]+ })+ ).toThrowError(JournalEntrySyncError);+ });++ it("refuses to bury a real imbalance in the rounding account (residue cap: half a cent per line)", () => {+ expect(() =>+ aggregateJournalEntriesForDate({+ batchId: "daily:xero:2026-07-08",+ companyId: "co_1",+ postingDate: "2026-07-08",+ journals: [+ journal("j1", "2026-07-08", [+ { accountId: "acct_a", amount: 100 },+ { accountId: "acct_b", amount: -95 }+ ])+ ],+ roundingAccountId: "acct_rounding"+ })+ ).toThrowError(JournalEntrySyncError);+ });+});++// ── Documents-mode payment sync-back gate (Phase 0.4) ────────────────────────+// Inbound payment pull is allowed for a family only when it is in `documents`+// mode; a missing/invalid config defaults to documents (sync-back enabled).++describe("isPaymentSyncbackEnabled", () => {+ function metadata(family: "ar" | "ap", mode: string) {+ return { settings: { postingSync: { families: { [family]: mode } } } };+ }++ it("returns true when the family is in documents mode", () => {+ expect(isPaymentSyncbackEnabled(metadata("ar", "documents"), "ar")).toBe(+ true+ );+ expect(isPaymentSyncbackEnabled(metadata("ap", "documents"), "ap")).toBe(+ true+ );+ });++ it("returns false when the family is in journals mode", () => {+ expect(isPaymentSyncbackEnabled(metadata("ar", "journals"), "ar")).toBe(+ false+ );+ expect(isPaymentSyncbackEnabled(metadata("ap", "journals"), "ap")).toBe(+ false+ );+ });++ it("returns false when the family is set to none", () => {+ expect(isPaymentSyncbackEnabled(metadata("ar", "none"), "ar")).toBe(false);+ expect(isPaymentSyncbackEnabled(metadata("ap", "none"), "ap")).toBe(false);+ });++ it("defaults to enabled (documents) for absent or invalid metadata", () => {+ expect(isPaymentSyncbackEnabled(undefined, "ar")).toBe(true);+ expect(isPaymentSyncbackEnabled(null, "ap")).toBe(true);+ expect(isPaymentSyncbackEnabled({}, "ar")).toBe(true);+ expect(isPaymentSyncbackEnabled({ settings: {} }, "ap")).toBe(true);+ // A bad stored fragment resolves to defaults, not a crash.+ expect(+ isPaymentSyncbackEnabled(+ { settings: { postingSync: { families: "nonsense" } } },+ "ar"+ )+ ).toBe(true);+ });++ it("gates each family independently", () => {+ const meta = {+ settings: {+ postingSync: { families: { ar: "documents", ap: "journals" } }+ }+ };+ expect(isPaymentSyncbackEnabled(meta, "ar")).toBe(true);+ expect(isPaymentSyncbackEnabled(meta, "ap")).toBe(false);+ });+});diff --git a/packages/ee/src/accounting/core/posting.ts b/packages/ee/src/accounting/core/posting.tsnew file mode 100644index 0000000000..d8b9a649fd--- /dev/null+++ b/packages/ee/src/accounting/core/posting.ts@@ -0,0 +1,1061 @@+import type z from "zod";+import {+ type JournalEntryLineDimensionSchema,+ type JournalEntrySourceType,+ POSTING_POLICY,+ type PostingDecisionReasonCode,+ type PostingGranularity,+ PostingSyncSettingsSchema+} from "./models";+import type { Accounting } from "./types";++export type JournalLineDimensionRef = z.infer<+ typeof JournalEntryLineDimensionSchema+>;++/**+ * Shared posting-sync helpers (Phase B journal push, reused by every+ * provider's JournalEntrySyncer): per-company settings resolution, the+ * machine-readable pre-flight failure envelope, and the pure pre-flight+ * rules (account mapping, AR/AP control accounts, period lock, balance).+ *+ * Everything here is provider-agnostic — provider-specific inputs (the+ * account-code map, the org lock date) are resolved by the syncer and+ * passed in.+ */++export type PostingSyncSettings = z.output<typeof PostingSyncSettingsSchema>;++export const DEFAULT_POSTING_SYNC_SETTINGS: PostingSyncSettings =+ PostingSyncSettingsSchema.parse({});++/**+ * Resolve the per-company posting-sync settings stored at+ * `companyIntegration.metadata.settings.postingSync`. Missing or invalid+ * fragments resolve to the defaults (posting sync disabled) with a warning+ * — a bad stored config must never break sync (same contract as+ * resolveSyncConfig).+ */+export function resolvePostingSyncSettings(+ metadata: unknown+): PostingSyncSettings {+ if (typeof metadata !== "object" || metadata === null) {+ return { ...DEFAULT_POSTING_SYNC_SETTINGS };+ }++ const settings = (metadata as { settings?: unknown }).settings;+ if (typeof settings !== "object" || settings === null) {+ return { ...DEFAULT_POSTING_SYNC_SETTINGS };+ }++ const fragment = (settings as { postingSync?: unknown }).postingSync;+ if (fragment === undefined) {+ return { ...DEFAULT_POSTING_SYNC_SETTINGS };+ }++ const parsed = PostingSyncSettingsSchema.safeParse(fragment);+ if (!parsed.success) {+ console.warn(+ "Ignoring invalid stored postingSync settings:",+ parsed.error.issues+ );+ return { ...DEFAULT_POSTING_SYNC_SETTINGS };+ }++ return parsed.data;+}++/**+ * Whether inbound payment sync-back is allowed for an AR/AP family: true+ * ONLY when that family is in `documents` mode. Payments settle the pushed+ * documents, so pulling provider payments back is coherent only when Carbon+ * owns the documents (documents mode). `journals`/`none` families do not pull+ * payments. A missing/invalid config resolves to the defaults (documents for+ * both families), so an unconfigured integration keeps sync-back ENABLED —+ * preserving today's Rillet AR behavior.+ */+export function isPaymentSyncbackEnabled(+ integrationMetadata: unknown,+ family: "ar" | "ap"+): boolean {+ return (+ resolvePostingSyncSettings(integrationMetadata).families[family] ===+ "documents"+ );+}++// /********************************************************\+// * Posting policy decision (v3) *+// \********************************************************/++/**+ * Whether each backing DOCUMENT entity sync is enabled in the company's+ * resolved sync config — decides delivery for document-represented source+ * types in `documents` family mode.+ */+export type PostingSyncDocumentSyncFlags = {+ invoiceEnabled: boolean;+ billEnabled: boolean;+};++export type JournalPostingPolicyDecision =+ | { kind: "push"; granularity: PostingGranularity }+ | {+ kind: "exclude";+ reason: PostingDecisionReasonCode;+ message: string;+ /** The synced entity that carries this journal's amounts (DOC_BACKED). */+ backingDocument?: { entityType: string };+ }+ | {+ kind: "warn";+ code:+ | "DOC_SYNC_DISABLED"+ | "DOUBLE_REPRESENTATION"+ | "PAYMENT_FAMILY_UNRESOLVED";+ message: string;+ };++/**+ * The v3 posting policy decision for one posted journal (spec §1–2): every+ * journal gets exactly one disposition. Pure — the caller resolves the+ * settings, the doc-sync flags, and (for Payment journals when the AR/AP+ * family modes diverge) which side the journal's control-account lines+ * touch.+ *+ * - journal-represented types: push per the per-source-type config+ * (Manual → MANUAL_DISABLED when off; others → SOURCE_TYPE_DISABLED);+ * - "Inventory Adjustment" while the inventoryAdjustment ENTITY sync is+ * enabled → DOC_BACKED (the entity syncer pushes the same economic event;+ * pushing the journal too would double-post);+ * - document-represented types follow the family mode:+ * `documents` → DOC_BACKED when the backing document actually syncs+ * (invoice/bill enabled; Payment is provider-native cash application),+ * `Warning/DOC_SYNC_DISABLED` when it does not (a silent delivery hole is+ * the one outcome this system must not produce);+ * `journals` → push (forced individual granularity), or+ * `Warning/DOUBLE_REPRESENTATION` if the document sync is somehow also on;+ * `none` → FAMILY_OFF (explicit, visible opt-out).+ */+export function getJournalPostingPolicyDecision(args: {+ sourceType: string | null | undefined;+ settings: PostingSyncSettings;+ docSync: PostingSyncDocumentSyncFlags;+ /**+ * "ar" | "ap" for Payment journals, resolved from which control account+ * the lines touch; null when unresolved. Ignored for static-family types.+ */+ paymentFamily?: "ar" | "ap" | null;+ inventoryAdjustmentEntitySyncEnabled?: boolean;+}): JournalPostingPolicyDecision {+ const { settings } = args;++ if (!args.sourceType) {+ return {+ kind: "exclude",+ reason: "SOURCE_TYPE_DISABLED",+ message:+ "Journal has no source type; only configured source types are pushed"+ };+ }++ const sourceType = args.sourceType as JournalEntrySourceType;+ const policy = POSTING_POLICY[sourceType];++ if (!policy) {+ return {+ kind: "exclude",+ reason: "SOURCE_TYPE_DISABLED",+ message: `Source type "${args.sourceType}" is not enabled for posting sync`+ };+ }++ if (+ sourceType === "Inventory Adjustment" &&+ args.inventoryAdjustmentEntitySyncEnabled+ ) {+ return {+ kind: "exclude",+ reason: "DOC_BACKED",+ message:+ 'Source type "Inventory Adjustment" is excluded while inventory-adjustment entity sync is enabled (the entity syncer already pushes it; pushing the journal too would double-post)',+ backingDocument: { entityType: "inventoryAdjustment" }+ };+ }++ const config = settings.sourceTypes[sourceType];++ if (policy.representation === "journal") {+ // Manual journals are NEVER synced — the external ledger owns manual+ // journals (payroll, etc.) and they can touch arbitrary/unmapped accounts.+ // Every other automated journal-represented posting always pushes; there is+ // no per-source-type on/off (granularity remains configurable).+ if (policy.syncable === false) {+ return {+ kind: "exclude",+ reason: "MANUAL_DISABLED",+ message:+ "Manual journals are never synced — the external ledger owns manual journals; Carbon syncs only its automated postings"+ };+ }+ return { kind: "push", granularity: config.granularity };+ }++ // Document-represented: resolve the family, then the family mode.+ const family =+ policy.family === "per-line" ? (args.paymentFamily ?? null) : policy.family;++ if (!family) {+ // Payment with modes diverging and no resolvable side. Unreachable when+ // both families share a mode (callers may skip line inspection then).+ if (settings.families.ar === settings.families.ap) {+ return decideDocumentFamily({+ sourceType,+ policy,+ mode: settings.families.ar,+ docSync: args.docSync+ });+ }+ return {+ kind: "warn",+ code: "PAYMENT_FAMILY_UNRESOLVED",+ message: `Journal source type "Payment" could not be resolved to AR or AP from its control-account lines while the family modes diverge (ar: ${settings.families.ar}, ap: ${settings.families.ap}); resolve the payment's side or align the family modes, then retry.`+ };+ }++ return decideDocumentFamily({+ sourceType,+ policy,+ mode: settings.families[family],+ docSync: args.docSync+ });+}++function decideDocumentFamily(args: {+ sourceType: JournalEntrySourceType;+ policy: (typeof POSTING_POLICY)[JournalEntrySourceType];+ mode: PostingSyncSettings["families"]["ar"];+ docSync: PostingSyncDocumentSyncFlags;+}): JournalPostingPolicyDecision {+ const backingEntityType = args.policy.backingEntityType ?? null;+ const documentSyncEnabled =+ backingEntityType === "invoice"+ ? args.docSync.invoiceEnabled+ : backingEntityType === "bill"+ ? args.docSync.billEnabled+ : backingEntityType === "payment"+ ? true // cash application is provider-native, not a Carbon-pushed document+ : false; // memos/returns have no document representation yet++ if (args.mode === "none") {+ return {+ kind: "exclude",+ reason: "FAMILY_OFF",+ message: `Source type "${args.sourceType}" is excluded: its AR/AP family is set to "none" (this family is handled outside the sync).`+ };+ }++ if (args.mode === "journals") {+ if (backingEntityType && backingEntityType !== "payment") {+ // journals mode requires the family's document sync to be OFF; a+ // contradictory config must be loud, never a double-post.+ if (documentSyncEnabled) {+ return {+ kind: "warn",+ code: "DOUBLE_REPRESENTATION",+ message: `Source type "${args.sourceType}" is set to journal representation, but the ${backingEntityType} document sync is also enabled — pushing both would double-post. Disable the document sync or switch the family back to documents, then retry.`+ };+ }+ }+ // AR/AP journals are forced individual: provider constraints (QBO's one+ // AR/AP line per JE with a party ref) make cross-document summaries+ // structurally impossible.+ return { kind: "push", granularity: "individual" };+ }++ // documents mode+ if (!documentSyncEnabled) {+ const detail =+ backingEntityType === null+ ? `Source type "${args.sourceType}" has no document representation yet (credit/debit memos and returns are not pushed as provider documents), so its amounts have NOT reached the external GL. Switch the family to journal representation when available, or handle these in the provider.`+ : `Source type "${args.sourceType}" is document-represented, but the ${backingEntityType} document sync is disabled — its amounts would never reach the external GL. Enable the ${backingEntityType} sync (or switch the family representation), then retry.`;+ return { kind: "warn", code: "DOC_SYNC_DISABLED", message: detail };+ }++ return {+ kind: "exclude",+ reason: "DOC_BACKED",+ message: `Source type "${args.sourceType}" is document-backed and excluded from posting sync (the synced document already books it)`,+ ...(backingEntityType+ ? { backingDocument: { entityType: backingEntityType } }+ : {})+ };+}++/**+ * Backstop source-type gate used by the provider journal syncers at drain+ * time (the authoritative disposition is recorded at enqueue by+ * getJournalPostingPolicyDecision — this keeps a conservatively-excluding+ * second gate in front of any provider call). Returns a human-readable skip+ * reason, or null when the journal is pushable. The backstop lacks the+ * resolved sync config, so it assumes a SELF-CONSISTENT one (document sync+ * on exactly for documents-mode families) — contradictions are the enqueue+ * decision's job to surface; the backstop's job is never pushing a+ * doc-backed or family-off journal.+ */+/**+ * Convert a Carbon journalLine amount to the engine's debit-signed+ * convention (positive = debit, negative = credit).+ *+ * Carbon's post-* edge functions sign amounts by the account's NATURAL+ * balance (`credit("liability", x)` stores +x; `debit("liability", x)`+ * stores -x — see functions/lib/utils.ts), so a Carbon journal balances+ * as debits == credits, not as a signed sum of zero. The engine's+ * preflight, netting, consolidation and provider mappers all assume+ * debit-signed amounts, so every journal fetch converts at the edge using+ * the line's account class: Asset/Expense amounts keep their sign (natural+ * balance IS debit), Liability/Equity/Revenue amounts negate. A missing+ * class (no account on the line) passes through unchanged — those lines+ * already fail preflight as unmapped.+ */+/**+ * Normalize a journal.postingDate read through Kysely to YYYY-MM-DD. The+ * pg driver parses DATE columns into JS Date objects at LOCAL midnight, so+ * local components (not toISOString, which can shift a calendar day by the+ * runtime timezone) recover the stored date; strings pass through sliced.+ */+export function toPostingDateString(value: unknown): string {+ if (typeof value === "string") return value.slice(0, 10);+ if (value instanceof Date) {+ const month = String(value.getMonth() + 1).padStart(2, "0");+ const day = String(value.getDate()).padStart(2, "0");+ return `${value.getFullYear()}-${month}-${day}`;+ }+ return String(value);+}++export function toDebitSignedAmount(+ accountClass: string | null | undefined,+ amount: number+): number {+ switch (accountClass) {+ case "Liability":+ case "Equity":+ case "Revenue":+ return -amount;+ default:+ return amount;+ }+}++export function getPostingSyncSourceTypeSkipReason(+ sourceType: string | null | undefined,+ settings: PostingSyncSettings,+ options?: { inventoryAdjustmentEntitySyncEnabled?: boolean }+): string | null {+ const decision = getJournalPostingPolicyDecision({+ sourceType,+ settings,+ docSync: {+ invoiceEnabled: settings.families.ar === "documents",+ billEnabled: settings.families.ap === "documents"+ },+ paymentFamily: null,+ inventoryAdjustmentEntitySyncEnabled:+ options?.inventoryAdjustmentEntitySyncEnabled ?? false+ });++ if (decision.kind === "push") return null;+ return decision.message;+}++// /********************************************************\+// * Reversal entity-id contract *+// \********************************************************/++/**+ * Reversal pushes reuse the journal syncer with the ORIGINAL journal id+ * suffixed ":reversal" as the sync entity id (matches the operation+ * idempotencyKey "<journal.id>:reversal"): the syncer negates the line+ * amounts, and the reversal's provider mapping is stored under the+ * suffixed id so the original push's mapping is untouched.+ */+export const JOURNAL_ENTRY_REVERSAL_SUFFIX = ":reversal";++/** Entity id the drain passes to the journal syncer for a sync operation. */+export function getJournalEntrySyncEntityId(+ journalId: string,+ reversal: boolean+): string {+ return reversal ? `${journalId}${JOURNAL_ENTRY_REVERSAL_SUFFIX}` : journalId;+}++/** Split a journal sync entity id back into the journal id + reversal flag. */+export function parseJournalEntrySyncEntityId(entityId: string): {+ journalId: string;+ reversal: boolean;+} {+ if (entityId.endsWith(JOURNAL_ENTRY_REVERSAL_SUFFIX)) {+ return {+ journalId: entityId.slice(+ 0,+ entityId.length - JOURNAL_ENTRY_REVERSAL_SUFFIX.length+ ),+ reversal: true+ };+ }+ return { journalId: entityId, reversal: false };+}++// /********************************************************\+// * Pre-flight failure envelope *+// \********************************************************/++export const JOURNAL_ENTRY_SYNC_ERROR_CODES = [+ "UNMAPPED_ACCOUNTS",+ // A slot-configured dimension value on a journal line has no provider+ // option mapping (and autoCreate did not resolve it) while the company's+ // onUnmappedDimensionValue policy is "warn" — user-fixable by mapping+ // the value on the integration settings page, then Retry.+ "UNMAPPED_DIMENSION_VALUES",+ "CONTROL_ACCOUNT_LINE",+ "PERIOD_LOCKED",+ "UNBALANCED_JOURNAL",+ // Master-data syncers (QBO customer/vendor/item) reuse the same envelope+ // for user-fixable name failures: QBO's shared name namespace rejects+ // duplicates (Intuit fault 6240) and caps names at 100 characters.+ "NAME_EXISTS",+ "NAME_TOO_LONG",+ // Decision-time Warnings (recorded at enqueue by the posting policy):+ // a doc-represented journal whose backing document sync is off, a+ // journals-mode family whose document sync is contradictorily on, and a+ // Payment journal whose AR/AP side could not be resolved while the+ // family modes diverge.+ "DOC_SYNC_DISABLED",+ "DOUBLE_REPRESENTATION",+ "PAYMENT_FAMILY_UNRESOLVED",+ // Rillet requires external_references on AR_ONLY invoices, and every+ // reference type must be a slug pre-registered (dashboard-only) under+ // Rillet Settings → External References — user-fixable there.+ "EXTERNAL_REFERENCE_TYPE_MISSING",+ // A document push was skipped because the provider rejects edits to a+ // document that already carries payments (Xero paid/partially-paid bills).+ // User-fixable: void/unapply the payment in the provider, then retry.+ "DOC_HAS_PAYMENTS",+ // An outbound payment settles a document (invoice/bill) that hasn't been+ // pushed to the provider yet — the provider payment references the document's+ // remote id, so the document must sync first. A dependency-ordering Warning,+ // NOT an account-mapping problem: it self-resolves once the document syncs+ // (the outbound sweep / manual Retry re-drives the payment). Kept distinct+ // from UNMAPPED_ACCOUNTS so it stops masquerading as a missing account.+ "UNSYNCED_DOCUMENT"+] as const;++export type JournalEntrySyncErrorCode =+ (typeof JOURNAL_ENTRY_SYNC_ERROR_CODES)[number];++/**+ * Machine-readable pre-flight failure. The syncer surfaces it on+ * `SyncResult.error` (typed `unknown` for exactly this); the drain records+ * it with `failOperation({ errorCode, errorMessage, warning })`.+ * `warning: true` → the operation lands `Warning` (user-fixable, retryable+ * after the fix); `warning: false` → `Failed`.+ */+export interface JournalEntrySyncFailure {+ errorCode: JournalEntrySyncErrorCode;+ message: string;+ warning: boolean;+ metadata?: Record<string, unknown>;+}++/**+ * Thrown by the syncer's mapping step on a pre-flight failure. The message+ * is "<errorCode>: <detail>" so paths that flatten errors to strings (the+ * base batch workflow) stay greppable; structured consumers should catch+ * the class and read `failure`.+ */+export class JournalEntrySyncError extends Error {+ readonly failure: JournalEntrySyncFailure;++ constructor(failure: JournalEntrySyncFailure) {+ super(`${failure.errorCode}: ${failure.message}`);+ this.name = "JournalEntrySyncError";+ this.failure = failure;+ }+}++/**+ * Type guard for `SyncResult.error` payloads: true when the value is the+ * structured pre-flight failure the drain should record via+ * `failOperation({ errorCode, errorMessage, warning })`.+ */+export function isJournalEntrySyncFailure(+ value: unknown+): value is JournalEntrySyncFailure {+ if (typeof value !== "object" || value === null) return false;+ const candidate = value as Record<string, unknown>;+ return (+ typeof candidate.errorCode === "string" &&+ (JOURNAL_ENTRY_SYNC_ERROR_CODES as readonly string[]).includes(+ candidate.errorCode+ ) &&+ typeof candidate.message === "string" &&+ typeof candidate.warning === "boolean"+ );+}++// /********************************************************\+// * Pure pre-flight helpers *+// \********************************************************/++/** Round to 2dp, normalizing -0 to 0. */+export function roundCurrency(amount: number): number {+ const rounded = Math.round(amount * 100) / 100;+ return rounded === 0 ? 0 : rounded;+}++/**+ * A journal balances when its signed line amounts (positive = debit,+ * negative = credit) sum to zero at 2dp.+ */+export function isBalancedJournal(+ lines: Array<Pick<Accounting.JournalEntryLine, "amount">>+): boolean {+ const cents = lines.reduce(+ (sum, line) => sum + Math.round(line.amount * 100),+ 0+ );+ return cents === 0;+}++/**+ * Split a journal's lines into unmapped-account buckets: line account ids+ * with no provider account code, and lines with no account at all. Both+ * block a push (UNMAPPED_ACCOUNTS).+ */+export function collectUnmappedJournalAccounts(+ lines: Accounting.JournalEntryLine[],+ accountCodesById: ReadonlyMap<string, string>+): { unmappedAccountIds: string[]; lineIdsWithoutAccount: string[] } {+ const unmapped = new Set<string>();+ const lineIdsWithoutAccount: string[] = [];++ for (const line of lines) {+ if (!line.accountId) {+ lineIdsWithoutAccount.push(line.id);+ continue;+ }+ if (!accountCodesById.get(line.accountId)) {+ unmapped.add(line.accountId);+ }+ }++ return { unmappedAccountIds: [...unmapped], lineIdsWithoutAccount };+}++/**+ * Composite key for a dimension value: `<dimensionId>:<valueId>` — the+ * SAME key the dimension value mappings use as entityId (valueId is+ * polymorphic across entity-typed dimensions, so the composite is+ * required). Kept in sync with buildDimensionValueMappingEntityId+ * (core/dimension-mapping.ts) — duplicated here so this import-light+ * module stays free of DB-facing imports.+ */+function dimensionValueKey(value: JournalLineDimensionRef): string {+ return `${value.dimensionId}:${value.valueId}`;+}++/**+ * Distinct slotted dimension values on the journal's lines that have no+ * provider option mapping. Only SLOT-CONFIGURED dimensions participate —+ * unslotted dimensions don't sync and are untouched by pre-flight.+ * `mappings` is the dimension-value lookup keyed `<dimensionId>:<valueId>`+ * → provider option id.+ */+export function collectUnmappedDimensionValues(+ lines: ReadonlyArray<Pick<Accounting.JournalEntryLine, "dimensions">>,+ slots: ReadonlyArray<{ dimensionId: string }>,+ mappings: ReadonlyMap<string, string>+): JournalLineDimensionRef[] {+ if (slots.length === 0) return [];++ const slottedDimensionIds = new Set(slots.map((slot) => slot.dimensionId));+ const unmapped = new Map<string, JournalLineDimensionRef>();++ for (const line of lines) {+ for (const dimension of line.dimensions ?? []) {+ if (!slottedDimensionIds.has(dimension.dimensionId)) continue;+ const key = dimensionValueKey(dimension);+ if (mappings.get(key)) continue;+ if (!unmapped.has(key)) {+ unmapped.set(key, {+ dimensionId: dimension.dimensionId,+ valueId: dimension.valueId+ });+ }+ }+ }++ return [...unmapped.values()];+}++/**+ * Line ids whose account is an AR/AP control account+ * (accountDefault.receivablesAccount / payablesAccount). Control-account+ * lines never push: the AR/AP balance in the provider is owned by the+ * synced documents, and pushing them would double-post (it also keeps+ * QBD's one-AR/AP-line-per-JE constraint unreachable).+ */+export function findControlAccountLineIds(+ lines: Accounting.JournalEntryLine[],+ controlAccountIds: ReadonlySet<string>+): string[] {+ if (controlAccountIds.size === 0) return [];+ return lines+ .filter((line) => line.accountId && controlAccountIds.has(line.accountId))+ .map((line) => line.id);+}++/** Add days to a YYYY-MM-DD date string (UTC), returning YYYY-MM-DD. */+export function addDaysToIsoDate(isoDate: string, days: number): string {+ const date = new Date(`${isoDate.slice(0, 10)}T00:00:00Z`);+ date.setUTCDate(date.getUTCDate() + days);+ return date.toISOString().slice(0, 10);+}++export type PeriodLockEvaluation =+ | { locked: false }+ | { locked: true; policy: "park"; lockDate: string }+ | { locked: true; policy: "redate"; lockDate: string; pushDate: string };++/**+ * Evaluate the period-lock rule: a journal dated on or before the provider+ * lock date is locked. Under `park` (default) the push is blocked+ * (PERIOD_LOCKED Warning); under `redate` it pushes at lock date + 1 with+ * the original date preserved in the narration. Dates are YYYY-MM-DD+ * strings (lexicographic comparison is date order).+ */+export function evaluatePeriodLock(args: {+ postingDate: string;+ lockDate: string | null;+ policy: PostingSyncSettings["periodLockPolicy"];+}): PeriodLockEvaluation {+ if (!args.lockDate) return { locked: false };++ const postingDay = args.postingDate.slice(0, 10);+ const lockDay = args.lockDate.slice(0, 10);+ if (postingDay > lockDay) return { locked: false };++ if (args.policy === "redate") {+ return {+ locked: true,+ policy: "redate",+ lockDate: lockDay,+ pushDate: addDaysToIsoDate(lockDay, 1)+ };+ }++ return { locked: true, policy: "park", lockDate: lockDay };+}++// /********************************************************\+// * Daily consolidation aggregation (Task 12) *+// \********************************************************/++/**+ * Net signed line amounts per account id (cents-accurate, -0 normalized to+ * 0). Lines without an account net into the `null` bucket so the unmapped+ * pre-flight still sees them. Used by the daily-consolidation aggregate and+ * by reconciliation when re-deriving what a consolidated batch booked.+ */+export function netJournalLinesPerAccount(+ lines: ReadonlyArray<+ Pick<Accounting.JournalEntryLine, "accountId" | "amount">+ >+): Map<string | null, number> {+ const centsByAccount = new Map<string | null, number>();+ for (const line of lines) {+ const key = line.accountId ?? null;+ centsByAccount.set(+ key,+ (centsByAccount.get(key) ?? 0) + Math.round(line.amount * 100)+ );+ }++ const netted = new Map<string | null, number>();+ for (const [accountId, cents] of centsByAccount) {+ netted.set(accountId, cents === 0 ? 0 : cents / 100);+ }+ return netted;+}++/** Narration for one daily-consolidation batch (sourceType since v3 partitions). */+export function getDailyConsolidationNarration(+ postingDate: string,+ journalCount: number,+ sourceType?: string | null+): string {+ const sourceTypeLabel = sourceType ? ` — ${sourceType}` : "";+ return `Carbon daily summary ${postingDate}${sourceTypeLabel} — ${journalCount} journals`;+}++export type DailyJournalEntryAggregate = {+ /**+ * Synthetic journal covering every member journal of the posting date:+ * one line per account with the summed signed amount, zero-net lines+ * dropped. Feed it through the SAME pre-flight + mapping helpers as an+ * individual push (runJournalEntryPreflight + the provider mapper).+ */+ journal: Accounting.JournalEntry;+ /** "Carbon daily summary <date> — <n> journals" */+ narration: string;+ journalIds: string[];+};++/**+ * Canonical grouping key for a line's dimension tuple: slotted dimensions+ * only (when `slottedDimensionIds` is provided), sorted by dimensionId.+ * Empty tuple → "" (the legacy per-account bucket).+ */+export function getDimensionTupleKey(+ dimensions: ReadonlyArray<JournalLineDimensionRef> | null | undefined,+ slottedDimensionIds?: ReadonlySet<string>+): string {+ if (!dimensions || dimensions.length === 0) return "";+ return dimensions+ .filter(+ (dimension) =>+ !slottedDimensionIds || slottedDimensionIds.has(dimension.dimensionId)+ )+ .map((dimension) => `${dimension.dimensionId}=${dimension.valueId}`)+ .sort()+ .join("|");+}++/**+ * Build ONE aggregated journal for a posting date from its member journals+ * (daily-consolidation cron). Pure:+ *+ * - sums signed line amounts per (account, dimension tuple) across every+ * member (cents math) — summaries preserve exactly the analytical+ * granularity the provider will see (spec §4). The tuple covers the+ * dimensions in `slottedDimensionIds` when provided, else every+ * dimension present on the lines; lines without dimensions keep the+ * legacy per-account bucket;+ * - drops groups that net to zero;+ * - books post-2dp rounding residue (per-line cents rounding of sub-cent+ * amounts) to `roundingAccountId` when provided — capped at half a cent+ * per input line, beyond which the input is corrupt, not rounding;+ * - throws JournalEntrySyncError UNBALANCED_JOURNAL (Failed, not Warning)+ * when the combined lines do not sum to zero and no rounding account+ * can absorb the residue;+ * - throws a plain Error on misuse (no members, or a member dated off the+ * batch date) — programmer error, not a sync failure.+ *+ * A date whose members fully cancel produces an aggregate with NO lines —+ * the caller skips the provider push and just closes the members (nothing+ * to book).+ */+export function aggregateJournalEntriesForDate(args: {+ /** Batch key, e.g. "daily:xero:production-event:2026-07-08" — becomes the synthetic journal id. */+ batchId: string;+ companyId: string;+ /** YYYY-MM-DD posting date shared by every member journal. */+ postingDate: string;+ /** Source type shared by the batch's members (v3 per-source-type partitions); null for legacy mixed batches. */+ sourceType?: string | null;+ journals: Accounting.JournalEntry[];+ /**+ * Slot-configured dimension ids: the tuple is restricted to these so+ * summaries group only by dimensions that actually cross the wire.+ * Absent = group by every dimension present on the lines (a superset of+ * the mapped tuple — never coarser than what the provider will see).+ */+ slottedDimensionIds?: Iterable<string>;+ /**+ * accountDefault.roundingAccount — when provided, post-2dp rounding+ * residue books here (mapped like any account) instead of failing the+ * batch. Absent = residue throws UNBALANCED_JOURNAL (legacy behavior).+ */+ roundingAccountId?: string | null;+}): DailyJournalEntryAggregate {+ const postingDay = args.postingDate.slice(0, 10);+ const journalIds = args.journals.map((journal) => journal.id);++ if (args.journals.length === 0) {+ throw new Error(+ `Cannot aggregate zero journals for posting date ${postingDay}`+ );+ }++ for (const journal of args.journals) {+ if (journal.postingDate.slice(0, 10) !== postingDay) {+ throw new Error(+ `Journal ${journal.id} is dated ${journal.postingDate}, not ${postingDay}; daily consolidation groups strictly by posting date`+ );+ }+ }++ const slottedDimensionIds = args.slottedDimensionIds+ ? new Set(args.slottedDimensionIds)+ : undefined;++ const allLines = args.journals.flatMap((journal) => journal.lines);+ const totalCents = allLines.reduce(+ (sum, line) => sum + Math.round(line.amount * 100),+ 0+ );++ // Post-2dp residue: per-line cents rounding of sub-cent amounts can+ // shift the total by at most half a cent per line. Anything larger is+ // corrupt input, not rounding — refuse to bury it in roundingAccount.+ const residueCapCents = Math.ceil(allLines.length / 2);+ const bookableResidue =+ totalCents !== 0 &&+ Boolean(args.roundingAccountId) &&+ Math.abs(totalCents) <= residueCapCents;++ if (totalCents !== 0 && !bookableResidue) {+ throw new JournalEntrySyncError({+ errorCode: "UNBALANCED_JOURNAL",+ message: `Daily summary for ${postingDay} does not balance across its ${args.journals.length} member journal(s) (signed line amounts must sum to zero); refusing to push.`,+ warning: false,+ metadata: { postingDate: postingDay, journalIds }+ });+ }++ // Net cents per (account, dimension tuple)+ type Group = {+ accountId: string | null;+ tupleKey: string;+ dimensions: JournalLineDimensionRef[];+ cents: number;+ };+ const groups = new Map<string, Group>();+ for (const line of allLines) {+ const accountId = line.accountId ?? null;+ const tupleKey = getDimensionTupleKey(line.dimensions, slottedDimensionIds);+ const key = `${accountId ?? ""}\u0000${tupleKey}`;+ const existing = groups.get(key);+ const cents = Math.round(line.amount * 100);+ if (existing) {+ existing.cents += cents;+ } else {+ const dimensions = (line.dimensions ?? [])+ .filter(+ (dimension) =>+ !slottedDimensionIds ||+ slottedDimensionIds.has(dimension.dimensionId)+ )+ .sort((a, b) => a.dimensionId.localeCompare(b.dimensionId));+ groups.set(key, { accountId, tupleKey, dimensions, cents });+ }+ }++ const lines: Accounting.JournalEntryLine[] = [...groups.values()]+ .filter((group) => group.cents !== 0)+ .sort(+ (a, b) =>+ String(a.accountId ?? "").localeCompare(String(b.accountId ?? "")) ||+ a.tupleKey.localeCompare(b.tupleKey)+ )+ .map((group) => ({+ id: `${args.batchId}:${group.accountId ?? "no-account"}${+ group.tupleKey ? `:${group.tupleKey}` : ""+ }`,+ accountId: group.accountId,+ amount: group.cents / 100,+ description: null,+ ...(group.dimensions.length > 0 ? { dimensions: group.dimensions } : {})+ }));++ if (bookableResidue) {+ lines.push({+ id: `${args.batchId}:rounding`,+ accountId: args.roundingAccountId ?? null,+ amount: -totalCents / 100,+ description: "Rounding residue"+ });+ }++ const narration = getDailyConsolidationNarration(+ postingDay,+ args.journals.length,+ args.sourceType+ );++ return {+ journal: {+ id: args.batchId,+ companyId: args.companyId,+ journalEntryId: `Daily summary ${postingDay}`,+ description: narration,+ postingDate: postingDay,+ status: "Posted",+ sourceType: args.sourceType ?? null,+ reversalOfId: null,+ reversedById: null,+ reversal: false,+ lines,+ updatedAt: new Date().toISOString()+ },+ narration,+ journalIds+ };+}++export type JournalEntryPreflightResult =+ | { failure: JournalEntrySyncFailure }+ | {+ failure: null;+ pushDate: string;+ redatedFromDate?: string;+ /**+ * Slotted dimension values the push proceeds WITHOUT+ * (onUnmappedDimensionValue "drop"): unmapped values whose+ * dimensions the mapper will omit. Recorded by the caller — I3:+ * degradation is recorded, never silent.+ */+ droppedDimensionValues?: JournalLineDimensionRef[];+ };++/**+ * Run every pre-flight rule for one journal push. Returns either the+ * structured failure to record (no provider call happens) or the push date+ * to use — `redatedFromDate` is set when the redate policy moved the date,+ * so the mapper can append the original date to the narration.+ *+ * Dimension rule (opt-in): when `dimensionValueMappings` is provided and+ * the settings carry dimension slots, every slotted dimension value on the+ * lines must resolve through the mapping lookup. Unmapped values follow+ * `settings.onUnmappedDimensionValue`: "warn" → UNMAPPED_DIMENSION_VALUES+ * Warning (park); "drop" → pass, with the dropped values reported on the+ * success branch. Callers that don't load dimension mappings (legacy+ * paths) omit the arg and skip the rule entirely.+ */+export function runJournalEntryPreflight(args: {+ journal: Accounting.JournalEntry;+ accountCodesById: ReadonlyMap<string, string>;+ controlAccountIds: ReadonlySet<string>;+ lockDate: string | null;+ settings: PostingSyncSettings;+ dimensionValueMappings?: ReadonlyMap<string, string>;+}): JournalEntryPreflightResult {+ const { journal } = args;++ const { unmappedAccountIds, lineIdsWithoutAccount } =+ collectUnmappedJournalAccounts(journal.lines, args.accountCodesById);+ if (unmappedAccountIds.length > 0 || lineIdsWithoutAccount.length > 0) {+ const parts: string[] = [];+ if (unmappedAccountIds.length > 0) {+ parts.push(+ `${unmappedAccountIds.length} account(s) on journal ${journal.journalEntryId} have no provider account mapping`+ );+ }+ if (lineIdsWithoutAccount.length > 0) {+ parts.push(`${lineIdsWithoutAccount.length} line(s) have no account`);+ }+ return {+ failure: {+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `${parts.join("; ")}. Map the account(s) on the integration settings page, then retry.`,+ warning: true,+ metadata: {+ unmappedAccountIds,+ ...(lineIdsWithoutAccount.length > 0 ? { lineIdsWithoutAccount } : {})+ }+ }+ };+ }++ const controlAccountLineIds = findControlAccountLineIds(+ journal.lines,+ args.controlAccountIds+ );+ if (controlAccountLineIds.length > 0) {+ return {+ failure: {+ errorCode: "CONTROL_ACCOUNT_LINE",+ message: `Journal ${journal.journalEntryId} has ${controlAccountLineIds.length} line(s) on an AR/AP control account; control-account postings are owned by the synced documents and are never pushed as journals.`,+ warning: true,+ metadata: {+ lineIds: controlAccountLineIds,+ controlAccountIds: [...args.controlAccountIds]+ }+ }+ };+ }++ let droppedDimensionValues: JournalLineDimensionRef[] | undefined;+ if (+ args.dimensionValueMappings !== undefined &&+ args.settings.dimensionSlots.length > 0+ ) {+ const unmappedDimensionValues = collectUnmappedDimensionValues(+ journal.lines,+ args.settings.dimensionSlots,+ args.dimensionValueMappings+ );++ if (unmappedDimensionValues.length > 0) {+ if (args.settings.onUnmappedDimensionValue === "warn") {+ return {+ failure: {+ errorCode: "UNMAPPED_DIMENSION_VALUES",+ message: `Journal ${journal.journalEntryId} carries ${unmappedDimensionValues.length} slotted dimension value(s) with no provider option mapping. Map the value(s) on the integration settings page (or enable auto-create on the slot), then retry.`,+ warning: true,+ metadata: { unmappedDimensionValues }+ }+ };+ }+ // "drop": push without those dimensions, recorded — never silent+ droppedDimensionValues = unmappedDimensionValues;+ }+ }++ if (!isBalancedJournal(journal.lines)) {+ return {+ failure: {+ errorCode: "UNBALANCED_JOURNAL",+ message: `Journal ${journal.journalEntryId} does not balance (signed line amounts must sum to zero); refusing to push.`,+ warning: false,+ metadata: { journalId: journal.id }+ }+ };+ }++ const lock = evaluatePeriodLock({+ postingDate: journal.postingDate,+ lockDate: args.lockDate,+ policy: args.settings.periodLockPolicy+ });++ if (lock.locked && lock.policy === "park") {+ return {+ failure: {+ errorCode: "PERIOD_LOCKED",+ message: `Journal ${journal.journalEntryId} is dated ${journal.postingDate}, on or before the provider lock date ${lock.lockDate}. Unlock the period in the provider (or switch the period-lock policy to re-date), then retry.`,+ warning: true,+ metadata: {+ postingDate: journal.postingDate,+ lockDate: lock.lockDate+ }+ }+ };+ }++ if (lock.locked) {+ return {+ failure: null,+ pushDate: lock.pushDate,+ redatedFromDate: journal.postingDate,+ ...(droppedDimensionValues ? { droppedDimensionValues } : {})+ };+ }++ return {+ failure: null,+ pushDate: journal.postingDate.slice(0, 10),+ ...(droppedDimensionValues ? { droppedDimensionValues } : {})+ };+}diff --git a/packages/ee/src/accounting/core/remote-journal.test.ts b/packages/ee/src/accounting/core/remote-journal.test.tsnew file mode 100644index 0000000000..9170a56539--- /dev/null+++ b/packages/ee/src/accounting/core/remote-journal.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";+import {+ sumQboJournalEntryDebitTotals,+ sumRilletJournalEntryDebitTotals,+ sumXeroManualJournalDebitTotals+} from "./remote-journal";++// The tie-out compares Carbon's debit-signed per-account sums against what+// the provider actually stored, so each reducer must return NET debit-signed+// totals per remote account ref: debits positive, credits negative, refs+// with equal debits and credits netting to zero (not dropped — a zero net is+// still information).++describe("sumXeroManualJournalDebitTotals", () => {+ it("nets debit-signed LineAmounts per AccountCode", () => {+ const totals = sumXeroManualJournalDebitTotals({+ JournalLines: [+ { AccountCode: "1200", LineAmount: 150.25 },+ { AccountCode: "1200", LineAmount: 49.75 },+ { AccountCode: "4000", LineAmount: -200 }+ ]+ });++ expect(totals.get("1200")).toBe(200);+ expect(totals.get("4000")).toBe(-200);+ expect(totals.size).toBe(2);+ });++ it("handles a journal with no lines", () => {+ expect(sumXeroManualJournalDebitTotals({}).size).toBe(0);+ expect(sumXeroManualJournalDebitTotals({ JournalLines: [] }).size).toBe(0);+ });++ it("sums in cents so 2-dp amounts carry no float residue", () => {+ const totals = sumXeroManualJournalDebitTotals({+ JournalLines: [+ { AccountCode: "1200", LineAmount: 0.1 },+ { AccountCode: "1200", LineAmount: 0.2 }+ ]+ });++ expect(totals.get("1200")).toBe(0.3);+ });+});++describe("sumRilletJournalEntryDebitTotals", () => {+ it("parses 2-dp string amounts, DEBIT adds and CREDIT subtracts, keyed by account_code", () => {+ const totals = sumRilletJournalEntryDebitTotals({+ items: [+ {+ account_code: "1200",+ amount: { amount: "150.25", currency: "USD" },+ side: "DEBIT"+ },+ {+ account_code: "1200",+ amount: { amount: "50.25", currency: "USD" },+ side: "CREDIT"+ },+ {+ account_code: "4000",+ amount: { amount: "100.00", currency: "USD" },+ side: "CREDIT"+ }+ ]+ });++ expect(totals.get("1200")).toBe(100);+ expect(totals.get("4000")).toBe(-100);+ expect(totals.size).toBe(2);+ });++ it("nets a balanced ref to zero instead of dropping it", () => {+ const totals = sumRilletJournalEntryDebitTotals({+ items: [+ {+ account_code: "1200",+ amount: { amount: "75.00", currency: "USD" },+ side: "DEBIT"+ },+ {+ account_code: "1200",+ amount: { amount: "75.00", currency: "USD" },+ side: "CREDIT"+ }+ ]+ });++ expect(totals.get("1200")).toBe(0);+ });+});++describe("sumQboJournalEntryDebitTotals", () => {+ it("applies PostingType to always-positive Amounts, keyed by AccountRef.value", () => {+ const totals = sumQboJournalEntryDebitTotals({+ Line: [+ {+ Amount: 150.25,+ DetailType: "JournalEntryLineDetail",+ JournalEntryLineDetail: {+ PostingType: "Debit",+ AccountRef: { value: "72" }+ }+ },+ {+ Amount: 50.25,+ DetailType: "JournalEntryLineDetail",+ JournalEntryLineDetail: {+ PostingType: "Credit",+ AccountRef: { value: "72" }+ }+ },+ {+ Amount: 100,+ DetailType: "JournalEntryLineDetail",+ JournalEntryLineDetail: {+ PostingType: "Credit",+ AccountRef: { value: "81" }+ }+ }+ ]+ });++ expect(totals.get("72")).toBe(100);+ expect(totals.get("81")).toBe(-100);+ expect(totals.size).toBe(2);+ });++ it("handles an entry with no lines", () => {+ expect(sumQboJournalEntryDebitTotals({ Line: [] }).size).toBe(0);+ });+});diff --git a/packages/ee/src/accounting/core/remote-journal.ts b/packages/ee/src/accounting/core/remote-journal.tsnew file mode 100644index 0000000000..86f2afe12f--- /dev/null+++ b/packages/ee/src/accounting/core/remote-journal.ts@@ -0,0 +1,158 @@+import type { AccountingProvider } from "../providers";+import type { Qbo } from "../providers/quickbooks-online";+import { QboProvider } from "../providers/quickbooks-online";+import type { Rillet } from "../providers/rillet";+import { RilletProvider } from "../providers/rillet";+import type { Xero } from "../providers/xero";+import { XeroProvider } from "../providers/xero";++/**+ * Provider-agnostic read of one Carbon-pushed provider journal, for the+ * tie-out's external-fidelity check (v3 spec §5): net DEBIT-SIGNED totals+ * per remote account ref (debits positive, credits negative).+ *+ * `found: false` means the entry is missing, voided, or deleted remotely —+ * the same drift semantics as the weekly presence check. A missing entity+ * NEVER throws (each provider's read returns null on failure); a+ * RatelimitError raised by the provider client propagates untouched so+ * callers can pace themselves.+ *+ * The account ref is whatever the provider's journal payload exposes:+ * Xero `AccountCode`, Rillet `account_code`, QBO `AccountRef.value` (the+ * provider account id). Callers map refs back to Carbon accounts via the+ * account-mapping rows, which carry both the external id and the external+ * code.+ */+export type RemoteJournalTotals = {+ found: boolean;+ /** Net debit-signed total per remote account ref. Empty when not found. */+ debitTotalsByAccountRef: Map<string, number>;+};++function notFound(): RemoteJournalTotals {+ return { found: false, debitTotalsByAccountRef: new Map() };+}++/** Accumulate in integer cents so per-ref nets carry no float residue. */+function addCents(+ centsByRef: Map<string, number>,+ ref: string | null | undefined,+ cents: number+): void {+ if (!ref) return;+ centsByRef.set(ref, (centsByRef.get(ref) ?? 0) + cents);+}++function toAmounts(centsByRef: Map<string, number>): Map<string, number> {+ const totals = new Map<string, number>();+ for (const [ref, cents] of centsByRef) {+ totals.set(ref, cents / 100);+ }+ return totals;+}++/** Xero manual-journal LineAmounts are debit-signed already; ref = AccountCode. */+export function sumXeroManualJournalDebitTotals(+ journal: Pick<Xero.ManualJournal, "JournalLines">+): Map<string, number> {+ const cents = new Map<string, number>();+ for (const line of journal.JournalLines ?? []) {+ addCents(+ cents,+ line.AccountCode,+ Math.round((Number(line.LineAmount) || 0) * 100)+ );+ }+ return toAmounts(cents);+}++/**+ * Rillet items carry an unsigned 2-dp string amount plus an explicit side:+ * DEBIT adds, CREDIT subtracts; ref = account_code (always present on the+ * payload, unlike the server-resolved optional account_id).+ */+export function sumRilletJournalEntryDebitTotals(+ entry: Pick<Rillet.JournalEntry, "items">+): Map<string, number> {+ const cents = new Map<string, number>();+ for (const item of entry.items ?? []) {+ const magnitude = Math.round((Number(item.amount?.amount) || 0) * 100);+ addCents(+ cents,+ item.account_code,+ item.side === "CREDIT" ? -magnitude : magnitude+ );+ }+ return toAmounts(cents);+}++/**+ * QBO line Amounts are always positive; PostingType "Debit" adds, "Credit"+ * subtracts; ref = JournalEntryLineDetail.AccountRef.value.+ */+export function sumQboJournalEntryDebitTotals(+ entry: Pick<Qbo.JournalEntry, "Line">+): Map<string, number> {+ const cents = new Map<string, number>();+ for (const line of entry.Line ?? []) {+ const detail = line.JournalEntryLineDetail;+ if (!detail) continue;+ const magnitude = Math.round((Number(line.Amount) || 0) * 100);+ addCents(+ cents,+ detail.AccountRef.value,+ detail.PostingType === "Credit" ? -magnitude : magnitude+ );+ }+ return toAmounts(cents);+}++/**+ * Fetch one pushed provider journal by external id and reduce it to net+ * debit-signed totals per remote account ref. Dispatches on the concrete+ * provider class (the same discrimination core/service.ts uses to build+ * providers). A provider without a journal reader — or an unknown provider+ * — resolves found:false rather than throwing.+ */+export async function fetchRemoteJournalTotals(+ provider: AccountingProvider,+ externalId: string+): Promise<RemoteJournalTotals> {+ if (provider instanceof XeroProvider) {+ if (typeof provider.getManualJournal !== "function") return notFound();+ const journal = await provider.getManualJournal(externalId);+ if (+ !journal ||+ journal.Status === "VOIDED" ||+ journal.Status === "DELETED"+ ) {+ return notFound();+ }+ return {+ found: true,+ debitTotalsByAccountRef: sumXeroManualJournalDebitTotals(journal)+ };+ }++ if (provider instanceof RilletProvider) {+ if (typeof provider.getJournalEntry !== "function") return notFound();+ const entry = await provider.getJournalEntry(externalId);+ if (!entry) return notFound();+ return {+ found: true,+ debitTotalsByAccountRef: sumRilletJournalEntryDebitTotals(entry)+ };+ }++ if (provider instanceof QboProvider) {+ if (typeof provider.getJournalEntry !== "function") return notFound();+ const entry = await provider.getJournalEntry(externalId);+ if (!entry) return notFound();+ return {+ found: true,+ debitTotalsByAccountRef: sumQboJournalEntryDebitTotals(entry)+ };+ }++ return notFound();+}diff --git a/packages/ee/src/accounting/core/service.ts b/packages/ee/src/accounting/core/service.tsindex 3106251340..64ff8e9ab0 100644--- a/packages/ee/src/accounting/core/service.ts+++ b/packages/ee/src/accounting/core/service.ts@@ -1,13 +1,85 @@import type { Database } from "@carbon/database";import { getLogger } from "@carbon/logger";import type { SupabaseClient } from "@supabase/supabase-js";+import z from "zod";+import type { AccountingProvider } from "../providers";+import { QboProvider } from "../providers/quickbooks-online";+import { RilletProvider } from "../providers/rillet";import { XeroProvider } from "../providers/xero";import type { ProviderID } from "./models";import {DEFAULT_SYNC_CONFIG,- ProviderIntegrationMetadataSchema+ ProviderIntegrationMetadataSchema,+ parseStoredCredentials,+ SyncDirectionSchema} from "./models";-import type { ProviderCredentials, ProviderIntegrationMetadata } from "./types";+import type {+ AccountingEntityType,+ GlobalSyncConfig,+ ProviderCredentials,+ ProviderIntegrationMetadata+} from "./types";++/**+ * Stored per-entity sync-config fragment. Deliberately has no defaults —+ * only the keys a company actually stored may override the defaults.+ */+const storedEntityConfigSchema = z.object({+ enabled: z.boolean().optional(),+ direction: SyncDirectionSchema.optional(),+ owner: z.enum(["carbon", "accounting"]).optional(),+ syncFromDate: z.string().datetime().optional()+});++/**+ * Resolve the effective sync config for a company by deep-merging the+ * per-entity fragments stored on `companyIntegration.metadata.syncConfig`+ * over `DEFAULT_SYNC_CONFIG`. Only `enabled`, `direction`, `owner` and+ * `syncFromDate` can be overridden; invalid fragments are ignored with a+ * warning — a bad stored config must never break sync.+ */+export function resolveSyncConfig(metadata: unknown): GlobalSyncConfig {+ const resolved: GlobalSyncConfig = {+ entities: Object.fromEntries(+ Object.entries(DEFAULT_SYNC_CONFIG.entities).map(+ ([entityType, entityConfig]) => [entityType, { ...entityConfig }]+ )+ ) as GlobalSyncConfig["entities"]+ };++ const storedEntities =+ metadata && typeof metadata === "object"+ ? (metadata as { syncConfig?: { entities?: unknown } }).syncConfig+ ?.entities+ : undefined;++ if (!storedEntities || typeof storedEntities !== "object") {+ return resolved;+ }++ for (const entityType of Object.keys(+ resolved.entities+ ) as AccountingEntityType[]) {+ const fragment = (storedEntities as Record<string, unknown>)[entityType];+ if (fragment === undefined) continue;++ const parsed = storedEntityConfigSchema.safeParse(fragment);+ if (!parsed.success) {+ logger.warning("Ignoring invalid stored sync config for entity", {+ entityType,+ issues: parsed.error.issues+ });+ continue;+ }++ resolved.entities[entityType] = {+ ...resolved.entities[entityType],+ ...parsed.data+ };+ }++ return resolved;+}const logger = getLogger("ee", "accounting");@@ -21,7 +93,9 @@ export const getAccountingIntegration = async <T extends ProviderID>(.select("*").eq("id", provider).or(- `companyId.eq.${companyOrTenantId},metadata->credentials->>tenantId.eq.${companyOrTenantId}`+ // Credentials written before the providerMetadata shape kept tenantId+ // at the top level — match both paths so legacy rows stay resolvable+ `companyId.eq.${companyOrTenantId},metadata->credentials->>tenantId.eq.${companyOrTenantId},metadata->credentials->providerMetadata->>tenantId.eq.${companyOrTenantId}`).single();@@ -53,31 +127,88 @@ export const getAccountingIntegration = async <T extends ProviderID>(} as const;};-export const getProviderIntegration = (+export function getProviderIntegration(+ client: SupabaseClient<Database>,+ companyId: string,+ provider: ProviderID.XERO,+ config?: ProviderIntegrationMetadata+): XeroProvider;+export function getProviderIntegration(+ client: SupabaseClient<Database>,+ companyId: string,+ provider: ProviderID.QUICKBOOKS,+ config?: ProviderIntegrationMetadata+): QboProvider;+export function getProviderIntegration(+ client: SupabaseClient<Database>,+ companyId: string,+ provider: ProviderID.RILLET,+ config?: ProviderIntegrationMetadata+): RilletProvider;+export function getProviderIntegration(client: SupabaseClient<Database>,companyId: string,provider: ProviderID,config?: ProviderIntegrationMetadata-) => {- const { accessToken, refreshToken, tenantId } = config?.credentials || {};+): AccountingProvider;+export function getProviderIntegration(+ client: SupabaseClient<Database>,+ companyId: string,+ provider: ProviderID,+ config?: ProviderIntegrationMetadata+): AccountingProvider {+ // Reads go through the stored-credentials shim so legacy flat oauth2 rows+ // (top-level tenantId/tenantName) resolve the same as the new shape+ let credentials: ProviderCredentials | undefined;+ if (config?.credentials) {+ try {+ credentials = parseStoredCredentials(config.credentials);+ } catch (error) {+ logger.error("Invalid stored provider credentials", { provider, error });+ }+ }- // For now don't use the company level sync config- const syncConfig = DEFAULT_SYNC_CONFIG;+ const oauthCredentials =+ credentials?.type === "oauth2" ? credentials : undefined;+ const { accessToken, refreshToken } = oauthCredentials ?? {};+ const tenantId =+ typeof oauthCredentials?.providerMetadata?.tenantId === "string"+ ? oauthCredentials.providerMetadata.tenantId+ : undefined;+ const realmId =+ typeof oauthCredentials?.providerMetadata?.realmId === "string"+ ? oauthCredentials.providerMetadata.realmId+ : undefined;++ const syncConfig = resolveSyncConfig(config);// Create a callback function to update the integration metadata when tokens are refreshedconst onTokenRefresh = async (auth: ProviderCredentials) => {try {+ if (auth.type !== "oauth2") {+ logger.error("Unexpected credentials in provider token refresh", {+ provider,+ type: auth.type+ });+ return;+ }+logger.info("Refreshing tokens for integration", { provider });+ // Writes always use the new shape: provider-specific fields live under+ // providerMetadata (carried over from the stored credentials)const update: ProviderCredentials = {...auth,expiresAt:auth.expiresAt || new Date(Date.now() + 3600000).toISOString(), // Default to 1 hour if not provided- tenantId: auth.tenantId || tenantId+ providerMetadata: {+ ...oauthCredentials?.providerMetadata,+ ...auth.providerMetadata+ }};await client.from("companyIntegration")- .update({ metadata: { ...config, credentials: update } })+ .update({ metadata: { ...config, credentials: update } as any }).eq("companyId", companyId).eq("id", provider);} catch (error) {@@ -89,26 +220,36 @@ export const getProviderIntegration = (};switch (provider) {- // case "quickbooks": {- // const environment = process.env.QUICKBOOKS_ENVIRONMENT as- // | "production"- // | "sandbox";- // return new QuickBooksProvider({- // companyId,- // tenantId,- // environment: environment || "sandbox",- // clientId: process.env.QUICKBOOKS_CLIENT_ID!,- // clientSecret: process.env.QUICKBOOKS_CLIENT_SECRET!,- // redirectUri: process.env.QUICKBOOKS_REDIRECT_URI,- // onTokenRefresh- // });- // }+ case "rillet": {+ // API-key provider: no OAuth client and no token refresh — the apiKey+ // credentials variant is the whole connection+ return new RilletProvider({+ companyId,+ credentials,+ syncConfig+ });+ }+ case "quickbooks": {+ // Hosts default to production; sandbox is an explicit opt-in+ const environment =+ process.env.QUICKBOOKS_ENVIRONMENT === "sandbox"+ ? "sandbox"+ : "production";+ return new QboProvider({+ companyId,+ realmId,+ environment,+ accessToken,+ refreshToken,+ clientId: process.env.QUICKBOOKS_CLIENT_ID!,+ clientSecret: process.env.QUICKBOOKS_CLIENT_SECRET!,+ redirectUri: process.env.QUICKBOOKS_REDIRECT_URI,+ syncConfig,+ onTokenRefresh+ });+ }case "xero": {- const settings = {- defaultSalesAccountCode: config?.defaultSalesAccountCode,- defaultPurchaseAccountCode: config?.defaultPurchaseAccountCode- };- logger.info("Creating XeroProvider", { settings, config });+ logger.info("Creating XeroProvider", { config });return new XeroProvider({companyId,tenantId,@@ -118,8 +259,7 @@ export const getProviderIntegration = (clientSecret: process.env.XERO_CLIENT_SECRET!,redirectUri: process.env.XERO_REDIRECT_URI,syncConfig,- onTokenRefresh,- settings+ onTokenRefresh});}// Add other providers as needed@@ -128,4 +268,4 @@ export const getProviderIntegration = (default:throw new Error(`Unsupported provider: ${provider}`);}-};+}diff --git a/packages/ee/src/accounting/core/subscriptions.test.ts b/packages/ee/src/accounting/core/subscriptions.test.tsnew file mode 100644index 0000000000..7f2dafe306--- /dev/null+++ b/packages/ee/src/accounting/core/subscriptions.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it, vi } from "vitest";+import { ProviderID } from "./models";+import {+ ensureProviderSubscriptions,+ getSyncSubscriptionName,+ REQUIRED_SYNC_SUBSCRIPTIONS+} from "./subscriptions";++/**+ * Minimal mock of the two client surfaces convergence touches: the+ * create/delete subscription RPCs and the `eventSystemSubscription` list+ * read. `existingRows` simulates what is already in the table for the+ * provider's `${id}-sync` name.+ */+function makeClient(existingRows: Array<{ id: string; table: string }>) {+ const rpc = vi.fn(async (fn: string) => {+ if (fn === "create_event_system_subscription") {+ return { data: [{ id: "sub_new" }], error: null };+ }+ return { data: null, error: null };+ });++ const from = vi.fn(() => ({+ select: () => ({+ eq: () => ({+ eq: async () => ({ data: existingRows, error: null })+ })+ })+ }));++ return { rpc, from } as any;+}++describe("REQUIRED_SYNC_SUBSCRIPTIONS", () => {+ it("subscribes journal for every provider (posting sync's event source)", () => {+ for (const providerId of Object.values(ProviderID)) {+ const tables = REQUIRED_SYNC_SUBSCRIPTIONS[providerId].map(+ (subscription) => subscription.table+ );+ expect(tables, `${providerId} must subscribe journal`).toContain(+ "journal"+ );+ }+ });++ it("never subscribes address (dead letter — parent bump covers it)", () => {+ for (const providerId of Object.values(ProviderID)) {+ const tables = REQUIRED_SYNC_SUBSCRIPTIONS[providerId].map(+ (subscription) => subscription.table+ );+ expect(tables).not.toContain("address");+ }+ });++ it("subscribes payment for every push-capable provider (Xero, QBO, Rillet)", () => {+ const withPayment = Object.values(ProviderID).filter((providerId) =>+ REQUIRED_SYNC_SUBSCRIPTIONS[providerId].some(+ (subscription) => subscription.table === "payment"+ )+ );+ expect(withPayment).toEqual([+ ProviderID.XERO,+ ProviderID.QUICKBOOKS,+ ProviderID.RILLET+ ]);+ });+});++describe("ensureProviderSubscriptions", () => {+ it("upserts every required table under the provider's sync name", async () => {+ const client = makeClient([]);++ const result = await ensureProviderSubscriptions(+ client,+ "company-1",+ ProviderID.RILLET+ );++ const required = REQUIRED_SYNC_SUBSCRIPTIONS[ProviderID.RILLET];+ const createCalls = client.rpc.mock.calls.filter(+ ([fn]: [string]) => fn === "create_event_system_subscription"+ );++ expect(createCalls).toHaveLength(required.length);+ for (const [, params] of createCalls) {+ expect(params.p_name).toBe(getSyncSubscriptionName(ProviderID.RILLET));+ expect(params.p_company_id).toBe("company-1");+ expect(params.p_handler_type).toBe("SYNC");+ expect(params.p_config).toEqual({ provider: ProviderID.RILLET });+ expect(params.p_active).toBe(true);+ }++ expect(result.ensured.sort()).toEqual(+ required.map((subscription) => subscription.table).sort()+ );+ expect(result.removed).toEqual([]);+ });++ it("removes rows whose table is no longer required (e.g. legacy address)", async () => {+ const client = makeClient([+ { id: "sub_addr", table: "address" },+ { id: "sub_journal", table: "journal" }+ ]);++ const result = await ensureProviderSubscriptions(+ client,+ "company-1",+ ProviderID.RILLET+ );++ const deleteCalls = client.rpc.mock.calls.filter(+ ([fn]: [string]) => fn === "delete_event_system_subscription"+ );+ expect(deleteCalls).toHaveLength(1);+ expect(deleteCalls[0]?.[1]).toEqual({ p_subscription_id: "sub_addr" });+ expect(result.removed).toEqual(["address"]);+ });++ it("is idempotent — a fully-converged install deletes nothing", async () => {+ const required = REQUIRED_SYNC_SUBSCRIPTIONS[ProviderID.XERO];+ const client = makeClient(+ required.map((subscription, index) => ({+ id: `sub_${index}`,+ table: subscription.table+ }))+ );++ const result = await ensureProviderSubscriptions(+ client,+ "company-1",+ ProviderID.XERO+ );++ const deleteCalls = client.rpc.mock.calls.filter(+ ([fn]: [string]) => fn === "delete_event_system_subscription"+ );+ expect(deleteCalls).toHaveLength(0);+ expect(result.removed).toEqual([]);+ });+});diff --git a/packages/ee/src/accounting/core/subscriptions.ts b/packages/ee/src/accounting/core/subscriptions.tsnew file mode 100644index 0000000000..56f45ced40--- /dev/null+++ b/packages/ee/src/accounting/core/subscriptions.ts@@ -0,0 +1,151 @@+import type { Database } from "@carbon/database";+import type { CreateSubscriptionParams } from "@carbon/database/event";+import {+ createEventSystemSubscription,+ deleteEventSystemSubscription+} from "@carbon/database/event";+import type { SupabaseClient } from "@supabase/supabase-js";+import { ProviderID } from "./models";++/**+ * The event-system subscriptions each accounting provider's OUTBOUND sync+ * requires (subscription name `${providerId}-sync`, handlerType SYNC).+ *+ * Single source of truth (v4 spec, Pillar A): install hooks, integration+ * settings saves, and the outbound reconciliation sweep all converge a+ * company's subscription rows onto this list via+ * `ensureProviderSubscriptions` — the subscription set is never a+ * write-once install artifact. Existing installs converge at runtime; no+ * migration ever backfills subscription rows (migrations only attach table+ * triggers).+ *+ * A table belongs here only if the SYNC event handler's TABLE_TO_ENTITY_MAP+ * (packages/jobs/src/inngest/functions/events/sync.ts) routes it to an+ * entity type the provider registers a syncer for — that pairing is pinned+ * by a test in @carbon/jobs. `address` is deliberately absent everywhere:+ * address edits reach sync through the parent-row `updatedAt` bump+ * interceptor, and a direct address subscription is a dead letter.+ */++type RequiredSyncSubscription = {+ table: CreateSubscriptionParams["table"];+ operations: CreateSubscriptionParams["operations"];+};++/** Master + document tables every provider pushes. DELETE stays subscribed+ * for parity with historical rows (the handler logs-and-skips it). */+const COMMON_PUSH_TABLES: RequiredSyncSubscription[] = [+ { table: "customer", operations: ["INSERT", "UPDATE", "DELETE"] },+ { table: "supplier", operations: ["INSERT", "UPDATE", "DELETE"] },+ { table: "item", operations: ["INSERT", "UPDATE", "DELETE"] },+ { table: "salesInvoice", operations: ["INSERT", "UPDATE", "DELETE"] },+ { table: "purchaseInvoice", operations: ["INSERT", "UPDATE", "DELETE"] }+];++/** Posting sync: journals are INSERTed born Posted or UPDATEd to+ * Posted/Reversed; they are immutable once posted and DELETE sync does not+ * exist, so only INSERT/UPDATE are subscribed. */+const JOURNAL_SUBSCRIPTION: RequiredSyncSubscription = {+ table: "journal",+ operations: ["INSERT", "UPDATE"]+};++export const REQUIRED_SYNC_SUBSCRIPTIONS: Record<+ ProviderID,+ RequiredSyncSubscription[]+> = {+ [ProviderID.RILLET]: [+ ...COMMON_PUSH_TABLES,+ JOURNAL_SUBSCRIPTION,+ // Phase G outbound payment write-back (Rillet only): push on the+ // transition to Posted/Voided.+ { table: "payment", operations: ["INSERT", "UPDATE"] }+ ],+ [ProviderID.XERO]: [+ ...COMMON_PUSH_TABLES,+ JOURNAL_SUBSCRIPTION,+ { table: "purchaseOrder", operations: ["INSERT", "UPDATE", "DELETE"] },+ { table: "salesOrder", operations: ["INSERT", "UPDATE", "DELETE"] },+ // Phase G outbound payment write-back: push on the transition to+ // Posted/Voided. Inbound payments still ride the pull sweep.+ { table: "payment", operations: ["INSERT", "UPDATE"] }+ ],+ [ProviderID.QUICKBOOKS]: [+ ...COMMON_PUSH_TABLES,+ JOURNAL_SUBSCRIPTION,+ { table: "purchaseOrder", operations: ["INSERT", "UPDATE", "DELETE"] },+ // No `salesOrder` (no QBO salesOrder syncer registered). Phase G outbound+ // payment write-back: push on the transition to Posted/Voided. Inbound+ // payments still ride the CDC pull sweep + webhook.+ { table: "payment", operations: ["INSERT", "UPDATE"] }+ ]+};++export function getSyncSubscriptionName(providerId: ProviderID): string {+ return `${providerId}-sync`;+}++export type EnsureSubscriptionsResult = {+ /** Tables upserted (created or refreshed to the required shape). */+ ensured: string[];+ /** Subscription rows removed because their table is no longer required. */+ removed: string[];+};++/**+ * Converge a company's `${providerId}-sync` subscription rows onto+ * REQUIRED_SYNC_SUBSCRIPTIONS. Idempotent: the create RPC upserts on+ * (companyId, name, table) — re-running refreshes operations/config/active+ * without churning rows — and rows for tables no longer in the required+ * list are deleted. Safe to call from the install hook, every settings+ * save, and the reconciliation sweep.+ */+export async function ensureProviderSubscriptions(+ client: SupabaseClient<Database>,+ companyId: string,+ providerId: ProviderID+): Promise<EnsureSubscriptionsResult> {+ const required = REQUIRED_SYNC_SUBSCRIPTIONS[providerId];+ const name = getSyncSubscriptionName(providerId);++ for (const subscription of required) {+ await createEventSystemSubscription(client, {+ table: subscription.table,+ companyId,+ name,+ operations: subscription.operations,+ type: "SYNC",+ config: { provider: providerId },+ active: true+ });+ }++ const requiredTables = new Set(+ required.map((subscription) => subscription.table)+ );++ const existing = await client+ .from("eventSystemSubscription")+ .select("id, table")+ .eq("companyId", companyId)+ .eq("name", name);++ if (existing.error) {+ throw new Error(+ `Failed to list ${name} subscriptions: ${existing.error.message}`+ );+ }++ const removed: string[] = [];+ for (const row of existing.data ?? []) {+ if (!requiredTables.has(row.table as CreateSubscriptionParams["table"])) {+ await deleteEventSystemSubscription(client, row.id);+ removed.push(row.table);+ }+ }++ return {+ ensured: required.map((subscription) => subscription.table),+ removed+ };+}diff --git a/packages/ee/src/accounting/core/sync-config.test.ts b/packages/ee/src/accounting/core/sync-config.test.tsnew file mode 100644index 0000000000..2e811a1b1f--- /dev/null+++ b/packages/ee/src/accounting/core/sync-config.test.ts@@ -0,0 +1,98 @@+import { configureSync, reset } from "@logtape/logtape";+import { createLogRecorder } from "@logtape/testing";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { DEFAULT_SYNC_CONFIG } from "./models";+import { resolveSyncConfig } from "./service";++const recorder = createLogRecorder();++describe("resolveSyncConfig", () => {+ beforeEach(() => {+ recorder.clear();+ configureSync({+ reset: true,+ sinks: { recorder: recorder.sink },+ loggers: [+ { category: ["carbon"], lowestLevel: "trace", sinks: ["recorder"] }+ ]+ });+ });++ afterEach(async () => {+ await reset();+ });++ it("returns the defaults when no config is stored", () => {+ expect(resolveSyncConfig(undefined)).toEqual(DEFAULT_SYNC_CONFIG);+ expect(resolveSyncConfig(null)).toEqual(DEFAULT_SYNC_CONFIG);+ expect(resolveSyncConfig({})).toEqual(DEFAULT_SYNC_CONFIG);+ expect(resolveSyncConfig({ syncConfig: {} })).toEqual(DEFAULT_SYNC_CONFIG);++ // Never hands back (or mutates) the shared default object+ const resolved = resolveSyncConfig(undefined);+ expect(resolved).not.toBe(DEFAULT_SYNC_CONFIG);+ expect(resolved.entities.item).not.toBe(DEFAULT_SYNC_CONFIG.entities.item);+ });++ it("merges stored per-entity overrides over the defaults", () => {+ const resolved = resolveSyncConfig({+ syncConfig: { entities: { item: { enabled: false } } }+ });++ expect(resolved.entities.item).toEqual({+ ...DEFAULT_SYNC_CONFIG.entities.item,+ enabled: false+ });++ // Every other entity keeps its default config+ for (const entityType of Object.keys(DEFAULT_SYNC_CONFIG.entities) as Array<+ keyof typeof DEFAULT_SYNC_CONFIG.entities+ >) {+ if (entityType === "item") continue;+ expect(resolved.entities[entityType]).toEqual(+ DEFAULT_SYNC_CONFIG.entities[entityType]+ );+ }+ });++ it("ignores invalid fragments with a warning and keeps the default", () => {+ const resolved = resolveSyncConfig({+ syncConfig: {+ entities: {+ customer: { direction: "sideways" },+ item: { enabled: false }+ }+ }+ });++ // Invalid fragment → default kept, warning logged+ expect(resolved.entities.customer).toEqual(+ DEFAULT_SYNC_CONFIG.entities.customer+ );+ const warnings = recorder.records.filter((r) => r.level === "warning");+ expect(warnings).toHaveLength(1);+ expect(warnings[0]?.message.join("")).toContain(+ "Ignoring invalid stored sync config"+ );++ // Valid fragment in the same config still applies+ expect(resolved.entities.item.enabled).toBe(false);+ });++ it("ignores unknown keys in stored fragments", () => {+ const resolved = resolveSyncConfig({+ syncConfig: {+ entities: {+ item: { enabled: false, batchSize: 500, direction: "two-way" }+ }+ }+ });++ expect(resolved.entities.item).toEqual({+ ...DEFAULT_SYNC_CONFIG.entities.item,+ enabled: false,+ direction: "two-way"+ });+ expect("batchSize" in resolved.entities.item).toBe(false);+ });+});diff --git a/packages/ee/src/accounting/core/sync-factory.test.ts b/packages/ee/src/accounting/core/sync-factory.test.tsnew file mode 100644index 0000000000..66e61a30eb--- /dev/null+++ b/packages/ee/src/accounting/core/sync-factory.test.ts@@ -0,0 +1,246 @@+import { describe, expect, it } from "vitest";+import type { AccountingProvider } from "../providers";+// Importing the barrels runs their module-scope SyncFactory.register calls —+// the same side effect every runtime consumer gets via @carbon/ee/accounting.+import { qboSyncerRegistry } from "../providers/quickbooks-online";+import { QboBillSyncer } from "../providers/quickbooks-online/entities/bill";+import { QboCustomerSyncer } from "../providers/quickbooks-online/entities/customer";+import { QboSalesInvoiceSyncer } from "../providers/quickbooks-online/entities/invoice";+import { QboItemSyncer } from "../providers/quickbooks-online/entities/item";+import { QboJournalEntrySyncer } from "../providers/quickbooks-online/entities/journal-entry";+import { QboPaymentSyncer } from "../providers/quickbooks-online/entities/payment";+import { QboPurchaseOrderSyncer } from "../providers/quickbooks-online/entities/purchase-order";+import { QboVendorSyncer } from "../providers/quickbooks-online/entities/vendor";+import { rilletSyncerRegistry } from "../providers/rillet";+import { RilletBillSyncer } from "../providers/rillet/entities/bill";+import { RilletCustomerSyncer } from "../providers/rillet/entities/customer";+import { RilletSalesInvoiceSyncer } from "../providers/rillet/entities/invoice";+import { RilletItemSyncer } from "../providers/rillet/entities/item";+import { RilletJournalEntrySyncer } from "../providers/rillet/entities/journal-entry";+import { RilletPaymentSyncer } from "../providers/rillet/entities/payment";+import { RilletVendorSyncer } from "../providers/rillet/entities/vendor";+import { xeroSyncerRegistry } from "../providers/xero";+import { BillSyncer } from "../providers/xero/entities/bill";+import { ContactSyncer } from "../providers/xero/entities/contact";+import { InventoryAdjustmentSyncer } from "../providers/xero/entities/inventory-adjustment";+import { SalesInvoiceSyncer } from "../providers/xero/entities/invoice";+import { ItemSyncer } from "../providers/xero/entities/item";+import { JournalEntrySyncer } from "../providers/xero/entities/journal-entry";+import { XeroPaymentSyncer } from "../providers/xero/entities/payment";+import { PurchaseOrderSyncer } from "../providers/xero/entities/purchase-order";+import { SalesOrderSyncer } from "../providers/xero/entities/sales-order";+import { ProviderID } from "./models";+import { SyncFactory } from "./sync";+import type { AccountingEntityType, SyncContext } from "./types";++function makeContext(+ entityType: AccountingEntityType,+ providerId: string = ProviderID.XERO+): SyncContext {+ return {+ database: {} as unknown as SyncContext["database"],+ companyId: "test-company",+ provider: { id: providerId } as unknown as AccountingProvider,+ config: {+ enabled: true,+ direction: "two-way",+ owner: "carbon"+ },+ entityType+ };+}++/**+ * The exact set of syncers the pre-registry switch resolved (plus the+ * Phase B journalEntry case). Any change here is a behavior change for+ * the Xero integration.+ */+const EXPECTED_XERO_SYNCERS: Record<string, string> = {+ customer: "ContactSyncer",+ vendor: "ContactSyncer",+ item: "ItemSyncer",+ bill: "BillSyncer",+ invoice: "SalesInvoiceSyncer",+ purchaseOrder: "PurchaseOrderSyncer",+ salesOrder: "SalesOrderSyncer",+ inventoryAdjustment: "InventoryAdjustmentSyncer",+ journalEntry: "JournalEntrySyncer"+};++describe("SyncFactory", () => {+ it("resolves every supported Xero entity type to the same class as the old switch", () => {+ for (const [entityType, expectedClassName] of Object.entries(+ EXPECTED_XERO_SYNCERS+ )) {+ const syncer = SyncFactory.getSyncer(+ makeContext(entityType as AccountingEntityType)+ );+ expect(syncer.constructor.name).toBe(expectedClassName);+ }+ });++ it("constructs instances of the exact registered classes", () => {+ expect(SyncFactory.getSyncer(makeContext("customer"))).toBeInstanceOf(+ ContactSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("vendor"))).toBeInstanceOf(+ ContactSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("item"))).toBeInstanceOf(+ ItemSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("bill"))).toBeInstanceOf(+ BillSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("invoice"))).toBeInstanceOf(+ SalesInvoiceSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("purchaseOrder"))).toBeInstanceOf(+ PurchaseOrderSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("salesOrder"))).toBeInstanceOf(+ SalesOrderSyncer+ );+ expect(+ SyncFactory.getSyncer(makeContext("inventoryAdjustment"))+ ).toBeInstanceOf(InventoryAdjustmentSyncer);+ expect(SyncFactory.getSyncer(makeContext("journalEntry"))).toBeInstanceOf(+ JournalEntrySyncer+ );+ });++ it("registers exactly the expected Xero entity types", () => {+ expect(xeroSyncerRegistry).toEqual({+ customer: ContactSyncer,+ vendor: ContactSyncer,+ item: ItemSyncer,+ bill: BillSyncer,+ invoice: SalesInvoiceSyncer,+ purchaseOrder: PurchaseOrderSyncer,+ salesOrder: SalesOrderSyncer,+ inventoryAdjustment: InventoryAdjustmentSyncer,+ journalEntry: JournalEntrySyncer,+ // Phase 3: pull-only Xero payment sync-back (ACCREC → AR, ACCPAY → AP)+ payment: XeroPaymentSyncer+ });+ });++ it("resolves the Xero payment syncer (Phase 3)", () => {+ expect(SyncFactory.getSyncer(makeContext("payment"))).toBeInstanceOf(+ XeroPaymentSyncer+ );+ });++ it("throws the descriptive error for an unregistered entity type", () => {+ expect(() => SyncFactory.getSyncer(makeContext("employee"))).toThrow(+ /^No Syncer implementation found for entity type: employee$/+ );+ });++ it("throws the descriptive error for an unknown provider", () => {+ expect(() =>+ SyncFactory.getSyncer(makeContext("customer", "sage"))+ ).toThrow(/^No Syncer registry found for provider: sage$/);+ });++ it("resolves both providers side by side (customer → ContactSyncer for Xero, QboCustomerSyncer for QBO)", () => {+ expect(SyncFactory.getSyncer(makeContext("customer"))).toBeInstanceOf(+ ContactSyncer+ );+ expect(+ SyncFactory.getSyncer(makeContext("customer", ProviderID.QUICKBOOKS))+ ).toBeInstanceOf(QboCustomerSyncer);+ });++ it("registers exactly the expected QuickBooks Online entity types", () => {+ expect(qboSyncerRegistry).toEqual({+ customer: QboCustomerSyncer,+ vendor: QboVendorSyncer,+ item: QboItemSyncer,+ bill: QboBillSyncer,+ invoice: QboSalesInvoiceSyncer,+ purchaseOrder: QboPurchaseOrderSyncer,+ journalEntry: QboJournalEntrySyncer,+ payment: QboPaymentSyncer+ });+ });++ it("constructs instances of the exact registered QBO classes", () => {+ const qbo = ProviderID.QUICKBOOKS;+ expect(SyncFactory.getSyncer(makeContext("vendor", qbo))).toBeInstanceOf(+ QboVendorSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("item", qbo))).toBeInstanceOf(+ QboItemSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("bill", qbo))).toBeInstanceOf(+ QboBillSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("invoice", qbo))).toBeInstanceOf(+ QboSalesInvoiceSyncer+ );+ expect(+ SyncFactory.getSyncer(makeContext("purchaseOrder", qbo))+ ).toBeInstanceOf(QboPurchaseOrderSyncer);+ expect(+ SyncFactory.getSyncer(makeContext("journalEntry", qbo))+ ).toBeInstanceOf(QboJournalEntrySyncer);+ });++ it("registers exactly the expected Rillet entity types", () => {+ expect(Object.keys(rilletSyncerRegistry).sort()).toEqual(+ [+ "bill",+ "customer",+ "invoice",+ "item",+ "journalEntry",+ "payment",+ "vendor"+ ].sort()+ );+ });++ it("constructs instances of the exact registered Rillet classes", () => {+ const rillet = ProviderID.RILLET;+ expect(+ SyncFactory.getSyncer(makeContext("customer", rillet))+ ).toBeInstanceOf(RilletCustomerSyncer);+ expect(SyncFactory.getSyncer(makeContext("vendor", rillet))).toBeInstanceOf(+ RilletVendorSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("item", rillet))).toBeInstanceOf(+ RilletItemSyncer+ );+ expect(SyncFactory.getSyncer(makeContext("bill", rillet))).toBeInstanceOf(+ RilletBillSyncer+ );+ expect(+ SyncFactory.getSyncer(makeContext("invoice", rillet))+ ).toBeInstanceOf(RilletSalesInvoiceSyncer);+ expect(+ SyncFactory.getSyncer(makeContext("journalEntry", rillet))+ ).toBeInstanceOf(RilletJournalEntrySyncer);+ expect(+ SyncFactory.getSyncer(makeContext("payment", rillet))+ ).toBeInstanceOf(RilletPaymentSyncer);+ });++ it("throws for entity types Rillet does not implement (no PO endpoint)", () => {+ expect(() =>+ SyncFactory.getSyncer(makeContext("purchaseOrder", ProviderID.RILLET))+ ).toThrow(/No Syncer implementation found/);+ expect(() =>+ SyncFactory.getSyncer(+ makeContext("inventoryAdjustment", ProviderID.RILLET)+ )+ ).toThrow(/No Syncer implementation found/);+ });++ it("merges when registering the same provider twice", () => {+ SyncFactory.register(ProviderID.XERO, {});+ expect(SyncFactory.getSyncer(makeContext("customer"))).toBeInstanceOf(+ ContactSyncer+ );+ });+});diff --git a/packages/ee/src/accounting/core/sync.ts b/packages/ee/src/accounting/core/sync.tsindex c786e716bc..0b7a062e5a 100644--- a/packages/ee/src/accounting/core/sync.ts+++ b/packages/ee/src/accounting/core/sync.ts@@ -1,50 +1,56 @@-import { BillSyncer } from "../providers/xero/entities/bill";-import { ContactSyncer } from "../providers/xero/entities/contact";-import { InventoryAdjustmentSyncer } from "../providers/xero/entities/inventory-adjustment";-import { SalesInvoiceSyncer } from "../providers/xero/entities/invoice";-import { ItemSyncer } from "../providers/xero/entities/item";-import { PurchaseOrderSyncer } from "../providers/xero/entities/purchase-order";-import { SalesOrderSyncer } from "../providers/xero/entities/sales-order";-import type { IEntitySyncer, SyncContext } from "./types";+import type { ProviderID } from "./models";+import type { AccountingEntityType, IEntitySyncer, SyncContext } from "./types";++/**+ * Constructor shape shared by every entity syncer: constructed with the+ * execution context only (see BaseEntitySyncer).+ */+export type SyncerConstructor = new (context: SyncContext) => IEntitySyncer;++/**+ * A provider's syncer classes, keyed by the entity types it supports.+ */+export type SyncerRegistry = Partial<+ Record<AccountingEntityType, SyncerConstructor>+>;++/**+ * Syncer registries keyed by provider. Populated at module scope by each+ * provider's barrel (e.g. providers/xero registers xeroSyncerRegistry), so+ * importing a provider is what makes its syncers resolvable.+ */+const registries: Partial<Record<ProviderID, SyncerRegistry>> = {};export const SyncFactory = {/**- * Instantiates the correct Syncer class based on the Entity Type from context.+ * Registers (or extends) a provider's syncer registry. Called at module+ * scope from the provider's barrel; registering the same provider twice+ * merges the registries.+ */+ register(providerId: ProviderID, registry: SyncerRegistry): void {+ registries[providerId] = { ...registries[providerId], ...registry };+ },++ /**+ * Instantiates the correct Syncer class based on the Provider and the+ * Entity Type from context.* @param context - The execution context (DB connection, Provider, Config, entityType)*/getSyncer(context: SyncContext): IEntitySyncer {- switch (context.entityType) {- // Master Data- case "vendor":- case "customer":- return new ContactSyncer(context);- case "item":- return new ItemSyncer(context);-- // Transaction Data- case "bill":- return new BillSyncer(context);- case "invoice":- return new SalesInvoiceSyncer(context);- case "purchaseOrder":- return new PurchaseOrderSyncer(context);-- case "inventoryAdjustment":- return new InventoryAdjustmentSyncer(context);-- case "salesOrder":- return new SalesOrderSyncer(context);-- // Not yet implemented- // case "employee":- // Xero no longer supports the Employees API- // case "payment":- // return new PaymentSyncer(context);+ const registry = registries[context.provider.id];+ if (!registry) {+ throw new Error(+ `No Syncer registry found for provider: ${context.provider.id}`+ );+ }- default:- throw new Error(- `No Syncer implementation found for entity type: ${context.entityType}`- );+ const Syncer = registry[context.entityType];+ if (!Syncer) {+ throw new Error(+ `No Syncer implementation found for entity type: ${context.entityType}`+ );}++ return new Syncer(context);}};diff --git a/packages/ee/src/accounting/core/types.ts b/packages/ee/src/accounting/core/types.tsindex 1f1a8cf761..f9d08b3648 100644--- a/packages/ee/src/accounting/core/types.ts+++ b/packages/ee/src/accounting/core/types.ts@@ -16,6 +16,8 @@ import type {EmployeeSchema,InventoryAdjustmentSchema,ItemSchema,+ JournalEntryLineSchema,+ JournalEntrySchema,ProviderCredentialsSchema,ProviderID,ProviderIntegrationMetadataSchema,@@ -25,8 +27,13 @@ import type {SalesInvoiceSchema,SalesOrderLineSchema,SalesOrderSchema,- SyncDirectionSchema+ SyncDirectionSchema,+ SyncOperationDirectionSchema,+ SyncOperationSchema,+ SyncOperationStatusSchema,+ SyncOperationTriggerSchema} from "./models";+import { JournalEntrySyncError } from "./posting";import { AccountingApiError, withTriggersDisabled } from "./utils";const logger = getLogger("ee", "accounting");@@ -64,12 +71,122 @@ export type ProviderConfig<T = unknown> = {onTokenRefresh?: OAuthClientOptions["onTokenRefresh"];} & T;+/**+ * Static description of how a provider communicates and what it supports.+ */+export interface ProviderCapabilities {+ /**+ * How the provider is reached: "rest" = Carbon calls the provider API+ * synchronously; "bridge" = a third-party vendor bridge performs the calls.+ */+ transport: "rest" | "bridge";+ /** Whether the provider can push change notifications to Carbon. */+ supportsWebhooks: boolean;+ /** Whether Carbon journals can be pushed as provider journal entries. */+ supportsJournalPush: boolean;+ /**+ * Structural cap on how many dimension slots the provider's journal+ * lines can carry (QBO: 2 — one ClassRef + one DepartmentRef; Xero: 2 —+ * org-wide tracking-category limit). Absent = no structural cap+ * (Rillet Fields are dimension-native).+ */+ maxJournalDimensionSlots?: number;+}++/**+ * One analytics field a provider can carry on pushed journal lines — a+ * QBO Class/Department, a Xero tracking category, a Rillet Field. The+ * settings UI offers only targets the provider actually declares (via+ * `journalDimensionTargets()`), so slot config can never point at a+ * feature the org doesn't have.+ */+export interface DimensionTarget {+ /**+ * Provider-specific target id stored on the dimension slot:+ * QBO `"class"` / `"department"`, Xero `"tracking:<categoryId>"`,+ * Rillet `"field:<fieldId>"`.+ */+ id: string;+ /** Human label for the settings UI (e.g. the tracking category name). */+ label: string;+ /** Max slots that may use this target. Absent = 1. */+ capacity?: number;+}++/**+ * One remote change observed by an incremental pull (the sweep cron).+ */+export interface ProviderChange {+ entityType: AccountingEntityType;+ /**+ * Remote id used as the sync operation's entityId. Composite ids are+ * allowed where an entity is only addressable through its parent (e.g.+ * Rillet payments use "<invoiceRemoteId>:<paymentRemoteId>").+ */+ remoteId: string;+ /** Remote last-updated timestamp (ISO 8601) driving cursor advance. */+ updatedAt: string | null;+ /** Remote deletion stub — logged and skipped (DELETE sync is unimplemented). */+ deleted?: boolean;+ /**+ * Local mapping this change's processing depends on. The sweep skips the+ * change (without a ledger row) when the mapping is absent — the+ * ownership filter for providers whose org is shared by several Carbon+ * instances (e.g. Rillet payments on another subsidiary's invoices).+ */+ dependsOnMapping?: { entityType: AccountingEntityType; remoteId: string };+}++export interface ListChangesResult {+ changes: ProviderChange[];+}++/**+ * Incremental remote-change pull, implemented by providers the generic+ * accounting-pull-sweep cron can poll (webhooks are a latency+ * optimization; the sweep is the correctness guarantee). Providers filter+ * internally to entities whose resolved sync config allows pull; the+ * sweep owns cursor state and clamps `since` to `pullLookbackDays` before+ * calling.+ */+export interface SupportsIncrementalPull {+ /**+ * Days the provider's change feed can reach back, when capped (QBO CDC:+ * 30, clamped to 29 for margin). Absent = unbounded.+ */+ readonly pullLookbackDays?: number;+ listChanges(args: { since: string }): Promise<ListChangesResult>;+}++export function providerSupportsIncrementalPull<T extends BaseProvider>(+ provider: T+): provider is T & SupportsIncrementalPull {+ return (+ typeof (provider as Partial<SupportsIncrementalPull>).listChanges ===+ "function"+ );+}+export abstract class BaseProvider {static id: ProviderID;+ /**+ * Optional capability declaration. When absent, callers should assume a+ * REST provider (`transport: "rest"`) — the default for all providers+ * that predate this field (e.g. Xero).+ */+ readonly capabilities?: ProviderCapabilities;+protected creds?: ProviderCredentials;public auth!: AuthProvider;+ /**+ * Optional: the journal-line analytics targets this provider offers for+ * dimension slots (see DimensionTarget). Absent = the provider carries+ * no journal dimensions.+ */+ journalDimensionTargets?(): Promise<DimensionTarget[]>;+abstract getSyncConfig<T extends AccountingEntityType>(entity: T): GlobalSyncConfig["entities"][T];@@ -89,6 +206,13 @@ export abstract class BaseProvider {export type SyncDirection = z.infer<typeof SyncDirectionSchema>;+export type SyncOperation = z.infer<typeof SyncOperationSchema>;+export type SyncOperationStatus = z.infer<typeof SyncOperationStatusSchema>;+export type SyncOperationDirection = z.infer<+ typeof SyncOperationDirectionSchema+>;+export type SyncOperationTrigger = z.infer<typeof SyncOperationTriggerSchema>;+/*** Defines which system owns the data integrity.* - 'carbon': Carbon data overwrites Accounting data.@@ -111,7 +235,8 @@ export type AccountingEntityType =| "salesOrder"| "invoice"| "payment"- | "inventoryAdjustment";+ | "inventoryAdjustment"+ | "journalEntry";export interface EntityConfig {/** Is this entity sync active? */@@ -179,6 +304,17 @@ export interface SyncResult {error?: unknown;}+/**+ * Normalize a thrown value for SyncResult.error. A JournalEntrySyncError+ * keeps its structured failure envelope (errorCode/warning/metadata) so+ * the ledger drain records a Warning with machine-readable detail instead+ * of a flattened Failed string — batch pushes previously lost this.+ */+export function toSyncResultError(err: unknown): unknown {+ if (err instanceof JournalEntrySyncError) return err.failure;+ return err instanceof Error ? err.message : String(err);+}+export interface BatchSyncResult {results: SyncResult[];successCount: number;@@ -401,6 +537,7 @@ export abstract class BaseEntitySyncer<return {status: "skipped",action: "none",+ localId: entityId,error: "Sync disabled in config"};}@@ -484,7 +621,7 @@ export abstract class BaseEntitySyncer<status: "error",action: "none",localId: entityId,- error: err instanceof Error ? err.message : String(err)+ error: toSyncResultError(err)};}}@@ -498,6 +635,7 @@ export abstract class BaseEntitySyncer<return {status: "skipped",action: "none",+ remoteId,error: "Sync disabled in config"};}@@ -591,7 +729,7 @@ export abstract class BaseEntitySyncer<status: "error",action: "none",remoteId,- error: err instanceof Error ? err.message : String(err)+ error: toSyncResultError(err)};}}@@ -668,7 +806,7 @@ export abstract class BaseEntitySyncer<status: "error",action: "none",localId,- error: err instanceof Error ? err.message : String(err)+ error: toSyncResultError(err)});}}@@ -727,7 +865,7 @@ export abstract class BaseEntitySyncer<status: "error",action: "none",localId: id,- error: err instanceof Error ? err.message : String(err)+ error: toSyncResultError(err)});}}@@ -834,7 +972,7 @@ export abstract class BaseEntitySyncer<status: "error",action: "none",remoteId,- error: err instanceof Error ? err.message : String(err)+ error: toSyncResultError(err)});}}@@ -846,7 +984,7 @@ export abstract class BaseEntitySyncer<status: "error",action: "none",remoteId: id,- error: err instanceof Error ? err.message : String(err)+ error: toSyncResultError(err)});}}@@ -1008,6 +1146,8 @@ export namespace Accounting {export type InventoryAdjustment = z.infer<typeof InventoryAdjustmentSchema>;export type SalesOrder = z.infer<typeof SalesOrderSchema>;export type SalesOrderLine = z.infer<typeof SalesOrderLineSchema>;+ export type JournalEntry = z.infer<typeof JournalEntrySchema>;+ export type JournalEntryLine = z.infer<typeof JournalEntryLineSchema>;}export interface RequestContext {diff --git a/packages/ee/src/accounting/core/utils.ts b/packages/ee/src/accounting/core/utils.tsindex 09184d5d4e..41f209396b 100644--- a/packages/ee/src/accounting/core/utils.ts+++ b/packages/ee/src/accounting/core/utils.ts@@ -427,7 +427,7 @@ export function createOAuthClient({const basicAuth = btoa(`${clientId}:${clientSecret}`);const http = new HTTPClient();- let creds: ProviderCredentials = {+ let creds: Extract<ProviderCredentials, { type: "oauth2" }> = {type: "oauth2",accessToken: options.accessToken!,refreshToken: options.refreshToken!@@ -452,8 +452,16 @@ export function createOAuthClient({})});- if (response.error || !response.data) {- throw new Error(`Auth failed: ${response.data}`);+ if (response.error || !response.data?.access_token) {+ // Surface the provider's actual rejection (e.g. invalid_grant /+ // invalid_client) instead of the useless "[object Object]".+ throw new Error(+ `Token exchange failed (HTTP ${response.code}): ${+ typeof response.data === "string"+ ? response.data+ : JSON.stringify(response.data)+ }`+ );}const newCreds = {@@ -510,7 +518,7 @@ export function createOAuthClient({expiresAt: new Date(Date.now() + response.data.expires_in * 1000).toISOString(),- tenantId: creds?.tenantId+ providerMetadata: creds?.providerMetadata} satisfies ProviderCredentials;creds = {diff --git a/packages/ee/src/accounting/index.ts b/packages/ee/src/accounting/index.tsindex 10d1bb0e84..e6c69d3acd 100644--- a/packages/ee/src/accounting/index.ts+++ b/packages/ee/src/accounting/index.ts@@ -1,6 +1,16 @@+export * from "./core/account-mapping";+export * from "./core/account-mapping-ai";+export * from "./core/dimension-mapping";+export * from "./core/document-costing";export * from "./core/external-mapping";export * from "./core/models";+export * from "./core/operations";+export * from "./core/payment-syncer";+export * from "./core/payment-tombstone";+export * from "./core/posting";+export * from "./core/remote-journal";export * from "./core/service";+export * from "./core/subscriptions";export * from "./core/sync";export * from "./core/types";export * from "./core/utils";diff --git a/packages/ee/src/accounting/providers/index.ts b/packages/ee/src/accounting/providers/index.tsindex a38b816a63..b5f7c0d444 100644--- a/packages/ee/src/accounting/providers/index.ts+++ b/packages/ee/src/accounting/providers/index.ts@@ -1,5 +1,9 @@+import type { QboProvider } from "./quickbooks-online";+import type { RilletProvider } from "./rillet";import type { XeroProvider } from "./xero";-export type AccountingProvider = XeroProvider;+export type AccountingProvider = XeroProvider | QboProvider | RilletProvider;+export * from "./quickbooks-online";+export * from "./rillet";export * from "./xero";diff --git a/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-cdc.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-cdc.test.tsnew file mode 100644index 0000000000..08f9a5f698--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-cdc.test.ts@@ -0,0 +1,242 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_SYNC_CONFIG } from "../../../core/models";+import { AccountingApiError } from "../../../core/utils";+import { isQboDuplicateNameError, QboProvider } from "../provider";++const REALM_ID = "9130357849328710";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+}++function makeProvider() {+ return new QboProvider({+ companyId: "company-1",+ clientId: "client-id",+ clientSecret: "client-secret",+ accessToken: "access-token",+ refreshToken: "refresh-token",+ realmId: REALM_ID,+ syncConfig: DEFAULT_SYNC_CONFIG,+ onTokenRefresh: vi.fn(async () => undefined)+ });+}++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++function requestUrl(callIndex: number): string {+ return decodeURIComponent(String(fetchMock.mock.calls[callIndex]?.[0]));+}++/**+ * Realistic CDC envelope: one QueryResponse per changed entity type, mixing+ * full objects (whose extra fields the minimal parse ignores) with a+ * `status: "Deleted"` tombstone stub.+ */+const CDC_FIXTURE = {+ CDCResponse: [+ {+ QueryResponse: [+ {+ Customer: [+ {+ Id: "63",+ SyncToken: "4",+ DisplayName: "Acme Machining",+ Active: true,+ MetaData: {+ CreateTime: "2026-06-01T09:00:00-07:00",+ LastUpdatedTime: "2026-07-08T13:07:59-07:00"+ }+ },+ {+ domain: "QBO",+ status: "Deleted",+ Id: "77",+ MetaData: { LastUpdatedTime: "2026-07-08T14:00:00-07:00" }+ }+ ],+ startPosition: 1,+ maxResults: 2+ },+ {+ Vendor: [+ {+ Id: "41",+ SyncToken: "1",+ DisplayName: "Bolts R Us",+ MetaData: { LastUpdatedTime: "2026-07-08T10:30:00-07:00" }+ }+ ],+ startPosition: 1,+ maxResults: 1+ },+ {+ Invoice: [+ {+ Id: "145",+ SyncToken: "2",+ CustomerRef: { value: "63" },+ Line: [],+ MetaData: { LastUpdatedTime: "2026-07-08T15:45:12-07:00" }+ }+ ],+ startPosition: 1,+ maxResults: 1+ }+ ]+ }+ ],+ time: "2026-07-08T16:00:00-07:00"+};++describe("QboProvider.changeDataCapture", () => {+ it("requests /cdc with the entity list + changedSince and normalizes mixed entities including Deleted stubs", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(CDC_FIXTURE));++ const provider = makeProvider();+ const changes = await provider.changeDataCapture(+ ["Customer", "Vendor", "Invoice"],+ "2026-07-01T00:00:00.000Z"+ );++ expect(requestUrl(0)).toContain(`/v3/company/${REALM_ID}/cdc`);+ expect(requestUrl(0)).toContain("entities=Customer,Vendor,Invoice");+ expect(requestUrl(0)).toContain("changedSince=2026-07-01T00:00:00.000Z");+ expect(requestUrl(0)).toContain("minorversion=75");++ expect(changes).toEqual([+ {+ entityName: "Customer",+ id: "63",+ deleted: false,+ lastUpdatedTime: "2026-07-08T13:07:59-07:00"+ },+ {+ entityName: "Customer",+ id: "77",+ deleted: true,+ lastUpdatedTime: "2026-07-08T14:00:00-07:00"+ },+ {+ entityName: "Vendor",+ id: "41",+ deleted: false,+ lastUpdatedTime: "2026-07-08T10:30:00-07:00"+ },+ {+ entityName: "Invoice",+ id: "145",+ deleted: false,+ lastUpdatedTime: "2026-07-08T15:45:12-07:00"+ }+ ]);+ });++ it("returns [] for an empty CDC window", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ CDCResponse: [{ QueryResponse: [] }],+ time: "2026-07-08T16:00:00-07:00"+ })+ );++ const provider = makeProvider();+ await expect(+ provider.changeDataCapture(["Customer"], "2026-07-01T00:00:00.000Z")+ ).resolves.toEqual([]);+ });++ it("skips records that fail the minimal identity parse and keeps the rest", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ CDCResponse: [+ {+ QueryResponse: [+ {+ Customer: [+ { DisplayName: "No id — unparseable" },+ {+ Id: "88",+ DisplayName: "Kept",+ // No MetaData: still processable, timestamp is null+ SyncToken: "0"+ }+ ]+ }+ ]+ }+ ]+ })+ );++ const provider = makeProvider();+ const changes = await provider.changeDataCapture(+ ["Customer"],+ "2026-07-01T00:00:00.000Z"+ );++ expect(changes).toEqual([+ {+ entityName: "Customer",+ id: "88",+ deleted: false,+ lastUpdatedTime: null+ }+ ]);+ expect(warn).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });++ it("throws a structured AccountingApiError carrying the Intuit fault on failure", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse(+ {+ Fault: {+ Error: [+ {+ Message: "Invalid query",+ Detail: "changedSince cannot be more than 30 days ago",+ code: "4000"+ }+ ],+ type: "ValidationFault"+ }+ },+ 400+ )+ );++ const provider = makeProvider();++ let thrown: unknown;+ try {+ await provider.changeDataCapture(+ ["Customer"],+ "2026-01-01T00:00:00.000Z"+ );+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(AccountingApiError);+ expect((thrown as AccountingApiError).details.providerErrorCode).toBe(+ "4000"+ );+ // Sanity: the fault-code classifiers see the same structured details+ expect(isQboDuplicateNameError(thrown)).toBe(false);+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-dimensions.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-dimensions.test.tsnew file mode 100644index 0000000000..b25c693cf5--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-dimensions.test.ts@@ -0,0 +1,146 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_SYNC_CONFIG } from "../../../core/models";+import {+ QBO_DIMENSION_TARGET_CLASS,+ QBO_DIMENSION_TARGET_DEPARTMENT,+ QboProvider+} from "../provider";++const REALM_ID = "9130357849328710";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+}++function faultResponse(): Response {+ return jsonResponse(+ {+ Fault: {+ Error: [+ {+ Message: "Feature Not Supported",+ Detail: "Class tracking is not enabled for this company.",+ code: "500"+ }+ ],+ type: "ValidationFault"+ }+ },+ 400+ );+}++function makeProvider() {+ return new QboProvider({+ companyId: "company-1",+ clientId: "client-id",+ clientSecret: "client-secret",+ accessToken: "token",+ refreshToken: "refresh",+ realmId: REALM_ID,+ syncConfig: DEFAULT_SYNC_CONFIG+ });+}++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++describe("QboProvider dimension entities (Class / Department)", () => {+ it("declares the 2-slot structural cap (one ClassRef + one DepartmentRef per line)", () => {+ expect(makeProvider().capabilities.maxJournalDimensionSlots).toBe(2);+ });++ it("lists active classes via /query", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ QueryResponse: {+ Class: [{ Id: "300", SyncToken: "0", Name: "Atlanta", Active: true }]+ }+ })+ );++ const classes = await makeProvider().listClasses();+ expect(classes).toEqual([+ { Id: "300", SyncToken: "0", Name: "Atlanta", Active: true }+ ]);+ expect(decodeURIComponent(String(fetchMock.mock.calls[0]?.[0]))).toContain(+ "SELECT * FROM Class WHERE Active = true"+ );+ });++ it("returns [] instead of hard-failing when the Intuit plan has the feature off", async () => {+ fetchMock.mockResolvedValueOnce(faultResponse());+ await expect(makeProvider().listClasses()).resolves.toEqual([]);++ fetchMock.mockResolvedValueOnce(faultResponse());+ await expect(makeProvider().listDepartments()).resolves.toEqual([]);+ });++ it("creates a Class by NAME (dimension autoCreate)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ Class: { Id: "301", SyncToken: "0", Name: "Boston" } })+ );++ const created = await makeProvider().createClass({ Name: "Boston" });+ expect(created.Id).toBe("301");++ const url = String(fetchMock.mock.calls[0]?.[0]);+ expect(url).toContain(`/v3/company/${REALM_ID}/class`);+ expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({+ Name: "Boston"+ });+ });++ it("creates a Department by NAME (dimension autoCreate)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Department: { Id: "500", SyncToken: "0", Name: "Operations" }+ })+ );++ const created = await makeProvider().createDepartment({+ Name: "Operations"+ });+ expect(created.Id).toBe("500");+ expect(String(fetchMock.mock.calls[0]?.[0])).toContain(+ `/v3/company/${REALM_ID}/department`+ );+ });+});++describe("QboProvider.journalDimensionTargets", () => {+ it("offers class + department when both probe queries succeed (even with zero values yet)", async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ QueryResponse: {} })) // Class probe: feature on, no rows+ .mockResolvedValueOnce(jsonResponse({ QueryResponse: {} })); // Department probe++ const targets = await makeProvider().journalDimensionTargets();+ expect(targets).toEqual([+ { id: QBO_DIMENSION_TARGET_CLASS, label: "Class" },+ { id: QBO_DIMENSION_TARGET_DEPARTMENT, label: "Department" }+ ]);+ });++ it("omits a target whose feature the org does not have (query error, not hard-fail)", async () => {+ fetchMock+ .mockResolvedValueOnce(faultResponse()) // Class probe fails+ .mockResolvedValueOnce(jsonResponse({ QueryResponse: {} }));++ const targets = await makeProvider().journalDimensionTargets();+ expect(targets).toEqual([+ { id: QBO_DIMENSION_TARGET_DEPARTMENT, label: "Department" }+ ]);+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-payment-cdc.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-payment-cdc.test.tsnew file mode 100644index 0000000000..91892bc047--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider-payment-cdc.test.ts@@ -0,0 +1,179 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_SYNC_CONFIG } from "../../../core/models";+import { QboProvider } from "../provider";++const REALM_ID = "9130357849328710";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+}++// DEFAULT_SYNC_CONFIG has payment disabled, but the QBO constructor overlays+// buildQboSyncConfig which forces payment → pull-from-accounting + enabled, so+// the CDC sweep requests Payment/BillPayment.+function makeProvider() {+ return new QboProvider({+ companyId: "company-1",+ clientId: "client-id",+ clientSecret: "client-secret",+ accessToken: "access-token",+ refreshToken: "refresh-token",+ realmId: REALM_ID,+ syncConfig: DEFAULT_SYNC_CONFIG,+ onTokenRefresh: vi.fn(async () => undefined)+ });+}++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++describe("QboProvider.listChanges — payment CDC entries", () => {+ it("emits an AP `payment` change with the canonical bill: composite + bill dependency", async () => {+ // 1st fetch: /cdc → one BillPayment delta (identity only)+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ CDCResponse: [+ {+ QueryResponse: [+ {+ BillPayment: [+ {+ Id: "bp-1",+ MetaData: { LastUpdatedTime: "2026-08-01T13:07:59-07:00" }+ }+ ]+ }+ ]+ }+ ]+ })+ );+ // 2nd fetch: GET /billpayment/bp-1 → the full object (LinkedTxn → bill)+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ BillPayment: {+ Id: "bp-1",+ TotalAmt: 500,+ TxnDate: "2026-08-01",+ CurrencyRef: { value: "USD" },+ Line: [+ { Amount: 500, LinkedTxn: [{ TxnId: "bill-9", TxnType: "Bill" }] }+ ],+ MetaData: { LastUpdatedTime: "2026-08-01T13:07:59-07:00" }+ }+ })+ );++ const result = await makeProvider().listChanges({+ since: "2026-07-15T00:00:00.000Z"+ });++ expect(result.changes).toEqual([+ {+ entityType: "payment",+ remoteId: "bill:bill-9:bp-1",+ updatedAt: new Date("2026-08-01T13:07:59-07:00").toISOString(),+ dependsOnMapping: { entityType: "bill", remoteId: "bill-9" }+ }+ ]);+ });++ it("emits an AR `payment` change with the prefix-less invoice composite", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ CDCResponse: [+ {+ QueryResponse: [+ {+ Payment: [+ {+ Id: "pay-1",+ MetaData: { LastUpdatedTime: "2026-08-01T14:00:00-07:00" }+ }+ ]+ }+ ]+ }+ ]+ })+ );+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Payment: {+ Id: "pay-1",+ TotalAmt: 125,+ TxnDate: "2026-08-01",+ CurrencyRef: { value: "USD" },+ Line: [+ { Amount: 125, LinkedTxn: [{ TxnId: "inv-7", TxnType: "Invoice" }] }+ ],+ MetaData: { LastUpdatedTime: "2026-08-01T14:00:00-07:00" }+ }+ })+ );++ const result = await makeProvider().listChanges({+ since: "2026-07-15T00:00:00.000Z"+ });++ expect(result.changes).toEqual([+ {+ entityType: "payment",+ remoteId: "inv-7:pay-1",+ updatedAt: new Date("2026-08-01T14:00:00-07:00").toISOString(),+ dependsOnMapping: { entityType: "invoice", remoteId: "inv-7" }+ }+ ]);+ });++ it("emits a deleted-flagged bare-id change for a deleted payment tombstone (no refetch)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ CDCResponse: [+ {+ QueryResponse: [+ {+ BillPayment: [+ {+ Id: "bp-9",+ status: "Deleted",+ MetaData: { LastUpdatedTime: "2026-08-02T09:00:00-07:00" }+ }+ ]+ }+ ]+ }+ ]+ })+ );++ const result = await makeProvider().listChanges({+ since: "2026-07-15T00:00:00.000Z"+ });++ // Deleted tombstone → a bare-id deleted-flagged change (no dependsOnMapping,+ // the settled document is unknown); the sweep resolves the composite from+ // the existing mapping and enqueues the void.+ expect(result.changes).toEqual([+ {+ entityType: "payment",+ remoteId: "bp-9",+ updatedAt: "2026-08-02T09:00:00-07:00",+ deleted: true+ }+ ]);+ // Only the CDC call — no refetch for a tombstone.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider.test.tsnew file mode 100644index 0000000000..66db38f154--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/__tests__/provider.test.ts@@ -0,0 +1,659 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_SYNC_CONFIG, ProviderID } from "../../../core/models";+import type { ProviderCredentials } from "../../../core/types";+import { AccountingApiError } from "../../../core/utils";+import { Qbo } from "../models";+import {+ buildQboSyncConfig,+ extractQboErrorDetails,+ isQboDuplicateNameError,+ isQboStaleObjectError,+ QBO_CDC_ENTITY_TYPES,+ QBO_FAULT_CODES,+ type QboEnvironment,+ QboProvider+} from "../provider";++const REALM_ID = "9130357849328710";+const TOKEN_URL = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+}++function tokenResponse(accessToken: string, refreshToken: string): Response {+ return jsonResponse({+ access_token: accessToken,+ refresh_token: refreshToken,+ expires_in: 3600+ });+}++function makeProvider(environment?: QboEnvironment) {+ const onTokenRefresh = vi.fn(+ async (_creds: ProviderCredentials): Promise<void> => undefined+ );++ const provider = new QboProvider({+ companyId: "company-1",+ clientId: "client-id",+ clientSecret: "client-secret",+ accessToken: "stale-token",+ refreshToken: "stale-refresh",+ realmId: REALM_ID,+ environment,+ syncConfig: DEFAULT_SYNC_CONFIG,+ onTokenRefresh+ });++ return { provider, onTokenRefresh };+}++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++function requestUrl(callIndex: number): string {+ return decodeURIComponent(String(fetchMock.mock.calls[callIndex]?.[0]));+}++function requestInit(callIndex: number): RequestInit | undefined {+ return fetchMock.mock.calls[callIndex]?.[1];+}++describe("QboProvider base URL", () => {+ it("targets the production host by default, under /v3/company/{realmId} with the pinned minorversion", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ QueryResponse: { Account: [] } })+ );++ const { provider } = makeProvider();+ await provider.query<Qbo.Account>("Account");++ expect(requestUrl(0)).toContain(+ `https://quickbooks.api.intuit.com/v3/company/${REALM_ID}/query`+ );+ expect(requestUrl(0)).toContain("minorversion=75");+ });++ it("targets the sandbox host when environment is sandbox", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ QueryResponse: { Account: [] } })+ );++ const { provider } = makeProvider("sandbox");+ await provider.query<Qbo.Account>("Account");++ expect(requestUrl(0)).toContain(+ `https://sandbox-quickbooks.api.intuit.com/v3/company/${REALM_ID}/query`+ );+ });++ it("identifies as the quickbooks provider", () => {+ const { provider } = makeProvider();+ expect(provider.id).toBe(ProviderID.QUICKBOOKS);+ expect(provider.capabilities).toEqual({+ transport: "rest",+ supportsWebhooks: false,+ supportsJournalPush: true,+ maxJournalDimensionSlots: 2+ });+ });+});++describe("QboProvider refresh-on-401", () => {+ it("refreshes the token once via the Intuit bearer endpoint and replays the request", async () => {+ // 1st: API rejects the stale token+ fetchMock.mockResolvedValueOnce(jsonResponse({ Fault: {} }, 401));+ // 2nd: refresh_token grant succeeds+ fetchMock.mockResolvedValueOnce(tokenResponse("new-token", "new-refresh"));+ // 3rd: replayed API call succeeds+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ CompanyInfo: { Id: "1", CompanyName: "Sandbox Company_US_1" }+ })+ );++ const { provider, onTokenRefresh } = makeProvider();+ const companyInfo = await provider.getCompanyInfo();++ expect(companyInfo?.CompanyName).toBe("Sandbox Company_US_1");+ expect(fetchMock).toHaveBeenCalledTimes(3);++ // The refresh went to Intuit's bearer endpoint with Basic auth and the+ // refresh_token grant+ expect(String(fetchMock.mock.calls[1]?.[0])).toBe(TOKEN_URL);+ const tokenInit = requestInit(1);+ expect((tokenInit?.headers as Record<string, string>).Authorization).toBe(+ `Basic ${btoa("client-id:client-secret")}`+ );+ expect(String(tokenInit?.body)).toContain("grant_type=refresh_token");+ expect(String(tokenInit?.body)).toContain("refresh_token=stale-refresh");++ // The replay used the refreshed bearer token+ const retryInit = requestInit(2);+ expect((retryInit?.headers as Record<string, string>).Authorization).toBe(+ "Bearer new-token"+ );++ // The new credentials were persisted through the onTokenRefresh callback+ expect(onTokenRefresh).toHaveBeenCalledTimes(1);+ expect(onTokenRefresh.mock.calls[0]?.[0]).toMatchObject({+ type: "oauth2",+ accessToken: "new-token",+ refreshToken: "new-refresh"+ });+ });++ it("retries at most once — a second 401 is returned, not refreshed again", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ Fault: {} }, 401));+ fetchMock.mockResolvedValueOnce(tokenResponse("new-token", "new-refresh"));+ fetchMock.mockResolvedValueOnce(jsonResponse({ Fault: {} }, 401));++ const { provider, onTokenRefresh } = makeProvider();+ const response = await provider.request("GET", `/companyinfo/${REALM_ID}`);++ expect(response.error).toBe(true);+ expect(response.code).toBe(401);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(onTokenRefresh).toHaveBeenCalledTimes(1);+ });+});++describe("QboProvider query pagination", () => {+ it("pages with STARTPOSITION/MAXRESULTS until a short page", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ QueryResponse: { Customer: [{ Id: "1" }, { Id: "2" }] }+ })+ );+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ QueryResponse: { Customer: [{ Id: "3" }] } })+ );++ const { provider } = makeProvider();+ const customers = await provider.query<{ Id: string }>(+ "Customer",+ "Active = true",+ 1,+ 2+ );++ expect(customers.map((customer) => customer.Id)).toEqual(["1", "2", "3"]);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(requestUrl(0)).toContain(+ "SELECT * FROM Customer WHERE Active = true STARTPOSITION 1 MAXRESULTS 2"+ );+ expect(requestUrl(1)).toContain("STARTPOSITION 3 MAXRESULTS 2");+ });++ it("caps MAXRESULTS at 1000 and handles a QueryResponse without the entity key", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ QueryResponse: {} }));++ const { provider } = makeProvider();+ const items = await provider.query<Qbo.Item>("Item", undefined, 1, 5000);++ expect(items).toEqual([]);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(requestUrl(0)).toContain("MAXRESULTS 1000");+ });++ it("throws a structured AccountingApiError when the query fails", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ Fault: { type: "ValidationFault" } }, 400)+ );++ const { provider } = makeProvider();++ await expect(provider.query("Customer")).rejects.toThrow(+ /query Customer failed/+ );+ });+});++describe("Qbo models", () => {+ it("parses a journal entry with Debit/Credit posting types", () => {+ const journal = Qbo.JournalEntrySchema.parse({+ Id: "147",+ SyncToken: "0",+ DocNumber: "JE000042",+ TxnDate: "2026-07-01",+ PrivateNote: "Carbon je_123",+ Line: [+ {+ Description: "Inventory",+ Amount: 150,+ DetailType: "JournalEntryLineDetail",+ JournalEntryLineDetail: {+ PostingType: "Debit",+ AccountRef: { value: "82", name: "Inventory Asset" }+ }+ },+ {+ Amount: 150,+ DetailType: "JournalEntryLineDetail",+ JournalEntryLineDetail: {+ PostingType: "Credit",+ AccountRef: { value: "90" }+ }+ }+ ]+ });++ expect(+ journal.Line.map((line) => line.JournalEntryLineDetail.PostingType)+ ).toEqual(["Debit", "Credit"]);++ expect(() =>+ Qbo.JournalEntryLineSchema.parse({+ Amount: 150,+ DetailType: "JournalEntryLineDetail",+ JournalEntryLineDetail: {+ PostingType: "DEBIT",+ AccountRef: { value: "82" }+ }+ })+ ).toThrow();+ });++ it("parses an account with an optional AcctNum", () => {+ const account = Qbo.AccountSchema.parse({+ Id: "82",+ Name: "Inventory Asset",+ AccountType: "Other Current Asset",+ Classification: "Asset",+ Active: true+ });++ expect(account.AcctNum).toBeUndefined();+ });+});++describe("QBO fault parsing", () => {+ const duplicateNameFault = {+ Fault: {+ Error: [+ {+ Message: "Duplicate Name Exists Error",+ Detail:+ "The name supplied already exists. : Another customer, vendor or employee is already using this name.",+ code: "6240",+ element: "DisplayName"+ }+ ],+ type: "ValidationFault"+ },+ time: "2026-07-08T13:07:59.334-07:00"+ };++ it("extracts type, code, message and validation errors from a Fault body", () => {+ const details = extractQboErrorDetails(+ 400,+ "Bad Request",+ duplicateNameFault+ );++ expect(details.providerErrorType).toBe("ValidationFault");+ expect(details.providerErrorCode).toBe("6240");+ expect(details.providerMessage).toContain("already exists");+ expect(details.validationErrors).toEqual([+ {+ field: "DisplayName",+ message:+ "The name supplied already exists. : Another customer, vendor or employee is already using this name."+ }+ ]);+ });++ it("classifies duplicate-name and stale-object faults by Intuit code", () => {+ const duplicate = new AccountingApiError(+ "quickbooks",+ "create customer",+ extractQboErrorDetails(400, "Bad Request", duplicateNameFault)+ );+ expect(isQboDuplicateNameError(duplicate)).toBe(true);+ expect(isQboStaleObjectError(duplicate)).toBe(false);++ const stale = new AccountingApiError(+ "quickbooks",+ "update customer",+ extractQboErrorDetails(400, "Bad Request", {+ Fault: {+ Error: [+ {+ Message: "Stale Object Error",+ Detail: "Stale Object Error : You and another user...",+ code: QBO_FAULT_CODES.STALE_OBJECT+ }+ ],+ type: "ValidationFault"+ }+ })+ );+ expect(isQboStaleObjectError(stale)).toBe(true);+ expect(isQboDuplicateNameError(stale)).toBe(false);++ expect(isQboDuplicateNameError(new Error("boom"))).toBe(false);+ });+});++describe("QboProvider chart of accounts", () => {+ it("queries active accounts and normalizes to { id, code, name } with code = AcctNum ?? Id", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ QueryResponse: {+ Account: [+ {+ Id: "82",+ Name: "Inventory Asset",+ AcctNum: "1400",+ AccountType: "Other Current Asset",+ Active: true+ },+ {+ Id: "90",+ Name: "Accrued Liabilities",+ AccountType: "Other Current Liability",+ Active: true+ }+ ]+ }+ })+ );++ const { provider } = makeProvider();+ const accounts = await provider.listChartOfAccounts();++ expect(requestUrl(0)).toContain(+ "SELECT * FROM Account WHERE Active = true"+ );+ expect(accounts).toEqual([+ { id: "82", code: "1400", name: "Inventory Asset" },+ { id: "90", code: "90", name: "Accrued Liabilities" }+ ]);+ });++ it("returns [] instead of throwing when the query fails (Xero-parity contract)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ Fault: { type: "ValidationFault" } }, 400)+ );++ const { provider } = makeProvider();+ await expect(provider.listChartOfAccounts()).resolves.toEqual([]);+ });+});++describe("QboProvider entity reads/writes", () => {+ it("creates a customer via POST /customer and unwraps the envelope", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Customer: { Id: "42", SyncToken: "0", DisplayName: "Acme" }+ })+ );++ const { provider } = makeProvider();+ const created = await provider.createCustomer({+ DisplayName: "Acme",+ Active: true+ });++ expect(created.Id).toBe("42");+ expect(requestUrl(0)).toContain(`/v3/company/${REALM_ID}/customer`);+ const body = JSON.parse(String(requestInit(0)?.body));+ expect(body).toEqual({ DisplayName: "Acme", Active: true });+ });++ it("sends updates sparse with the echoed Id + SyncToken", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Customer: { Id: "42", SyncToken: "1", DisplayName: "Acme Ltd" }+ })+ );++ const { provider } = makeProvider();+ await provider.updateCustomer({+ Id: "42",+ SyncToken: "0",+ DisplayName: "Acme Ltd",+ Active: true+ });++ const body = JSON.parse(String(requestInit(0)?.body));+ expect(body).toEqual({+ Id: "42",+ SyncToken: "0",+ DisplayName: "Acme Ltd",+ Active: true,+ sparse: true+ });+ });++ it("throws a structured AccountingApiError carrying the Intuit fault code on write failure", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse(+ {+ Fault: {+ Error: [+ {+ Message: "Duplicate Name Exists Error",+ Detail: "The name supplied already exists.",+ code: "6240"+ }+ ],+ type: "ValidationFault"+ }+ },+ 400+ )+ );++ const { provider } = makeProvider();++ let thrown: unknown;+ try {+ await provider.createCustomer({ DisplayName: "Acme" });+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(AccountingApiError);+ expect(isQboDuplicateNameError(thrown)).toBe(true);+ });++ it("returns null from getCustomer when the read fails", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ Fault: { type: "ValidationFault" } }, 404)+ );++ const { provider } = makeProvider();+ await expect(provider.getCustomer("missing")).resolves.toBeNull();+ });+});++describe("listChanges (SupportsIncrementalPull)", () => {+ it("maps the CDC entity names onto Carbon entity types (Payment + BillPayment → payment)", () => {+ expect(QBO_CDC_ENTITY_TYPES).toEqual({+ Customer: "customer",+ Vendor: "vendor",+ Item: "item",+ Invoice: "invoice",+ Bill: "bill",+ PurchaseOrder: "purchaseOrder",+ Payment: "payment",+ BillPayment: "payment"+ });+ });++ it("declares the 29-day CDC lookback cap", () => {+ const { provider } = makeProvider();+ expect(provider.pullLookbackDays).toBe(29);+ });++ it("excludes Carbon-owned entities from the CDC sweep, ignoring provider-side changes to them", async () => {+ const { provider } = makeProvider();++ // QBO reports changes to a customer and an invoice — but Carbon owns those+ // (buildQboSyncConfig forces customer/vendor/item/invoice/bill push-only),+ // so the sweep must neither request nor ingest them.+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ CDCResponse: [+ {+ QueryResponse: [+ {+ Customer: [+ {+ Id: "63",+ MetaData: { LastUpdatedTime: "2026-07-08T13:07:59-07:00" }+ }+ ],+ Invoice: [{ Id: "7", status: "Deleted", MetaData: {} }]+ }+ ]+ }+ ]+ })+ );++ const result = await provider.listChanges({+ since: "2026-07-08T00:00:00.000Z"+ });++ // Only the accounting-owned payment entities are swept; the Carbon-owned+ // master/document entities are absent from the request…+ const cdcUrl = decodeURIComponent(fetchMock.mock.calls[0]?.[0] as string);+ expect(cdcUrl).toContain("entities=Payment,BillPayment");+ expect(cdcUrl).not.toContain("Customer");+ expect(cdcUrl).not.toContain("Invoice");++ // …and because they aren't requested, changeDataCapture ignores them:+ // provider-side edits to Carbon-owned records never flow back.+ expect(result.changes).toEqual([]);+ });++ it("still requests the forced-pull payment entities even when every stored entity is push-only", async () => {+ // buildQboSyncConfig forces `payment` to pull-from-accounting + enabled, so+ // even an all-push stored config keeps Payment/BillPayment in the CDC sweep.+ const pushOnlyConfig = structuredClone(DEFAULT_SYNC_CONFIG);+ for (const entityConfig of Object.values(pushOnlyConfig.entities)) {+ entityConfig.direction = "push-to-accounting";+ }+ const pushOnly = new QboProvider({+ companyId: "company-1",+ clientId: "client-id",+ clientSecret: "client-secret",+ accessToken: "token",+ refreshToken: "refresh",+ realmId: REALM_ID,+ syncConfig: pushOnlyConfig,+ onTokenRefresh: async () => undefined+ });++ // Empty CDC window → no changes, but the request is still made (and only+ // for the forced-pull payment entities).+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ CDCResponse: [{ QueryResponse: [] }],+ time: "2026-07-08T16:00:00-07:00"+ })+ );++ const result = await pushOnly.listChanges({+ since: "2026-07-08T00:00:00.000Z"+ });+ expect(result.changes).toEqual([]);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const cdcUrl = decodeURIComponent(String(fetchMock.mock.calls[0]?.[0]));+ expect(cdcUrl).toContain("entities=Payment,BillPayment");+ });+});++describe("buildQboSyncConfig — payment force-enable (two-way)", () => {+ it("force-enables `payment` as two-way even when the stored config disables it", () => {+ // DEFAULT_SYNC_CONFIG ships `payment` disabled — the provider must override+ // it so two-way payment sync (Phase G push + inbound pull) works as soon as the+ // integration connects.+ expect(DEFAULT_SYNC_CONFIG.entities.payment.enabled).toBe(false);++ const stored = structuredClone(DEFAULT_SYNC_CONFIG);+ stored.entities.payment = {+ enabled: false,+ direction: "two-way",+ owner: "carbon"+ };++ expect(buildQboSyncConfig(stored).entities.payment).toEqual({+ enabled: true,+ direction: "two-way",+ owner: "accounting"+ });+ });++ it("exposes the forced payment config through a constructed provider's getSyncConfig", () => {+ expect(makeProvider().provider.getSyncConfig("payment")).toEqual({+ enabled: true,+ direction: "two-way",+ owner: "accounting"+ });+ });+});++describe("buildQboSyncConfig — Carbon-owned master + documents", () => {+ it.each([+ "customer",+ "vendor",+ "item",+ "invoice",+ "bill"+ ] as const)("forces `%s` to push-only + owner carbon regardless of the stored config", (entityType) => {+ const stored = structuredClone(DEFAULT_SYNC_CONFIG);+ // Pretend the company had previously set this entity accounting-owned+ // two-way (the old Source of Truth default) — the force must override it.+ stored.entities[entityType] = {+ enabled: true,+ direction: "two-way",+ owner: "accounting"+ };++ expect(buildQboSyncConfig(stored).entities[entityType]).toEqual({+ enabled: true,+ direction: "push-to-accounting",+ owner: "carbon"+ });+ });++ it("preserves the per-company `enabled` flag while forcing ownership", () => {+ const stored = structuredClone(DEFAULT_SYNC_CONFIG);+ stored.entities.bill = {+ enabled: false,+ direction: "two-way",+ owner: "accounting"+ };++ expect(buildQboSyncConfig(stored).entities.bill).toEqual({+ enabled: false,+ direction: "push-to-accounting",+ owner: "carbon"+ });+ });++ it("leaves payment accounting-owned and does not touch unforced entities", () => {+ const applied = buildQboSyncConfig(structuredClone(DEFAULT_SYNC_CONFIG));+ // payment stays the accounting-owned pull-only exception+ expect(applied.entities.payment.owner).toBe("accounting");+ // purchaseOrder is neither Carbon-owned-forced nor payment — passes through+ expect(applied.entities.purchaseOrder).toEqual(+ DEFAULT_SYNC_CONFIG.entities.purchaseOrder+ );+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.tsnew file mode 100644index 0000000000..f90e310033--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/bill.test.ts@@ -0,0 +1,399 @@+import { describe, expect, it } from "vitest";+import type { CostingLine } from "../../../../core/document-costing";+import { JournalEntrySyncError } from "../../../../core/posting";+import type { Accounting } from "../../../../core/types";+import type { Qbo } from "../../models";+import {+ buildQboBillLines,+ deriveCarbonBillStatus,+ QboBillSyncer+} from "../bill";+import { buildQboExpenseLines, type QboExpenseLineInput } from "../shared";++const ACCOUNT_REFS: ReadonlyMap<string, Qbo.Ref> = new Map([+ ["acc-freight", { value: "91", name: "Freight & Delivery" }]+]);++const itemLine: QboExpenseLineInput = {+ itemId: "item-1",+ accountId: null,+ description: "Widget Bracket",+ quantity: 10,+ unitPrice: 4.255,+ totalAmount: 42.555+};++const accountLine: QboExpenseLineInput = {+ itemId: null,+ accountId: "acc-freight",+ description: "Inbound freight",+ quantity: 1,+ unitPrice: 25,+ totalAmount: 25+};++describe("buildQboExpenseLines (bill mapping fixture)", () => {+ it("maps item lines to ItemBasedExpenseLineDetail and account lines to AccountBasedExpenseLineDetail", () => {+ const lines = buildQboExpenseLines({+ lines: [itemLine, accountLine],+ itemRemoteIds: new Map([["item-1", "77"]]),+ accountRefsById: ACCOUNT_REFS,+ documentLabel: "bill PI-000042"+ });++ expect(lines).toEqual([+ {+ Description: "Widget Bracket",+ Amount: 42.56,+ DetailType: "ItemBasedExpenseLineDetail",+ ItemBasedExpenseLineDetail: {+ ItemRef: { value: "77" },+ Qty: 10,+ UnitPrice: 4.255+ }+ },+ {+ Description: "Inbound freight",+ Amount: 25,+ DetailType: "AccountBasedExpenseLineDetail",+ AccountBasedExpenseLineDetail: {+ AccountRef: { value: "91", name: "Freight & Delivery" }+ }+ }+ ]);+ });++ it("throws a plain error (Failed, not Warning) for a non-item line with an unmapped account", () => {+ expect(() =>+ buildQboExpenseLines({+ lines: [accountLine],+ itemRemoteIds: new Map(),+ accountRefsById: new Map(),+ documentLabel: "bill PI-000042"+ })+ ).toThrow(/account acc-freight has no QuickBooks Online account mapping/);+ });++ it("throws for a line with neither an item nor an account", () => {+ expect(() =>+ buildQboExpenseLines({+ lines: [{ ...accountLine, accountId: null }],+ itemRemoteIds: new Map(),+ accountRefsById: ACCOUNT_REFS,+ documentLabel: "bill PI-000042"+ })+ ).toThrow(/neither an item nor a G\/L account/);+ });++ it("throws for an item line whose item was not synced first", () => {+ expect(() =>+ buildQboExpenseLines({+ lines: [itemLine],+ itemRemoteIds: new Map(),+ accountRefsById: ACCOUNT_REFS,+ documentLabel: "bill PI-000042"+ })+ ).toThrow(/item item-1 has not been synced/);+ });+});++const BILL_ACCOUNT_REFS: ReadonlyMap<string, Qbo.Ref> = new Map([+ ["acc-grir", { value: "2125", name: "GR/IR Clearing" }],+ ["acc-ppv", { value: "5210", name: "Purchase Price Variance" }]+]);++const billFixture = (+ overrides: Partial<Accounting.Bill> = {}+): Accounting.Bill =>+ ({+ id: "pi_1",+ companyId: "company-1",+ invoiceId: "AP000001",+ supplierId: "sup_1",+ supplierExternalId: "vendor-99",+ status: "Pending",+ dateIssued: "2026-08-04",+ dateDue: null,+ datePaid: null,+ currencyCode: "USD",+ exchangeRate: 1,+ subtotal: 300,+ totalTax: 0,+ totalDiscount: 0,+ totalAmount: 300,+ balance: 300,+ supplierReference: null,+ lines: [],+ updatedAt: "2026-08-04T00:00:00.000Z",+ ...overrides+ }) as unknown as Accounting.Bill;++describe("buildQboBillLines (account-costed journal replay)", () => {+ it("emits AccountBasedExpenseLineDetail to the journal accounts, item label as Description, no item detail, no tax", () => {+ const costingLines: CostingLine[] = [+ {+ id: "jl-1",+ accountId: "acc-grir",+ amount: 300,+ description: "GR/IR Clearing",+ sourceItem: { id: "item-1", code: "WIDGET-1", name: "Widget" }+ },+ {+ id: "jl-2",+ accountId: "acc-ppv",+ amount: 20,+ description: "Purchase Price Variance"+ }+ ];++ const lines = buildQboBillLines({+ bill: billFixture(),+ costingLines,+ accountRefsById: BILL_ACCOUNT_REFS+ });++ expect(lines).toEqual([+ {+ Amount: 300,+ Description: "WIDGET-1 Widget",+ DetailType: "AccountBasedExpenseLineDetail",+ AccountBasedExpenseLineDetail: {+ AccountRef: { value: "2125", name: "GR/IR Clearing" }+ }+ },+ {+ Amount: 20,+ Description: "Purchase Price Variance",+ DetailType: "AccountBasedExpenseLineDetail",+ AccountBasedExpenseLineDetail: {+ AccountRef: { value: "5210", name: "Purchase Price Variance" }+ }+ }+ ]);+ // No item-based detail leaks onto a bill line.+ expect(lines.every((l) => !("ItemBasedExpenseLineDetail" in l))).toBe(true);+ });++ it("survives a negative (credit PPV) costing line", () => {+ const lines = buildQboBillLines({+ bill: billFixture(),+ costingLines: [+ {+ id: "jl-1",+ accountId: "acc-grir",+ amount: 300,+ description: "GR/IR"+ },+ {+ id: "jl-2",+ accountId: "acc-ppv",+ amount: -20,+ description: "PPV credit"+ }+ ],+ accountRefsById: BILL_ACCOUNT_REFS+ });+ expect(lines[1]?.Amount).toBe(-20);+ });++ it("warns (UNMAPPED_ACCOUNTS, retryable) on an unmapped account", () => {+ try {+ buildQboBillLines({+ bill: billFixture(),+ costingLines: [+ {+ id: "jl-1",+ accountId: "acc-grir",+ amount: 300,+ description: "GR/IR"+ }+ ],+ accountRefsById: new Map()+ });+ expect.unreachable("should have thrown");+ } catch (error) {+ const failure = (error as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(failure.warning).toBe(true);+ expect(failure.metadata?.unmappedAccountIds).toEqual(["acc-grir"]);+ }+ });++ it("warns when the bill has no posted journal", () => {+ expect(() =>+ buildQboBillLines({+ bill: billFixture(),+ costingLines: [],+ accountRefsById: BILL_ACCOUNT_REFS+ })+ ).toThrowError(JournalEntrySyncError);+ });+});++// Table-dispatching Kysely fake for the mapToRemote FX drive.+function makeBillDb(config: {+ purchaseInvoice: { currencyCode: string; exchangeRate: number };+ journalLine: Array<{+ id: string;+ accountId: string | null;+ amount: number;+ description: string | null;+ documentLineReference: string | null;+ accountClass: string | null;+ }>;+ accountDefault: { payablesAccount: string | null };+ accountMappings: Array<{+ id: string;+ accountId: string;+ externalId: string | null;+ metadata: unknown;+ lastSyncedAt: string | null;+ accountNumber: string | null;+ accountName: string | null;+ }>;+}) {+ const makeBuilder = (table: string) => {+ const builder: any = {+ select: () => builder,+ innerJoin: () => builder,+ leftJoin: () => builder,+ where: () => builder,+ orderBy: () => builder,+ async execute() {+ if (table === "journalLine") return config.journalLine;+ if (table === "journalLineDimension") return [];+ if (table === "purchaseOrderLine") return [];+ if (table === "externalIntegrationMapping as m")+ return config.accountMappings.map((m) => ({+ id: m.id,+ accountId: m.accountId,+ externalId: m.externalId,+ metadata: m.metadata,+ lastSyncedAt: m.lastSyncedAt,+ accountNumber: m.accountNumber,+ accountName: m.accountName+ }));+ return [];+ },+ async executeTakeFirst() {+ if (table === "purchaseInvoice") return config.purchaseInvoice;+ if (table === "accountDefault") return config.accountDefault;+ return undefined;+ }+ };+ return builder;+ };+ return { selectFrom: (t: string) => makeBuilder(t) } as never;+}++describe("QboBillSyncer.mapToRemote (FX currency wiring)", () => {+ it("pins CurrencyRef + ExchangeRate and replays transaction-currency amounts", async () => {+ const syncer = new QboBillSyncer({+ database: makeBillDb({+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 2 },+ journalLine: [+ {+ id: "jl-1",+ accountId: "acc-grir",+ amount: 300,+ description: "GR/IR Clearing",+ documentLineReference: null,+ accountClass: "Asset"+ },+ {+ id: "jl-2",+ accountId: "acc-ap",+ amount: 300, // Liability natural balance → debit-signed -300+ description: "Accounts Payable",+ documentLineReference: null,+ accountClass: "Liability"+ }+ ],+ accountDefault: { payablesAccount: "acc-ap" },+ accountMappings: [+ {+ id: "m-1",+ accountId: "acc-grir",+ externalId: "2125",+ metadata: null,+ lastSyncedAt: null,+ accountNumber: "2125",+ accountName: "GR/IR Clearing"+ }+ ]+ }),+ companyId: "company-1",+ provider: { id: "quickbooks" } as never,+ config: { enabled: true, direction: "two-way", owner: "accounting" },+ entityType: "bill"+ });++ const payload = await (+ syncer as unknown as {+ mapToRemote(local: Accounting.Bill): Promise<Qbo.Bill>;+ }+ ).mapToRemote(billFixture({ currencyCode: "EUR", exchangeRate: 2 }));++ expect(payload.CurrencyRef).toEqual({ value: "EUR" });+ expect(payload.ExchangeRate).toBe(2);+ // Base 300 @ rate 2 → 150 EUR to the mapped GR/IR account only (AP excluded).+ expect(payload.Line).toEqual([+ {+ Amount: 150,+ Description: "GR/IR Clearing",+ DetailType: "AccountBasedExpenseLineDetail",+ AccountBasedExpenseLineDetail: { AccountRef: { value: "2125" } }+ }+ ]);+ });+});++describe("deriveCarbonBillStatus (pull status from Balance/TotalAmt/DueDate)", () => {+ const now = new Date("2026-07-09T00:00:00.000Z");++ it("derives Paid / Partially Paid / Overdue / Open", () => {+ expect(+ deriveCarbonBillStatus({+ totalAmt: 100,+ balance: 0,+ dueDate: "2026-07-01",+ now+ })+ ).toBe("Paid");+ expect(+ deriveCarbonBillStatus({+ totalAmt: 100,+ balance: 40,+ dueDate: "2026-08-01",+ now+ })+ ).toBe("Partially Paid");+ expect(+ deriveCarbonBillStatus({+ totalAmt: 100,+ balance: 100,+ dueDate: "2026-07-01",+ now+ })+ ).toBe("Overdue");+ expect(+ deriveCarbonBillStatus({+ totalAmt: 100,+ balance: 100,+ dueDate: "2026-08-01",+ now+ })+ ).toBe("Open");+ });++ it("returns undefined when QBO reports no balance", () => {+ expect(+ deriveCarbonBillStatus({+ totalAmt: 100,+ balance: undefined,+ dueDate: undefined,+ now+ })+ ).toBeUndefined();+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/customer.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/customer.test.tsnew file mode 100644index 0000000000..730634abf6--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/customer.test.ts@@ -0,0 +1,478 @@+import { describe, expect, it, vi } from "vitest";+import {+ isJournalEntrySyncFailure,+ JournalEntrySyncError+} from "../../../../core/posting";+import type { Accounting, SyncContext } from "../../../../core/types";+import { AccountingApiError } from "../../../../core/utils";+import type { Qbo } from "../../models";+import { extractQboErrorDetails, QBO_FAULT_CODES } from "../../provider";+import {+ mapContactToQboContact,+ mapQboContactToLocal,+ QBO_NAME_MAX_LENGTH,+ QboEntitySyncer,+ type QboWriteOmit,+ toQboNameExistsError,+ updateWithSyncTokenRetry+} from "../shared";++const makeContact = (+ overrides?: Partial<Accounting.Contact>+): Accounting.Contact => ({+ id: "cust-1",+ name: "Acme Manufacturing",+ firstName: "Jane",+ lastName: "Doe",+ companyId: "company-1",+ email: "[email protected]",+ website: null,+ taxId: null,+ currencyCode: "USD",+ balance: null,+ creditLimit: null,+ paymentTerms: null,+ updatedAt: "2026-07-01T12:00:00.000Z",+ workPhone: "555-0100",+ mobilePhone: "555-0101",+ fax: null,+ homePhone: null,+ isVendor: false,+ isCustomer: true,+ addresses: [+ {+ label: "HQ",+ type: null,+ line1: "1 Factory Way",+ line2: "Suite 2",+ city: "Cleveland",+ country: "US",+ region: "OH",+ postalCode: "44101"+ }+ ],+ raw: {},+ ...overrides+});++function makeQboFaultError(code: string, message: string): AccountingApiError {+ const details = extractQboErrorDetails(400, "Bad Request", {+ Fault: {+ Error: [{ Message: message, Detail: `${message}.`, code, element: "" }],+ type: "ValidationFault"+ }+ });+ return new AccountingApiError("quickbooks", "create customer", details);+}++describe("mapContactToQboContact (to-remote fixture)", () => {+ it("maps name, email, phone and billing address onto the QBO payload", () => {+ const payload = mapContactToQboContact(makeContact(), "customer");++ expect(payload).toEqual({+ DisplayName: "Acme Manufacturing",+ PrimaryEmailAddr: { Address: "[email protected]" },+ PrimaryPhone: { FreeFormNumber: "555-0100" },+ BillAddr: {+ Line1: "1 Factory Way",+ Line2: "Suite 2",+ City: "Cleveland",+ CountrySubDivisionCode: "OH",+ Country: "US",+ PostalCode: "44101"+ },+ Active: true+ });+ });++ it("omits optional fields when the contact has no email/phone/address (vendor case)", () => {+ const payload = mapContactToQboContact(+ makeContact({+ email: undefined,+ workPhone: null,+ mobilePhone: null,+ homePhone: null,+ addresses: [],+ isCustomer: false,+ isVendor: true+ }),+ "vendor"+ );++ expect(payload.DisplayName).toBe("Acme Manufacturing");+ expect(payload.PrimaryEmailAddr).toBeUndefined();+ expect(payload.PrimaryPhone).toBeUndefined();+ expect(payload.BillAddr).toBeUndefined();+ });++ it("falls back through workPhone → mobilePhone → homePhone for PrimaryPhone", () => {+ const payload = mapContactToQboContact(+ makeContact({ workPhone: null }),+ "customer"+ );+ expect(payload.PrimaryPhone).toEqual({ FreeFormNumber: "555-0101" });+ });++ it("throws the structured NAME_TOO_LONG Warning past 100 characters — no silent truncation", () => {+ const longName = "x".repeat(QBO_NAME_MAX_LENGTH + 1);++ let thrown: unknown;+ try {+ mapContactToQboContact(makeContact({ name: longName }), "customer");+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(JournalEntrySyncError);+ const failure = (thrown as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("NAME_TOO_LONG");+ expect(failure.warning).toBe(true);+ expect(failure.metadata?.maxLength).toBe(100);+ expect(isJournalEntrySyncFailure(failure)).toBe(true);+ });++ it("allows exactly 100 characters", () => {+ const name = "x".repeat(QBO_NAME_MAX_LENGTH);+ expect(+ mapContactToQboContact(makeContact({ name }), "customer").DisplayName+ ).toBe(name);+ });+});++describe("mapQboContactToLocal (to-local fixture)", () => {+ const remote: Qbo.Customer = {+ Id: "42",+ SyncToken: "3",+ DisplayName: "Acme Manufacturing",+ PrimaryEmailAddr: { Address: "[email protected]" },+ PrimaryPhone: { FreeFormNumber: "555-0100" },+ BillAddr: {+ Line1: "1 Factory Way",+ City: "Cleveland",+ CountrySubDivisionCode: "OH",+ Country: "US",+ PostalCode: "44101"+ },+ Active: true,+ MetaData: { LastUpdatedTime: "2026-07-01T13:07:59-07:00" }+ };++ it("maps DisplayName/email/phone/BillAddr back with customer flags", () => {+ const local = mapQboContactToLocal(remote, {+ isCustomer: true,+ isVendor: false+ });++ expect(local.name).toBe("Acme Manufacturing");+ expect(local.email).toBe("[email protected]");+ expect(local.workPhone).toBe("555-0100");+ expect(local.isCustomer).toBe(true);+ expect(local.isVendor).toBe(false);+ expect(local.addresses).toEqual([+ {+ label: null,+ type: "BILLING",+ line1: "1 Factory Way",+ line2: null,+ city: "Cleveland",+ region: "OH",+ country: "US",+ postalCode: "44101"+ }+ ]);+ });++ it("sets vendor flags for the vendor syncer and handles a bare contact", () => {+ const local = mapQboContactToLocal(+ { Id: "9", SyncToken: "0", DisplayName: "Bare Vendor" },+ { isCustomer: false, isVendor: true }+ );++ expect(local.name).toBe("Bare Vendor");+ expect(local.isVendor).toBe(true);+ expect(local.isCustomer).toBe(false);+ expect(local.email).toBeUndefined();+ expect(local.workPhone).toBeNull();+ expect(local.addresses).toEqual([]);+ });+});++describe("toQboNameExistsError (Duplicate Name Exists → NAME_EXISTS Warning)", () => {+ it("converts an Intuit 6240 fault into the structured NAME_EXISTS Warning envelope", () => {+ const fault = makeQboFaultError(+ QBO_FAULT_CODES.DUPLICATE_NAME_EXISTS,+ "Duplicate Name Exists Error"+ );++ const converted = toQboNameExistsError(fault, {+ entityLabel: "customer",+ name: "Acme Manufacturing"+ });++ expect(converted).toBeInstanceOf(JournalEntrySyncError);+ expect(converted?.failure.errorCode).toBe("NAME_EXISTS");+ expect(converted?.failure.warning).toBe(true);+ expect(converted?.failure.metadata?.name).toBe("Acme Manufacturing");+ // The drain detects this envelope generically+ expect(isJournalEntrySyncFailure(converted?.failure)).toBe(true);+ // String-flattening paths stay greppable+ expect(converted?.message).toMatch(/^NAME_EXISTS: /);+ });++ it("returns null for any other fault or error", () => {+ expect(+ toQboNameExistsError(makeQboFaultError("5010", "Stale Object Error"), {+ entityLabel: "customer",+ name: "Acme"+ })+ ).toBeNull();+ expect(+ toQboNameExistsError(new Error("boom"), {+ entityLabel: "customer",+ name: "Acme"+ })+ ).toBeNull();+ });+});++describe("updateWithSyncTokenRetry (stale SyncToken → ONE refetch-and-retry)", () => {+ it("updates with the freshly fetched token on the happy path", async () => {+ const fetchCurrent = vi.fn(async () => ({ SyncToken: "4" }));+ const update = vi.fn(async (syncToken: string) => ({+ Id: "42",+ syncToken+ }));++ const result = await updateWithSyncTokenRetry({+ entityLabel: "customer",+ remoteId: "42",+ fetchCurrent,+ update+ });++ expect(result).toEqual({ Id: "42", syncToken: "4" });+ expect(fetchCurrent).toHaveBeenCalledTimes(1);+ expect(update).toHaveBeenCalledTimes(1);+ expect(update).toHaveBeenCalledWith("4");+ });++ it("refetches and retries exactly once on a stale-token fault (5010)", async () => {+ const tokens = ["1", "2"];+ const fetchCurrent = vi.fn(async () => ({ SyncToken: tokens.shift()! }));+ const update = vi+ .fn<(syncToken: string) => Promise<{ Id: string }>>()+ .mockRejectedValueOnce(+ makeQboFaultError(QBO_FAULT_CODES.STALE_OBJECT, "Stale Object Error")+ )+ .mockResolvedValueOnce({ Id: "42" });++ const result = await updateWithSyncTokenRetry({+ entityLabel: "customer",+ remoteId: "42",+ fetchCurrent,+ update+ });++ expect(result).toEqual({ Id: "42" });+ expect(fetchCurrent).toHaveBeenCalledTimes(2);+ expect(update).toHaveBeenNthCalledWith(1, "1");+ expect(update).toHaveBeenNthCalledWith(2, "2");+ });++ it("propagates a second stale-token fault instead of retrying again", async () => {+ const staleError = makeQboFaultError(+ QBO_FAULT_CODES.STALE_OBJECT,+ "Stale Object Error"+ );+ const fetchCurrent = vi.fn(async () => ({ SyncToken: "1" }));+ const update = vi.fn(async () => {+ throw staleError;+ });++ await expect(+ updateWithSyncTokenRetry({+ entityLabel: "customer",+ remoteId: "42",+ fetchCurrent,+ update+ })+ ).rejects.toBe(staleError);++ expect(update).toHaveBeenCalledTimes(2);+ });++ it("does not retry non-stale errors", async () => {+ const fault = makeQboFaultError(+ QBO_FAULT_CODES.DUPLICATE_NAME_EXISTS,+ "Duplicate Name Exists Error"+ );+ const fetchCurrent = vi.fn(async () => ({ SyncToken: "1" }));+ const update = vi.fn(async () => {+ throw fault;+ });++ await expect(+ updateWithSyncTokenRetry({+ entityLabel: "customer",+ remoteId: "42",+ fetchCurrent,+ update+ })+ ).rejects.toBe(fault);++ expect(fetchCurrent).toHaveBeenCalledTimes(1);+ expect(update).toHaveBeenCalledTimes(1);+ });+});++// =====================================================================+// Structured-failure survival through the push workflow: the base+// workflow flattens throws to strings; QboEntitySyncer must return the+// JournalEntrySyncFailure object on SyncResult.error instead.+// =====================================================================++type PushBehavior = {+ upsertError?: unknown;+ existingMapping?: { externalId: string; lastSyncedAt: string } | null;+};++class TestContactSyncer extends QboEntitySyncer<+ Accounting.Contact,+ Qbo.Customer+> {+ constructor(+ context: SyncContext,+ private behavior: PushBehavior+ ) {+ super(context);+ // The mapping service is backed by the (fake) database — stub the one+ // read the push workflow performs.+ (this as any).mappingService = {+ getByEntity: async () => this.behavior.existingMapping ?? null+ };+ }++ async fetchLocal(): Promise<Accounting.Contact | null> {+ return makeContact();+ }++ protected async fetchLocalBatch(): Promise<Map<string, Accounting.Contact>> {+ return new Map([["cust-1", makeContact()]]);+ }++ async fetchRemote(): Promise<Qbo.Customer | null> {+ return null;+ }++ protected async fetchRemoteBatch(): Promise<Map<string, Qbo.Customer>> {+ return new Map();+ }++ protected async mapToRemote(+ local: Accounting.Contact+ ): Promise<Omit<Qbo.Customer, QboWriteOmit>> {+ return mapContactToQboContact(local, "customer");+ }++ protected async mapToLocal(): Promise<Partial<Accounting.Contact>> {+ return {};+ }++ protected async upsertLocal(): Promise<string> {+ return "cust-1";+ }++ protected async upsertRemote(): Promise<string> {+ if (this.behavior.upsertError) throw this.behavior.upsertError;+ return "42";+ }+}++function makeSyncer(behavior: PushBehavior): TestContactSyncer {+ const context: SyncContext = {+ database: {} as SyncContext["database"],+ companyId: "company-1",+ provider: { id: "quickbooks" } as SyncContext["provider"],+ config: { enabled: true, direction: "two-way", owner: "accounting" },+ entityType: "customer"+ };+ return new TestContactSyncer(context, behavior);+}++describe("QboEntitySyncer push workflow (structured failures survive)", () => {+ it("returns the NAME_EXISTS envelope on SyncResult.error, not a flattened string", async () => {+ const fault = makeQboFaultError(+ QBO_FAULT_CODES.DUPLICATE_NAME_EXISTS,+ "Duplicate Name Exists Error"+ );+ const structured = toQboNameExistsError(fault, {+ entityLabel: "customer",+ name: "Acme Manufacturing"+ });++ const syncer = makeSyncer({ upsertError: structured });+ const result = await syncer.pushToAccounting("cust-1");++ expect(result.status).toBe("error");+ expect(typeof result.error).toBe("object");+ expect(isJournalEntrySyncFailure(result.error)).toBe(true);+ expect((result.error as { errorCode: string }).errorCode).toBe(+ "NAME_EXISTS"+ );+ expect((result.error as { warning: boolean }).warning).toBe(true);+ });++ it("returns the NAME_TOO_LONG envelope thrown from the mapping step", async () => {+ const syncer = makeSyncer({});+ (syncer as any).fetchLocal = async () =>+ makeContact({ name: "x".repeat(101) });++ const result = await syncer.pushToAccounting("cust-1");++ expect(result.status).toBe("error");+ expect(isJournalEntrySyncFailure(result.error)).toBe(true);+ expect((result.error as { errorCode: string }).errorCode).toBe(+ "NAME_TOO_LONG"+ );+ });++ it("keeps the base flattened-string behavior for plain errors", async () => {+ const syncer = makeSyncer({ upsertError: new Error("boom") });+ const result = await syncer.pushToAccounting("cust-1");++ expect(result.status).toBe("error");+ expect(result.error).toBe("boom");+ });++ it("keeps the base fast bailout: mapped + unchanged local skips", async () => {+ const syncer = makeSyncer({+ existingMapping: {+ externalId: "42",+ lastSyncedAt: "2026-07-02T00:00:00.000Z" // after the fixture's updatedAt+ }+ });++ const result = await syncer.pushToAccounting("cust-1");++ expect(result.status).toBe("skipped");+ expect(result.remoteId).toBe("42");+ expect(result.error).toBe("Already synced - local unchanged");+ });++ it("preserves the envelope through the batch path (drain uses pushBatchToAccounting)", async () => {+ const fault = makeQboFaultError(+ QBO_FAULT_CODES.DUPLICATE_NAME_EXISTS,+ "Duplicate Name Exists Error"+ );+ const structured = toQboNameExistsError(fault, {+ entityLabel: "customer",+ name: "Acme Manufacturing"+ });++ const syncer = makeSyncer({ upsertError: structured });+ const batch = await syncer.pushBatchToAccounting(["cust-1"]);++ expect(batch.errorCount).toBe(1);+ expect(isJournalEntrySyncFailure(batch.results[0]?.error)).toBe(true);+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.tsnew file mode 100644index 0000000000..d46e827c38--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/invoice.test.ts@@ -0,0 +1,104 @@+import { describe, expect, it } from "vitest";+import type { Accounting } from "../../../../core/types";+import { buildQboInvoiceLines, deriveCarbonInvoiceStatus } from "../invoice";+import { buildQboDocNumberFields, QBO_DOC_NUMBER_MAX_LENGTH } from "../shared";++const makeLine = (+ overrides?: Partial<Accounting.SalesInvoiceLine>+): Accounting.SalesInvoiceLine => ({+ id: "line-1",+ invoiceLineType: "Part",+ itemId: "item-1",+ itemCode: "PART-000123",+ description: "Widget Bracket",+ quantity: 3,+ unitPrice: 19.999,+ taxPercent: 0,+ lineAmount: 59.997,+ ...overrides+});++describe("buildQboInvoiceLines (invoice mapping fixture)", () => {+ it("builds SalesItemLineDetail lines with ItemRef + Qty/UnitPrice and a rounded Amount", () => {+ const lines = buildQboInvoiceLines(+ [makeLine()],+ new Map([["item-1", "77"]])+ );++ expect(lines).toEqual([+ {+ Description: "Widget Bracket",+ Amount: 60,+ DetailType: "SalesItemLineDetail",+ SalesItemLineDetail: {+ ItemRef: { value: "77" },+ Qty: 3,+ UnitPrice: 19.999+ }+ }+ ]);+ });++ it("ships lines without an item without an ItemRef", () => {+ const lines = buildQboInvoiceLines(+ [+ makeLine({+ itemId: null,+ itemCode: null,+ description: "Expedite fee",+ quantity: 1,+ unitPrice: 50+ })+ ],+ new Map()+ );++ expect(lines[0]?.SalesItemLineDetail?.ItemRef).toBeUndefined();+ expect(lines[0]?.Amount).toBe(50);+ });+});++describe("buildQboDocNumberFields (21-char DocNumber cap)", () => {+ it("uses DocNumber when the readable id fits (boundary: exactly 21 chars)", () => {+ const id = "I".repeat(QBO_DOC_NUMBER_MAX_LENGTH);+ expect(buildQboDocNumberFields(id)).toEqual({+ DocNumber: id,+ PrivateNote: undefined,+ source: "docNumber"+ });+ });++ it("moves a longer id to PrivateNote and lets QBO auto-number", () => {+ const id = "INV-000000000000000042"; // 22 chars+ expect(id.length).toBe(QBO_DOC_NUMBER_MAX_LENGTH + 1);++ const fields = buildQboDocNumberFields(id);+ expect(fields.DocNumber).toBeUndefined();+ expect(fields.PrivateNote).toBe(`Carbon ${id}`);+ expect(fields.source).toBe("privateNote");+ });++ it("joins an extra note onto the PrivateNote carrier", () => {+ const id = "I".repeat(QBO_DOC_NUMBER_MAX_LENGTH + 1);+ expect(buildQboDocNumberFields(id, "Ref PO-9").PrivateNote).toBe(+ `Carbon ${id} | Ref PO-9`+ );+ expect(buildQboDocNumberFields("INV-42", "Ref PO-9")).toEqual({+ DocNumber: "INV-42",+ PrivateNote: "Ref PO-9",+ source: "docNumber"+ });+ });+});++describe("deriveCarbonInvoiceStatus (pull status from Balance/TotalAmt)", () => {+ it("derives Paid / Partially Paid / Submitted from the balance", () => {+ expect(deriveCarbonInvoiceStatus(100, 0)).toBe("Paid");+ expect(deriveCarbonInvoiceStatus(100, 40)).toBe("Partially Paid");+ expect(deriveCarbonInvoiceStatus(100, 100)).toBe("Submitted");+ });++ it("returns undefined when QBO reports no balance", () => {+ expect(deriveCarbonInvoiceStatus(100, undefined)).toBeUndefined();+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/item.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/item.test.tsnew file mode 100644index 0000000000..a5e17096e6--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/item.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it } from "vitest";+import {+ isJournalEntrySyncFailure,+ JournalEntrySyncError+} from "../../../../core/posting";+import type { Accounting } from "../../../../core/types";+import type { Qbo } from "../../models";+import { mapItemToQboItem } from "../item";++const makeItem = (overrides?: Partial<Accounting.Item>): Accounting.Item => ({+ id: "item-1",+ code: "PART-000123",+ name: "Widget Bracket",+ description: "Steel bracket for widgets",+ companyId: "company-1",+ type: "Part",+ unitOfMeasureCode: "EA",+ unitCost: 4.25,+ unitSalePrice: 9.99,+ isPurchased: true,+ isSold: true,+ isTrackedAsInventory: true,+ updatedAt: "2026-07-01T12:00:00.000Z",+ raw: {},+ ...overrides+});++const ACCOUNT_REFS: ReadonlyMap<string, Qbo.Ref> = new Map([+ ["acc-sales", { value: "79", name: "Sales of Product Income" }],+ ["acc-cogs", { value: "80", name: "Cost of Goods Sold" }]+]);++const passingArgs = () => ({+ item: makeItem(),+ accountRefsById: ACCOUNT_REFS,+ incomeAccountId: "acc-sales" as string | null,+ expenseAccountId: "acc-cogs" as string | null+});++describe("mapItemToQboItem (mapping fixture with account resolution)", () => {+ it("maps a purchased physical item to NonInventory with both account refs", () => {+ const payload = mapItemToQboItem(passingArgs());++ expect(payload).toEqual({+ Name: "PART-000123",+ Description: "Steel bracket for widgets",+ Type: "NonInventory",+ Active: true,+ UnitPrice: 9.99,+ PurchaseCost: 4.25,+ IncomeAccountRef: { value: "79", name: "Sales of Product Income" },+ ExpenseAccountRef: { value: "80", name: "Cost of Goods Sold" }+ });+ });++ it("maps Carbon Service items to QBO Type Service", () => {+ const payload = mapItemToQboItem({+ ...passingArgs(),+ item: makeItem({ type: "Service", isPurchased: false })+ });++ expect(payload.Type).toBe("Service");+ expect(payload.ExpenseAccountRef).toBeUndefined();+ });++ it("never produces Type Inventory for any Carbon item type (double-COGS guard)", () => {+ const types: Accounting.Item["type"][] = [+ "Part",+ "Material",+ "Tool",+ "Service",+ "Consumable",+ "Fixture"+ ];++ for (const type of types) {+ const payload = mapItemToQboItem({+ ...passingArgs(),+ item: makeItem({ type })+ });+ expect(["Service", "NonInventory"]).toContain(payload.Type);+ }+ });++ it("omits ExpenseAccountRef (and skips its mapping requirement) for non-purchased items", () => {+ const payload = mapItemToQboItem({+ ...passingArgs(),+ item: makeItem({ isPurchased: false }),+ expenseAccountId: null+ });++ expect(payload.ExpenseAccountRef).toBeUndefined();+ expect(payload.IncomeAccountRef).toEqual({+ value: "79",+ name: "Sales of Product Income"+ });+ });++ it("falls back to the item name when there is no description", () => {+ const payload = mapItemToQboItem({+ ...passingArgs(),+ item: makeItem({ description: null })+ });++ expect(payload.Description).toBe("Widget Bracket");+ });++ it("throws the structured UNMAPPED_ACCOUNTS Warning when a required account has no mapping", () => {+ let thrown: unknown;+ try {+ mapItemToQboItem({+ ...passingArgs(),+ accountRefsById: new Map([+ ["acc-cogs", { value: "80" } satisfies Qbo.Ref]+ ])+ });+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(JournalEntrySyncError);+ const failure = (thrown as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(failure.warning).toBe(true);+ expect(failure.metadata?.unmappedAccountIds).toEqual(["acc-sales"]);+ expect(isJournalEntrySyncFailure(failure)).toBe(true);+ });++ it("collects both unmapped accounts when neither default is mapped", () => {+ let thrown: unknown;+ try {+ mapItemToQboItem({ ...passingArgs(), accountRefsById: new Map() });+ } catch (error) {+ thrown = error;+ }++ const failure = (thrown as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(failure.metadata?.unmappedAccountIds).toEqual([+ "acc-sales",+ "acc-cogs"+ ]);+ });++ it("reports missing accountDefault columns as UNMAPPED_ACCOUNTS with missingDefaults metadata", () => {+ let thrown: unknown;+ try {+ mapItemToQboItem({+ ...passingArgs(),+ incomeAccountId: null,+ expenseAccountId: null+ });+ } catch (error) {+ thrown = error;+ }++ const failure = (thrown as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(failure.metadata?.missingDefaults).toEqual([+ "salesAccount",+ "costOfGoodsSoldAccount"+ ]);+ });++ it("throws the structured NAME_TOO_LONG Warning past QBO's 100-char Name cap", () => {+ let thrown: unknown;+ try {+ mapItemToQboItem({+ ...passingArgs(),+ item: makeItem({ code: "P".repeat(101) })+ });+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(JournalEntrySyncError);+ const failure = (thrown as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("NAME_TOO_LONG");+ expect(failure.warning).toBe(true);+ expect(isJournalEntrySyncFailure(failure)).toBe(true);+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/journal-entry.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/journal-entry.test.tsnew file mode 100644index 0000000000..c0665ebf6a--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/journal-entry.test.ts@@ -0,0 +1,512 @@+import { describe, expect, it } from "vitest";+import {+ DEFAULT_POSTING_SYNC_SETTINGS,+ isJournalEntrySyncFailure,+ JournalEntrySyncError,+ type PostingSyncSettings,+ runJournalEntryPreflight+} from "../../../../core/posting";+import type { Accounting } from "../../../../core/types";+import { AccountingApiError } from "../../../../core/utils";+import type { Qbo } from "../../models";+import {+ extractQboErrorDetails,+ isQboAccountPeriodClosedError,+ QBO_FAULT_CODES+} from "../../provider";+import {+ getQboLockDate,+ mapJournalEntryToQboJournalEntry,+ toQboPeriodClosedError+} from "../journal-entry";+import { QBO_DOC_NUMBER_MAX_LENGTH } from "../shared";++// 3-line balanced fixture: Dr Inventory 150.00, Dr Freight 25.50,+// Cr GRNI accrual 175.50 (Carbon signed amounts: positive = debit)+const makeJournal = (+ overrides?: Partial<Accounting.JournalEntry>+): Accounting.JournalEntry => ({+ id: "je_123",+ companyId: "company-1",+ journalEntryId: "JE000042",+ description: "Receipt posting",+ postingDate: "2026-07-01",+ status: "Posted",+ sourceType: "Purchase Receipt",+ reversalOfId: null,+ reversedById: null,+ reversal: false,+ lines: [+ {+ id: "line-1",+ accountId: "acc-inventory",+ amount: 150,+ description: "Inventory"+ },+ { id: "line-2", accountId: "acc-freight", amount: 25.5, description: null },+ {+ id: "line-3",+ accountId: "acc-accrual",+ amount: -175.5,+ description: "GRNI accrual"+ }+ ],+ updatedAt: "2026-07-01T12:00:00.000Z",+ ...overrides+});++// Carbon account.id -> QBO AccountRef (mapping externalId = QBO Account.Id)+const ACCOUNT_REFS: ReadonlyMap<string, Qbo.Ref> = new Map([+ ["acc-inventory", { value: "84", name: "Inventory Asset" }],+ ["acc-freight", { value: "85", name: "Freight & Delivery" }],+ ["acc-accrual", { value: "86", name: "GRNI Accrual" }]+]);++// The shared pre-flight consumes account "codes"; for QBO that role is+// played by the account Id (the ref value) — same derivation as mapToRemote+const accountIdsByCarbonId = new Map(+ [...ACCOUNT_REFS].map(([accountId, ref]) => [accountId, ref.value] as const)+);++const makeSettings = (+ overrides?: Partial<PostingSyncSettings>+): PostingSyncSettings => ({+ ...DEFAULT_POSTING_SYNC_SETTINGS,+ enabled: true,+ ...overrides+});++function makeQboFaultError(code: string, message: string): AccountingApiError {+ const details = extractQboErrorDetails(400, "Bad Request", {+ Fault: {+ Error: [{ Message: message, Detail: `${message}.`, code, element: "" }],+ type: "ValidationFault"+ }+ });+ return new AccountingApiError("quickbooks", "create journal entry", details);+}++describe("mapJournalEntryToQboJournalEntry", () => {+ it("maps a 3-line journal to unsigned amounts with PostingType per Carbon sign (positive = debit)", () => {+ const payload = mapJournalEntryToQboJournalEntry({+ journal: makeJournal(),+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01"+ });++ expect(payload.DocNumber).toBe("JE000042");+ expect(payload.PrivateNote).toBe("Carbon JE000042 je_123");+ expect(payload.TxnDate).toBe("2026-07-01");+ expect(payload.Line).toEqual([+ {+ Amount: 150,+ DetailType: "JournalEntryLineDetail",+ Description: "Inventory",+ JournalEntryLineDetail: {+ PostingType: "Debit",+ AccountRef: { value: "84", name: "Inventory Asset" }+ }+ },+ {+ // Line without a description falls back to the journal description+ Amount: 25.5,+ DetailType: "JournalEntryLineDetail",+ Description: "Receipt posting",+ JournalEntryLineDetail: {+ PostingType: "Debit",+ AccountRef: { value: "85", name: "Freight & Delivery" }+ }+ },+ {+ Amount: 175.5,+ DetailType: "JournalEntryLineDetail",+ Description: "GRNI accrual",+ JournalEntryLineDetail: {+ PostingType: "Credit",+ AccountRef: { value: "86", name: "GRNI Accrual" }+ }+ }+ ]);+ });++ it("keeps the payload balanced: debit cents equal credit cents", () => {+ const payload = mapJournalEntryToQboJournalEntry({+ journal: makeJournal(),+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01"+ });++ const centsBySide = payload.Line.reduce(+ (sides, line) => {+ const side = line.JournalEntryLineDetail.PostingType;+ sides[side] += Math.round(line.Amount * 100);+ return sides;+ },+ { Debit: 0, Credit: 0 }+ );++ expect(centsBySide.Debit).toBe(centsBySide.Credit);+ expect(centsBySide.Debit).toBe(17550);+ });++ it("rounds every Amount to 2dp", () => {+ const payload = mapJournalEntryToQboJournalEntry({+ journal: makeJournal({+ lines: [+ {+ id: "line-1",+ accountId: "acc-inventory",+ amount: 10.567,+ description: null+ },+ {+ id: "line-2",+ accountId: "acc-accrual",+ amount: -10.567,+ description: null+ }+ ]+ }),+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01"+ });++ expect(payload.Line.map((line) => line.Amount)).toEqual([10.57, 10.57]);+ });++ it("flips every PostingType (amounts stay positive) and uses the reversal PrivateNote for reversal pushes", () => {+ const payload = mapJournalEntryToQboJournalEntry({+ journal: makeJournal({ status: "Reversed", reversal: true }),+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01"+ });++ expect(payload.PrivateNote).toBe("Carbon reversal of JE000042");+ expect(+ payload.Line.map((line) => line.JournalEntryLineDetail.PostingType)+ ).toEqual(["Credit", "Credit", "Debit"]);+ expect(payload.Line.map((line) => line.Amount)).toEqual([150, 25.5, 175.5]);+ });++ it("appends the original date to the PrivateNote when the push was re-dated", () => {+ const payload = mapJournalEntryToQboJournalEntry({+ journal: makeJournal(),+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-02",+ redatedFromDate: "2026-07-01"+ });++ expect(payload.PrivateNote).toBe(+ "Carbon JE000042 je_123 | original date 2026-07-01"+ );+ expect(payload.TxnDate).toBe("2026-07-02");+ });++ it("keeps DocNumber at the 21-char boundary and omits it beyond (PrivateNote still carries the ids)", () => {+ const atCap = "X".repeat(QBO_DOC_NUMBER_MAX_LENGTH);+ const boundary = mapJournalEntryToQboJournalEntry({+ journal: makeJournal({ journalEntryId: atCap }),+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01"+ });+ expect(boundary.DocNumber).toBe(atCap);+ expect(boundary.PrivateNote).toBe(`Carbon ${atCap} je_123`);++ const overCap = "X".repeat(QBO_DOC_NUMBER_MAX_LENGTH + 1);+ const overflow = mapJournalEntryToQboJournalEntry({+ journal: makeJournal({ journalEntryId: overCap }),+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01"+ });+ expect(overflow.DocNumber).toBeUndefined();+ expect(overflow.PrivateNote).toBe(`Carbon ${overCap} je_123`);+ });++ it("throws the structured UNMAPPED_ACCOUNTS error when a line's account has no mapping", () => {+ let thrown: unknown;+ try {+ mapJournalEntryToQboJournalEntry({+ journal: makeJournal(),+ accountRefsById: new Map([+ ["acc-inventory", { value: "84" } satisfies Qbo.Ref]+ ]),+ pushDate: "2026-07-01"+ });+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(JournalEntrySyncError);+ const failure = (thrown as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(failure.warning).toBe(true);+ expect(failure.metadata?.unmappedAccountIds).toEqual(["acc-freight"]);+ });+});++// ── Dimension slots → ClassRef / DepartmentRef (Phase 2) ─────────────────────++describe("mapJournalEntryToQboJournalEntry — dimensions", () => {+ const LOCATION_DIM = "dim_loc";+ const COST_CENTER_DIM = "dim_cc";++ const dimensionedJournal = makeJournal({+ lines: [+ {+ id: "line-1",+ accountId: "acc-inventory",+ amount: 150,+ description: "Inventory",+ dimensions: [+ { dimensionId: LOCATION_DIM, valueId: "loc_atl" },+ { dimensionId: COST_CENTER_DIM, valueId: "cc_ops" }+ ]+ },+ {+ id: "line-2",+ accountId: "acc-accrual",+ amount: -150,+ description: null,+ dimensions: [{ dimensionId: LOCATION_DIM, valueId: "loc_bos" }]+ }+ ]+ });++ const slots = [+ { dimensionId: LOCATION_DIM, target: "class" },+ { dimensionId: COST_CENTER_DIM, target: "department" }+ ];++ it("attaches ClassRef and DepartmentRef from the value mappings (golden fixture)", () => {+ const payload = mapJournalEntryToQboJournalEntry({+ journal: dimensionedJournal,+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01",+ dimensions: {+ slots,+ refsByValue: new Map([+ ["dim_loc:loc_atl", { value: "300", name: "Atlanta" }],+ ["dim_loc:loc_bos", { value: "301", name: "Boston" }],+ ["dim_cc:cc_ops", { value: "500", name: "Operations" }]+ ])+ }+ });++ expect(payload.Line[0]?.JournalEntryLineDetail).toEqual({+ PostingType: "Debit",+ AccountRef: { value: "84", name: "Inventory Asset" },+ ClassRef: { value: "300", name: "Atlanta" },+ DepartmentRef: { value: "500", name: "Operations" }+ });+ expect(payload.Line[1]?.JournalEntryLineDetail).toEqual({+ PostingType: "Credit",+ AccountRef: { value: "86", name: "GRNI Accrual" },+ ClassRef: { value: "301", name: "Boston" }+ });+ });++ it("omits refs for unmapped values (drop path) and for unslotted dimensions", () => {+ const payload = mapJournalEntryToQboJournalEntry({+ journal: dimensionedJournal,+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01",+ dimensions: {+ slots: [{ dimensionId: LOCATION_DIM, target: "class" }],+ // Boston is unmapped → its line pushes without a ClassRef+ refsByValue: new Map([["dim_loc:loc_atl", { value: "300" }]])+ }+ });++ expect(payload.Line[0]?.JournalEntryLineDetail.ClassRef).toEqual({+ value: "300"+ });+ // cost-center dim is not slotted → never a DepartmentRef+ expect(+ payload.Line[0]?.JournalEntryLineDetail.DepartmentRef+ ).toBeUndefined();+ expect(payload.Line[1]?.JournalEntryLineDetail.ClassRef).toBeUndefined();+ });++ it("leaves lines untouched when no dimension args are passed (legacy callers)", () => {+ const payload = mapJournalEntryToQboJournalEntry({+ journal: dimensionedJournal,+ accountRefsById: ACCOUNT_REFS,+ pushDate: "2026-07-01"+ });++ expect(payload.Line[0]?.JournalEntryLineDetail.ClassRef).toBeUndefined();+ expect(+ payload.Line[0]?.JournalEntryLineDetail.DepartmentRef+ ).toBeUndefined();+ });++ it("parks with UNMAPPED_DIMENSION_VALUES in pre-flight before the mapper runs (warn policy)", () => {+ const settings = makeSettings({+ dimensionSlots: [{ dimensionId: LOCATION_DIM, target: "class" }],+ onUnmappedDimensionValue: "warn"+ });++ const preflight = runJournalEntryPreflight({+ journal: dimensionedJournal,+ accountCodesById: accountIdsByCarbonId,+ controlAccountIds: new Set(),+ lockDate: null,+ settings,+ dimensionValueMappings: new Map([["dim_loc:loc_atl", "300"]])+ });++ expect(preflight.failure?.errorCode).toBe("UNMAPPED_DIMENSION_VALUES");+ expect(preflight.failure?.warning).toBe(true);+ expect(preflight.failure?.metadata).toEqual({+ unmappedDimensionValues: [+ { dimensionId: LOCATION_DIM, valueId: "loc_bos" }+ ]+ });+ expect(isJournalEntrySyncFailure(preflight.failure)).toBe(true);+ });+});++describe("getQboLockDate (closed-books source)", () => {+ it("returns ONLY the manual settings.lockDate, normalized to YYYY-MM-DD", () => {+ expect(getQboLockDate(makeSettings({ lockDate: "2026-06-30" }))).toBe(+ "2026-06-30"+ );+ expect(+ getQboLockDate(makeSettings({ lockDate: "2026-06-30T00:00:00.000Z" }))+ ).toBe("2026-06-30");+ });++ it("returns null when no manual lock date is stored (the QBO API cannot read the close date)", () => {+ expect(getQboLockDate(makeSettings())).toBeNull();+ });+});++describe("closed-books pre-flight with the manual lock date", () => {+ it("parks the push (PERIOD_LOCKED warning) when the journal is dated on or before the lock date", () => {+ const settings = makeSettings({ lockDate: "2026-07-01" });++ const result = runJournalEntryPreflight({+ journal: makeJournal(), // dated 2026-07-01 — on the lock date+ accountCodesById: accountIdsByCarbonId,+ controlAccountIds: new Set<string>(),+ lockDate: getQboLockDate(settings),+ settings+ });++ expect(result.failure?.errorCode).toBe("PERIOD_LOCKED");+ expect(result.failure?.warning).toBe(true);+ expect(result.failure?.metadata).toEqual({+ postingDate: "2026-07-01",+ lockDate: "2026-07-01"+ });+ });++ it("re-dates to lock date + 1 under the redate policy and notes the original date in the PrivateNote", () => {+ const settings = makeSettings({+ lockDate: "2026-07-01",+ periodLockPolicy: "redate"+ });++ const preflight = runJournalEntryPreflight({+ journal: makeJournal(),+ accountCodesById: accountIdsByCarbonId,+ controlAccountIds: new Set<string>(),+ lockDate: getQboLockDate(settings),+ settings+ });++ expect(preflight).toEqual({+ failure: null,+ pushDate: "2026-07-02",+ redatedFromDate: "2026-07-01"+ });+ if (preflight.failure) throw new Error("preflight must pass");++ const payload = mapJournalEntryToQboJournalEntry({+ journal: makeJournal(),+ accountRefsById: ACCOUNT_REFS,+ pushDate: preflight.pushDate,+ redatedFromDate: preflight.redatedFromDate+ });++ expect(payload.TxnDate).toBe("2026-07-02");+ expect(payload.PrivateNote).toBe(+ "Carbon JE000042 je_123 | original date 2026-07-01"+ );+ });++ it("does not lock journals dated after the manual lock date", () => {+ const settings = makeSettings({ lockDate: "2026-06-30" });++ const result = runJournalEntryPreflight({+ journal: makeJournal(),+ accountCodesById: accountIdsByCarbonId,+ controlAccountIds: new Set<string>(),+ lockDate: getQboLockDate(settings),+ settings+ });++ expect(result.failure).toBeNull();+ });++ it("hard-fails an unbalanced journal (UNBALANCED_JOURNAL, warning: false) before any push", () => {+ const journal = makeJournal();+ const creditLine = journal.lines[2];+ if (!creditLine) throw new Error("fixture must have 3 lines");+ creditLine.amount = -175.49;++ const result = runJournalEntryPreflight({+ journal,+ accountCodesById: accountIdsByCarbonId,+ controlAccountIds: new Set<string>(),+ lockDate: null,+ settings: makeSettings()+ });++ expect(result.failure?.errorCode).toBe("UNBALANCED_JOURNAL");+ expect(result.failure?.warning).toBe(false);+ });+});++describe("toQboPeriodClosedError (6210 backstop for a stale manual lock date)", () => {+ it("converts QBO's Account Period Closed fault into the structured PERIOD_LOCKED Warning", () => {+ const fault = makeQboFaultError(+ QBO_FAULT_CODES.ACCOUNT_PERIOD_CLOSED,+ "Account Period Closed"+ );+ expect(isQboAccountPeriodClosedError(fault)).toBe(true);++ const converted = toQboPeriodClosedError(fault, {+ journalLabel: "JE000042",+ txnDate: "2026-07-01"+ });++ expect(converted).toBeInstanceOf(JournalEntrySyncError);+ expect(converted?.failure.errorCode).toBe("PERIOD_LOCKED");+ expect(converted?.failure.warning).toBe(true);+ expect(converted?.failure.metadata).toEqual({+ txnDate: "2026-07-01",+ qboFaultCode: QBO_FAULT_CODES.ACCOUNT_PERIOD_CLOSED+ });+ // The drain records the envelope, not a flattened string+ expect(isJournalEntrySyncFailure(converted?.failure)).toBe(true);+ expect(converted?.message).toContain("PERIOD_LOCKED");+ });++ it("returns null for other QBO faults and non-API errors", () => {+ const duplicateName = makeQboFaultError(+ QBO_FAULT_CODES.DUPLICATE_NAME_EXISTS,+ "Duplicate Name Exists Error"+ );+ expect(isQboAccountPeriodClosedError(duplicateName)).toBe(false);+ expect(+ toQboPeriodClosedError(duplicateName, { journalLabel: "JE000042" })+ ).toBeNull();++ expect(+ toQboPeriodClosedError(new Error("network down"), {+ journalLabel: "JE000042"+ })+ ).toBeNull();+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.tsnew file mode 100644index 0000000000..82faf9c3fa--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/payment.test.ts@@ -0,0 +1,429 @@+import { describe, expect, it, vi } from "vitest";+import type { NormalizedPayment } from "../../../../core/payment-application";+import { SyncFactory } from "../../../../core/sync";+import type { Qbo } from "../../models";+// Importing the provider barrel registers the QBO syncer registry (side+// effect) so SyncFactory.getSyncer can resolve `payment`.+import "../../index";+import {+ buildQboPaymentSyncChange,+ getQboBillPaymentSyncEntityId,+ getQboPaymentLinkedDocuments,+ getQboPaymentSyncEntityId,+ parseQboPaymentSyncEntityId,+ type QboPayment,+ QboPaymentSyncer+} from "../payment";++// The base dynamically imports @carbon/auth/client.server only when posting;+// mock it so nothing touches server env during these pure-mapper tests.+vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: () => ({ functions: { invoke: vi.fn() } })+}));++describe("composite payment sync entity id (QBO)", () => {+ it("round-trips invoice + payment ids as a prefix-less AR id", () => {+ const entityId = getQboPaymentSyncEntityId("inv-remote-1", "pay-1");+ expect(entityId).toBe("inv-remote-1:pay-1");+ expect(parseQboPaymentSyncEntityId(entityId)).toEqual({+ family: "ar",+ documentRemoteId: "inv-remote-1",+ paymentRemoteId: "pay-1"+ });+ });++ it("round-trips bill + payment ids as a `bill:`-prefixed AP id", () => {+ const entityId = getQboBillPaymentSyncEntityId("bill-remote-1", "bp-2");+ expect(entityId).toBe("bill:bill-remote-1:bp-2");+ expect(parseQboPaymentSyncEntityId(entityId)).toEqual({+ family: "ap",+ documentRemoteId: "bill-remote-1",+ paymentRemoteId: "bp-2"+ });+ });++ it("throws on malformed ids (both families)", () => {+ expect(() => parseQboPaymentSyncEntityId("no-separator")).toThrow(+ /Invalid QuickBooks Online payment sync entity id/+ );+ expect(() => parseQboPaymentSyncEntityId(":pay-1")).toThrow(+ /Invalid QuickBooks Online payment sync entity id/+ );+ expect(() => parseQboPaymentSyncEntityId("inv-1:")).toThrow(+ /Invalid QuickBooks Online payment sync entity id/+ );+ expect(() => parseQboPaymentSyncEntityId("bill:no-separator")).toThrow(+ /Invalid QuickBooks Online payment sync entity id/+ );+ expect(() => parseQboPaymentSyncEntityId("bill:b-1:")).toThrow(+ /Invalid QuickBooks Online payment sync entity id/+ );+ });+});++describe("getQboPaymentLinkedDocuments", () => {+ it("extracts one bill per line for a BillPayment (AP)", () => {+ const billPayment: Qbo.BillPayment = {+ Id: "bp-1",+ TotalAmt: 800,+ Line: [+ { Amount: 500, LinkedTxn: [{ TxnId: "bill-1", TxnType: "Bill" }] },+ { Amount: 300, LinkedTxn: [{ TxnId: "bill-2", TxnType: "Bill" }] }+ ]+ };+ expect(getQboPaymentLinkedDocuments(billPayment, "Bill")).toEqual([+ { remoteId: "bill-1", amount: 500 },+ { remoteId: "bill-2", amount: 300 }+ ]);+ });++ it("ignores non-matching TxnTypes", () => {+ const payment: Qbo.Payment = {+ Id: "pay-1",+ Line: [+ { Amount: 100, LinkedTxn: [{ TxnId: "inv-1", TxnType: "Invoice" }] },+ {+ Amount: 0,+ LinkedTxn: [{ TxnId: "credit-1", TxnType: "CreditMemo" }]+ }+ ]+ };+ expect(getQboPaymentLinkedDocuments(payment, "Invoice")).toEqual([+ { remoteId: "inv-1", amount: 100 }+ ]);+ });+});++describe("buildQboPaymentSyncChange", () => {+ it("builds the AP composite from the first linked bill", () => {+ const billPayment: Qbo.BillPayment = {+ Id: "bp-1",+ Line: [+ { Amount: 500, LinkedTxn: [{ TxnId: "bill-1", TxnType: "Bill" }] },+ { Amount: 300, LinkedTxn: [{ TxnId: "bill-2", TxnType: "Bill" }] }+ ]+ };+ expect(buildQboPaymentSyncChange(billPayment, "ap")).toEqual({+ documentRemoteId: "bill-1",+ entityId: "bill:bill-1:bp-1"+ });+ });++ it("builds the AR composite from the first linked invoice", () => {+ const payment: Qbo.Payment = {+ Id: "pay-1",+ Line: [+ { Amount: 125, LinkedTxn: [{ TxnId: "inv-1", TxnType: "Invoice" }] }+ ]+ };+ expect(buildQboPaymentSyncChange(payment, "ar")).toEqual({+ documentRemoteId: "inv-1",+ entityId: "inv-1:pay-1"+ });+ });++ it("returns null when the payment settles no document", () => {+ expect(+ buildQboPaymentSyncChange({ Id: "bp-1", Line: [] }, "ap")+ ).toBeNull();+ });+});++function makeMapperSyncer() {+ const syncer = new QboPaymentSyncer({+ database: {} as never,+ companyId: "company-1",+ provider: { id: "quickbooks" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ return syncer as unknown as {+ mapToNormalized(+ remote: Qbo.Payment | Qbo.BillPayment,+ entityId: string+ ): NormalizedPayment;+ };+}++describe("QboPaymentSyncer.mapToNormalized", () => {+ it("normalizes a single-bill BillPayment to a settled AP NormalizedPayment", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ Id: "bp-1",+ TotalAmt: 500,+ TxnDate: "2026-08-01",+ CurrencyRef: { value: "USD" },+ Line: [+ { Amount: 500, LinkedTxn: [{ TxnId: "bill-9", TxnType: "Bill" }] }+ ],+ MetaData: { LastUpdatedTime: "2026-08-01T10:00:00-07:00" }+ },+ "bill:bill-9:bp-1"+ );++ expect(normalized).toEqual({+ family: "ap",+ documentRemoteId: "bill-9",+ paymentRemoteId: "bp-1",+ amount: 500,+ currencyCode: "USD",+ exchangeRate: 1,+ paidDate: "2026-08-01",+ reference: "bp-1",+ status: "settled",+ linkedDocuments: [{ remoteId: "bill-9", amount: 500 }]+ });+ });++ it("fans a multi-bill BillPayment out into per-bill linkedDocuments", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ Id: "bp-2",+ TotalAmt: 800,+ TxnDate: "2026-08-02",+ CurrencyRef: { value: "USD" },+ ExchangeRate: 1,+ Line: [+ { Amount: 500, LinkedTxn: [{ TxnId: "bill-1", TxnType: "Bill" }] },+ { Amount: 300, LinkedTxn: [{ TxnId: "bill-2", TxnType: "Bill" }] }+ ],+ MetaData: { LastUpdatedTime: "2026-08-02T10:00:00-07:00" }+ },+ // The composite carries the FIRST linked bill.+ "bill:bill-1:bp-2"+ );++ expect(normalized.family).toBe("ap");+ expect(normalized.documentRemoteId).toBe("bill-1");+ expect(normalized.amount).toBe(800);+ expect(normalized.linkedDocuments).toEqual([+ { remoteId: "bill-1", amount: 500 },+ { remoteId: "bill-2", amount: 300 }+ ]);+ });++ it("normalizes a Payment to a settled AR NormalizedPayment", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ Id: "pay-1",+ TotalAmt: 125,+ TxnDate: "2026-07-15",+ CurrencyRef: { value: "EUR" },+ ExchangeRate: 1.1,+ Line: [+ { Amount: 125, LinkedTxn: [{ TxnId: "inv-1", TxnType: "Invoice" }] }+ ],+ MetaData: { LastUpdatedTime: "2026-07-15T10:00:00-07:00" }+ },+ "inv-1:pay-1"+ );++ expect(normalized).toEqual({+ family: "ar",+ documentRemoteId: "inv-1",+ paymentRemoteId: "pay-1",+ amount: 125,+ currencyCode: "EUR",+ exchangeRate: 1.1,+ paidDate: "2026-07-15",+ reference: "pay-1",+ status: "settled",+ linkedDocuments: [{ remoteId: "inv-1", amount: 125 }]+ });+ });++ it("maps a voided payment (TotalAmt 0) to void with no positive linkedDocuments", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ Id: "bp-3",+ TotalAmt: 0,+ TxnDate: "2026-08-03",+ CurrencyRef: { value: "USD" },+ Line: [+ { Amount: 0, LinkedTxn: [{ TxnId: "bill-9", TxnType: "Bill" }] }+ ],+ MetaData: { LastUpdatedTime: "2026-08-03T10:00:00-07:00" }+ },+ "bill:bill-9:bp-3"+ );+ expect(normalized.status).toBe("void");+ expect(normalized.family).toBe("ap");+ expect(normalized.documentRemoteId).toBe("bill-9");+ // Zeroed lines drop out — the core reverses via the documentRemoteId fallback.+ expect(normalized.linkedDocuments).toBeUndefined();+ });+});++describe("QboPaymentSyncer.fetchRemote tombstone (hard delete → void)", () => {+ function makeFetchSyncer(getResult: QboPayment | null) {+ const syncer = new QboPaymentSyncer({+ database: {} as never,+ companyId: "company-1",+ provider: {+ id: "quickbooks",+ getBillPayment: async () => getResult,+ getPayment: async () => getResult+ } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ return syncer as unknown as {+ fetchRemote(entityId: string): Promise<QboPayment | null>;+ mapToNormalized(remote: QboPayment, entityId: string): NormalizedPayment;+ };+ }++ it("returns a bare tombstone marker when a BillPayment 404s → normalizes to void", async () => {+ const syncer = makeFetchSyncer(null);+ const tombstone = await syncer.fetchRemote("bill:bill-9:bp-1");+ expect(tombstone).toEqual({ Id: "bp-1" });++ // The tombstone flows through mapToNormalized to a reversing (void) payment+ // built purely from the parsed composite id (amount 0, no linkedDocuments)+ // → upsertLocalPaymentDraft returns postAction "void" → post-payment+ // { type: "void" }.+ const normalized = syncer.mapToNormalized(+ tombstone as QboPayment,+ "bill:bill-9:bp-1"+ );+ expect(normalized.status).toBe("void");+ expect(normalized.family).toBe("ap");+ expect(normalized.documentRemoteId).toBe("bill-9");+ expect(normalized.amount).toBe(0);+ expect(normalized.linkedDocuments).toBeUndefined();+ });++ it("passes a found payment through unchanged (no tombstone)", async () => {+ const real: QboPayment = {+ Id: "bp-1",+ TotalAmt: 500,+ Line: [{ Amount: 500, LinkedTxn: [{ TxnId: "bill-9", TxnType: "Bill" }] }]+ };+ const syncer = makeFetchSyncer(real);+ expect(await syncer.fetchRemote("bill:bill-9:bp-1")).toBe(real);+ });+});++// Fake Kysely db answering only the documents-mode gate's metadata read.+// `metadata` undefined = no row (gate resolves to defaults = documents).+function makeMetadataDb(metadata: unknown) {+ const chain: any = {+ select: () => chain,+ where: () => chain,+ executeTakeFirst: async () =>+ metadata === undefined ? undefined : { metadata }+ };+ return { selectFrom: () => chain } as never;+}++function familyModeMetadata(family: "ar" | "ap", mode: string) {+ return { settings: { postingSync: { families: { [family]: mode } } } };+}++describe("QboPaymentSyncer.shouldSync ownership gate", () => {+ function makeSyncer(mappedDocId: string | null, metadata?: unknown) {+ const syncer = new QboPaymentSyncer({+ database: makeMetadataDb(metadata),+ companyId: "company-1",+ provider: { id: "quickbooks" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ (syncer as unknown as Record<string, unknown>).mappingService = {+ getEntityId: async () => mappedDocId+ };+ return syncer as unknown as {+ shouldSync(context: {+ direction: "push" | "pull";+ remoteEntity?: Qbo.Payment | Qbo.BillPayment;+ isFirstSync: boolean;+ entityId: string;+ }): Promise<boolean | string>;+ };+ }++ it("skips (does not fail) when the AP family is not in documents mode", async () => {+ const result = await makeSyncer(+ "purchase-invoice-1",+ familyModeMetadata("ap", "journals")+ ).shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:bp-1",+ remoteEntity: { Id: "bp-1", TotalAmt: 500 },+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("payment sync-back is disabled");+ expect(result).toContain("ap");+ });++ it("skips (does not fail) an AP bill payment on a bill with no local mapping", async () => {+ const result = await makeSyncer(null).shouldSync({+ direction: "pull",+ entityId: "bill:bill-other:bp-1",+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("no Carbon mapping");+ expect(result).toContain("bill");+ });++ it("skips an AR payment on an invoice with no local mapping", async () => {+ const result = await makeSyncer(null).shouldSync({+ direction: "pull",+ entityId: "inv-other:pay-1",+ isFirstSync: true+ });+ expect(result).toContain("no Carbon mapping");+ expect(result).toContain("invoice");+ });++ it("proceeds for a payment on a locally-mapped document", async () => {+ const result = await makeSyncer("purchase-invoice-1").shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:bp-1",+ remoteEntity: { Id: "bp-1", TotalAmt: 500 },+ isFirstSync: true+ });+ expect(result).toBe(true);+ });++ it("skips a first-seen voided (TotalAmt 0) payment on a mapped document", async () => {+ const result = await makeSyncer("purchase-invoice-1").shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:bp-1",+ remoteEntity: { Id: "bp-1", TotalAmt: 0 },+ isFirstSync: true+ });+ expect(result).toContain("never recorded");+ });+});++describe("QBO payment syncer registration", () => {+ it("resolves via SyncFactory.getSyncer({provider:'quickbooks', entityType:'payment'})", () => {+ const syncer = SyncFactory.getSyncer({+ database: {} as never,+ companyId: "company-1",+ provider: { id: "quickbooks" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ expect(syncer).toBeInstanceOf(QboPaymentSyncer);+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/purchase-order.test.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/purchase-order.test.tsnew file mode 100644index 0000000000..c438c60240--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/__tests__/purchase-order.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from "vitest";+import type { Accounting } from "../../../../core/types";+import type { Qbo } from "../../models";+import {+ mapCarbonPoStatusToQbo,+ mapQboPoStatusToCarbon+} from "../purchase-order";+import { buildQboDocNumberFields, buildQboExpenseLines } from "../shared";++describe("QBO purchase order mapping fixture", () => {+ it("maps a PO line set with item + G/L lines through the shared expense-line builder", () => {+ const accountRefs: ReadonlyMap<string, Qbo.Ref> = new Map([+ ["acc-tooling", { value: "88", name: "Tooling Expense" }]+ ]);++ const lines = buildQboExpenseLines({+ lines: [+ {+ itemId: "item-1",+ accountId: null,+ description: "Raw stock",+ quantity: 100,+ unitPrice: 1.25,+ totalAmount: 125+ },+ {+ itemId: null,+ accountId: "acc-tooling",+ description: "Tooling charge",+ quantity: 1,+ unitPrice: 300,+ totalAmount: 300+ }+ ],+ itemRemoteIds: new Map([["item-1", "55"]]),+ accountRefsById: accountRefs,+ documentLabel: "purchase order PO-000042"+ });++ expect(lines[0]?.DetailType).toBe("ItemBasedExpenseLineDetail");+ expect(lines[0]?.ItemBasedExpenseLineDetail?.ItemRef).toEqual({+ value: "55"+ });+ expect(lines[1]?.DetailType).toBe("AccountBasedExpenseLineDetail");+ expect(lines[1]?.AccountBasedExpenseLineDetail?.AccountRef.value).toBe(+ "88"+ );+ });++ it("applies the 21-char DocNumber rule to PO numbers", () => {+ const longPoNumber = "PO-0000000000000000042"; // 22 chars+ const fields = buildQboDocNumberFields(longPoNumber);+ expect(fields.DocNumber).toBeUndefined();+ expect(fields.PrivateNote).toBe(`Carbon ${longPoNumber}`);+ expect(fields.source).toBe("privateNote");+ });+});++describe("PO status mapping", () => {+ it("maps Carbon locked statuses onto QBO POStatus", () => {+ const open: Accounting.PurchaseOrder["status"][] = [+ "To Receive",+ "To Receive and Invoice",+ "To Invoice"+ ];+ for (const status of open) {+ expect(mapCarbonPoStatusToQbo(status)).toBe("Open");+ }+ expect(mapCarbonPoStatusToQbo("Completed")).toBe("Closed");+ expect(mapCarbonPoStatusToQbo("Closed")).toBe("Closed");+ });++ it("maps QBO POStatus back onto Carbon statuses", () => {+ expect(mapQboPoStatusToCarbon("Open")).toBe("To Receive");+ expect(mapQboPoStatusToCarbon("Closed")).toBe("Closed");+ expect(mapQboPoStatusToCarbon(undefined)).toBeUndefined();+ });+});diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/bill.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/bill.tsnew file mode 100644index 0000000000..e9c813c109--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/bill.ts@@ -0,0 +1,831 @@+import type { KyselyTx } from "@carbon/database/client";+import { sql } from "kysely";+import {+ type CostingLine,+ costingLineItemLabel,+ loadBillCostingLines,+ toTransactionCurrencyLines+} from "../../../core/document-costing";+import { createMappingService } from "../../../core/external-mapping";+import { JournalEntrySyncError, roundCurrency } from "../../../core/posting";+import {+ type Accounting,+ BaseEntitySyncer,+ type ShouldSyncContext+} from "../../../core/types";+import { parseQboDate, type Qbo } from "../models";+import type { QboProvider } from "../provider";+import {+ buildQboDocNumberFields,+ loadQboAccountRefsById,+ type QboWriteOmit,+ updateWithSyncTokenRetry+} from "./shared";++/**+ * QboBillSyncer — Carbon purchase invoices ↔ QBO Bill objects (two-way,+ * owner accounting per DEFAULT_SYNC_CONFIG; entityType "bill" like the+ * Xero counterpart).+ *+ * Push: VendorRef via JIT vendor sync; item lines →+ * ItemBasedExpenseLineDetail (ItemRef = the item's QBO id, JIT-synced),+ * non-item lines → AccountBasedExpenseLineDetail with the mapped account+ * (account-mapping service; unmapped → plain error, Failed). DocNumber+ * carries the Carbon invoice id under QBO's 21-char cap, else PrivateNote.+ *+ * Pull mirrors the Xero counterpart: status derived from+ * Balance/TotalAmt/DueDate, dates and totals back onto the Carbon+ * document, and — like Xero — a bill unknown to Carbon is created from the+ * remote (sequence id, supplier interaction, default user).+ */++// Row shapes (mirror the Xero bill syncer's, plus line accountId for the+// account-mapping resolution QBO needs)+type BillRow = {+ id: string;+ companyId: string;+ invoiceId: string;+ supplierId: string | null;+ status: Accounting.Bill["status"];+ dateIssued: string | null;+ dateDue: string | null;+ datePaid: string | null;+ currencyCode: string;+ exchangeRate: number;+ subtotal: number;+ totalTax: number;+ totalDiscount: number;+ totalAmount: number;+ balance: number;+ supplierReference: string | null;+ updatedAt: string | null;+};++type BillLineRow = {+ id: string;+ invoiceId: string;+ description: string | null;+ quantity: number;+ unitPrice: number | null;+ itemId: string | null;+ accountId: string | null;+ accountNumber: string | null;+ taxPercent: number | null;+ taxAmount: number | null;+ totalAmount: number | null;+ itemCode: string | null;+ purchaseOrderLineId: string | null;+};++/**+ * Derive the Carbon bill status from QBO's Balance/TotalAmt/DueDate (QBO+ * bills carry no status enum). Pure — exported for tests.+ */+export function deriveCarbonBillStatus(args: {+ totalAmt: number | undefined;+ balance: number | undefined;+ dueDate: string | undefined;+ now?: Date;+}): Accounting.Bill["status"] | undefined {+ if (args.balance === undefined) return undefined;+ if (args.balance <= 0) return "Paid";+ if (args.totalAmt !== undefined && args.balance < args.totalAmt) {+ return "Partially Paid";+ }+ if (args.dueDate && new Date(args.dueDate) < (args.now ?? new Date())) {+ return "Overdue";+ }+ return "Open";+}++// Only posted bills are pushed (Draft has no journal to replay) — mirrors the+// QBO invoice syncer's posted-status gate.+const SYNCABLE_STATUSES: Accounting.Bill["status"][] = [+ "Pending",+ "Open",+ "Return",+ "Debit Note Issued",+ "Partially Paid",+ "Paid",+ "Overdue"+];++/**+ * Build QBO bill lines as an account-costed replay of the bill's posted+ * "Purchase Invoice" journal: one `AccountBasedExpenseLineDetail` per costing+ * line to the journal's mapped account (GR-IR / PPV / clearing), NEVER the+ * item's account. The item is a Description label only. Pure — exported for+ * tests. Amounts are already in the invoice's transaction currency+ * (`toTransactionCurrencyLines`). Tax-neutral: no `TxnTaxDetail`, no per-line+ * tax (the replay amounts embed tax; the purchase posting folds it into cost).+ *+ * Unmapped / account-less lines throw the structured UNMAPPED_ACCOUNTS+ * Warning (user-fixable: map the account, then retry) — the same envelope the+ * Rillet bill and the QBO journal syncer use.+ */+export function buildQboBillLines(args: {+ bill: Accounting.Bill;+ costingLines: CostingLine[];+ accountRefsById: ReadonlyMap<string, Qbo.Ref>;+}): Array<Omit<Qbo.ExpenseLine, "Id">> {+ const { bill } = args;++ if (args.costingLines.length === 0) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync bill ${bill.invoiceId}: no posted Purchase Invoice journal found — the bill's G/L costing comes from its posting journal. Post the invoice (with accounting enabled), then retry.`,+ warning: true,+ metadata: { billId: bill.id }+ });+ }++ const unmapped = new Set<string>();+ const lineIdsWithoutAccount: string[] = [];+ for (const line of args.costingLines) {+ if (!line.accountId) {+ lineIdsWithoutAccount.push(line.id);+ continue;+ }+ if (!args.accountRefsById.get(line.accountId)) {+ unmapped.add(line.accountId);+ }+ }++ if (unmapped.size > 0 || lineIdsWithoutAccount.length > 0) {+ const parts: string[] = [];+ if (unmapped.size > 0) {+ parts.push(+ `${unmapped.size} account(s) have no QuickBooks Online account mapping`+ );+ }+ if (lineIdsWithoutAccount.length > 0) {+ parts.push(+ `${lineIdsWithoutAccount.length} posting journal line(s) have no account`+ );+ }+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync bill ${bill.invoiceId}: ${parts.join(+ "; "+ )}. Map the account(s) on the integration settings page, then retry.`,+ warning: true,+ metadata: {+ billId: bill.id,+ unmappedAccountIds: [...unmapped],+ ...(lineIdsWithoutAccount.length > 0 ? { lineIdsWithoutAccount } : {})+ }+ });+ }++ return args.costingLines.map((line) => {+ const description = costingLineItemLabel(line) ?? line.description;+ return {+ Amount: roundCurrency(line.amount),+ ...(description ? { Description: description } : {}),+ DetailType: "AccountBasedExpenseLineDetail",+ AccountBasedExpenseLineDetail: {+ AccountRef: args.accountRefsById.get(line.accountId!)!+ }+ };+ });+}++export class QboBillSyncer extends BaseEntitySyncer<+ Accounting.Bill,+ Qbo.Bill,+ QboWriteOmit+> {+ private accountRefsByIdPromise?: Promise<Map<string, Qbo.Ref>>;+ private remoteMetaById = new Map<+ string,+ { syncToken?: string; lastUpdatedTime?: string }+ >();++ private get qboProvider(): QboProvider {+ return this.provider as QboProvider;+ }++ private rememberRemoteEntity(+ remote: Pick<Qbo.Bill, "Id" | "SyncToken" | "MetaData"> | null+ ): void {+ if (!remote?.Id) return;+ this.remoteMetaById.set(remote.Id, {+ syncToken: remote.SyncToken,+ lastUpdatedTime: remote.MetaData?.LastUpdatedTime+ });+ }++ private getAccountRefsById(): Promise<Map<string, Qbo.Ref>> {+ if (!this.accountRefsByIdPromise) {+ this.accountRefsByIdPromise = loadQboAccountRefsById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountRefsByIdPromise;+ }++ // =================================================================+ // 1. ID MAPPING — default implementation (entityType "bill"), with+ // SyncToken/LastUpdatedTime recorded on the mapping (Xero pattern)+ // =================================================================++ protected async linkEntities(+ tx: KyselyTx,+ localId: string,+ remoteId: string,+ remoteUpdatedAt?: Date+ ): Promise<void> {+ const seen = this.remoteMetaById.get(remoteId);+ const txMappingService = createMappingService(tx, this.companyId);+ await txMappingService.link("bill", localId, this.provider.id, remoteId, {+ remoteUpdatedAt:+ remoteUpdatedAt ?? parseQboDate(seen?.lastUpdatedTime) ?? undefined,+ ...(seen?.syncToken !== undefined+ ? { metadata: { syncToken: seen.syncToken } }+ : {})+ });+ }++ // =================================================================+ // 2. TIMESTAMP EXTRACTION+ // =================================================================++ protected getRemoteUpdatedAt(remote: Qbo.Bill): Date | null {+ return parseQboDate(remote.MetaData?.LastUpdatedTime);+ }++ // =================================================================+ // 3. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.Bill | null> {+ const bills = await this.fetchBillsByIds([id]);+ return bills.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.Bill>> {+ return this.fetchBillsByIds(ids);+ }++ private async fetchBillsByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.Bill>> {+ if (ids.length === 0) return new Map();++ const billRows = await this.database+ .selectFrom("purchaseInvoice")+ // `balance` is derived and lives only on the `purchaseInvoices` view+ .leftJoin("purchaseInvoices", "purchaseInvoices.id", "purchaseInvoice.id")+ .select([+ "purchaseInvoice.id",+ "purchaseInvoice.companyId",+ "purchaseInvoice.invoiceId",+ "purchaseInvoice.supplierId",+ "purchaseInvoice.status",+ "purchaseInvoice.dateIssued",+ "purchaseInvoice.dateDue",+ "purchaseInvoice.datePaid",+ "purchaseInvoice.currencyCode",+ "purchaseInvoice.exchangeRate",+ "purchaseInvoice.subtotal",+ "purchaseInvoice.totalTax",+ "purchaseInvoice.totalDiscount",+ "purchaseInvoice.totalAmount",+ "purchaseInvoices.balance",+ "purchaseInvoice.supplierReference",+ "purchaseInvoice.updatedAt"+ ])+ .where("purchaseInvoice.id", "in", ids)+ .where("purchaseInvoice.companyId", "=", this.companyId)+ .execute();++ if (billRows.length === 0) return new Map();++ const lineRows = await this.database+ .selectFrom("purchaseInvoiceLine")+ .leftJoin("item", "item.id", "purchaseInvoiceLine.itemId")+ .leftJoin("account", "account.id", "purchaseInvoiceLine.accountId")+ .select([+ "purchaseInvoiceLine.id",+ "purchaseInvoiceLine.invoiceId",+ "purchaseInvoiceLine.description",+ "purchaseInvoiceLine.quantity",+ "purchaseInvoiceLine.unitPrice",+ "purchaseInvoiceLine.itemId",+ "purchaseInvoiceLine.accountId",+ "purchaseInvoiceLine.taxPercent",+ "purchaseInvoiceLine.taxAmount",+ "purchaseInvoiceLine.totalAmount",+ "purchaseInvoiceLine.purchaseOrderLineId",+ "item.readableId as itemCode",+ "account.number as accountNumber"+ ])+ .where(+ "purchaseInvoiceLine.invoiceId",+ "in",+ billRows.map((b) => b.id)+ )+ .execute();++ // Supplier external IDs (entityType "vendor" — what the vendor syncer+ // stores)+ const supplierIds = billRows+ .map((b) => b.supplierId)+ .filter((id): id is string => id !== null);++ const supplierExternalIds = new Map<string, string | null>();+ if (supplierIds.length > 0) {+ const mappingService = createMappingService(+ this.database,+ this.companyId+ );+ for (const supplierId of supplierIds) {+ supplierExternalIds.set(+ supplierId,+ await mappingService.getExternalId(+ "vendor",+ supplierId,+ this.provider.id+ )+ );+ }+ }++ const linesByInvoice = new Map<string, BillLineRow[]>();+ for (const line of lineRows as BillLineRow[]) {+ const existing = linesByInvoice.get(line.invoiceId) ?? [];+ existing.push(line);+ linesByInvoice.set(line.invoiceId, existing);+ }++ const result = new Map<string, Accounting.Bill>();+ for (const row of billRows as BillRow[]) {+ const lines = linesByInvoice.get(row.id) ?? [];+ result.set(row.id, {+ id: row.id,+ companyId: row.companyId,+ invoiceId: row.invoiceId,+ supplierId: row.supplierId,+ supplierExternalId: row.supplierId+ ? (supplierExternalIds.get(row.supplierId) ?? null)+ : null,+ status: row.status,+ dateIssued: row.dateIssued,+ dateDue: row.dateDue,+ datePaid: row.datePaid,+ currencyCode: row.currencyCode,+ exchangeRate: Number(row.exchangeRate) || 1,+ subtotal: Number(row.subtotal) || 0,+ totalTax: Number(row.totalTax) || 0,+ totalDiscount: Number(row.totalDiscount) || 0,+ totalAmount: Number(row.totalAmount) || 0,+ balance: Number(row.balance) || 0,+ supplierReference: row.supplierReference,+ lines: lines.map((line) => ({+ id: line.id,+ description: line.description,+ quantity: Number(line.quantity) || 0,+ unitPrice: Number(line.unitPrice) || 0,+ itemId: line.itemId,+ itemCode: line.itemCode,+ accountId: line.accountId,+ accountNumber: line.accountNumber,+ taxPercent: line.taxPercent != null ? Number(line.taxPercent) : null,+ taxAmount: line.taxAmount != null ? Number(line.taxAmount) : null,+ totalAmount: Number(line.totalAmount) || 0,+ purchaseOrderLineId: line.purchaseOrderLineId+ })),+ updatedAt: row.updatedAt ?? new Date().toISOString(),+ raw: row+ });+ }++ return result;+ }++ // =================================================================+ // 4. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Qbo.Bill | null> {+ const bill = await this.qboProvider.getBill(id);+ this.rememberRemoteEntity(bill);+ return bill;+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Qbo.Bill>> {+ const result = new Map<string, Qbo.Bill>();+ for (const id of ids) {+ const bill = await this.fetchRemote(id);+ if (bill) result.set(bill.Id, bill);+ }+ return result;+ }++ // =================================================================+ // 5. SHOULD SYNC (posted-bill gate on push)+ // =================================================================++ protected shouldSync(+ context: ShouldSyncContext<Accounting.Bill, Qbo.Bill>+ ): boolean | string {+ if (context.direction === "push" && context.localEntity) {+ if (!SYNCABLE_STATUSES.includes(context.localEntity.status)) {+ return `Bill must be posted before syncing (current status: ${context.localEntity.status})`;+ }+ }++ return true;+ }++ // =================================================================+ // 6. TRANSFORMATION (Carbon -> QBO)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.Bill+ ): Promise<Omit<Qbo.Bill, QboWriteOmit>> {+ // JIT dependency: vendor before the document+ let vendorRemoteId = local.supplierExternalId;+ if (!vendorRemoteId && local.supplierId) {+ vendorRemoteId = await this.ensureDependencySynced(+ "vendor",+ local.supplierId+ );+ }++ if (!vendorRemoteId) {+ throw new Error(+ `Cannot sync bill ${local.id}: No supplier linked or supplier not synced to QuickBooks Online`+ );+ }++ // Account-costed replay of the bill's posted Purchase Invoice journal —+ // the item is a label only, so NO item dependency sync is needed here (the+ // PO keeps item lines via buildQboExpenseLines; the bill does not).+ const accountRefsById = await this.getAccountRefsById();+ const payablesAccountId = await this.getPayablesAccountId();+ const {+ lines: costingLines,+ currencyCode,+ exchangeRate+ } = await loadBillCostingLines(this.database, {+ companyId: this.companyId,+ billId: local.id,+ payablesAccountId+ });++ const transactionLines = toTransactionCurrencyLines(+ costingLines,+ exchangeRate+ );++ // Due date: use dateDue if provided, otherwise default to Net 30+ // (Xero-syncer parity)+ let dueDate = local.dateDue;+ if (!dueDate && local.dateIssued) {+ const issued = new Date(local.dateIssued);+ issued.setDate(issued.getDate() + 30);+ dueDate = issued.toISOString().split("T")[0];+ } else if (!dueDate) {+ const now = new Date();+ now.setDate(now.getDate() + 30);+ dueDate = now.toISOString().split("T")[0];+ }++ const docNumber = buildQboDocNumberFields(+ local.invoiceId,+ local.supplierReference ? `Ref ${local.supplierReference}` : undefined+ );++ return {+ DocNumber: docNumber.DocNumber,+ PrivateNote: docNumber.PrivateNote,+ TxnDate: local.dateIssued ?? undefined,+ DueDate: dueDate,+ VendorRef: { value: vendorRemoteId },+ // FX: pin the currency + provider rate (omit both at parity rate 1).+ ...(exchangeRate !== 1+ ? {+ CurrencyRef: { value: currencyCode },+ ExchangeRate: exchangeRate+ }+ : {}),+ Line: buildQboBillLines({+ bill: local,+ costingLines: transactionLines,+ accountRefsById+ })+ };+ }++ /** accountDefault.payablesAccount — the AP control line to exclude. */+ private async getPayablesAccountId(): Promise<string | null> {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select("payablesAccount")+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();+ return defaults?.payablesAccount ?? null;+ }++ // =================================================================+ // 6. TRANSFORMATION (QBO -> Carbon)+ // =================================================================++ protected async mapToLocal(+ remote: Qbo.Bill+ ): Promise<Partial<Accounting.Bill>> {+ const mappingService = createMappingService(this.database, this.companyId);++ const lines: Accounting.BillLine[] = [];+ for (const [index, line] of (remote.Line ?? []).entries()) {+ const isItemLine = line.DetailType === "ItemBasedExpenseLineDetail";+ const isAccountLine = line.DetailType === "AccountBasedExpenseLineDetail";+ if (!isItemLine && !isAccountLine) continue;++ // Resolve the Carbon item from the QBO ItemRef via the mapping table+ let itemId: string | null = null;+ const remoteItemId = line.ItemBasedExpenseLineDetail?.ItemRef?.value;+ if (remoteItemId) {+ itemId = await mappingService.getEntityId(+ this.provider.id,+ remoteItemId,+ "item"+ );+ }++ // Resolve the Carbon account from the QBO AccountRef via the account+ // mapping (externalId → account.id)+ let accountId: string | null = null;+ const remoteAccountId =+ line.AccountBasedExpenseLineDetail?.AccountRef.value;+ if (remoteAccountId) {+ accountId = await mappingService.getEntityId(+ this.provider.id,+ remoteAccountId,+ "account"+ );+ }++ lines.push({+ id: line.Id ?? `temp-${index}`,+ description: line.Description ?? null,+ quantity: line.ItemBasedExpenseLineDetail?.Qty ?? 1,+ unitPrice: line.ItemBasedExpenseLineDetail?.UnitPrice ?? line.Amount,+ itemId,+ itemCode: null,+ accountId,+ accountNumber: null,+ taxPercent: null,+ taxAmount: null,+ totalAmount: line.Amount,+ purchaseOrderLineId: null+ });+ }++ return {+ invoiceId: remote.DocNumber ?? remote.Id,+ supplierExternalId: remote.VendorRef.value,+ status: deriveCarbonBillStatus({+ totalAmt: remote.TotalAmt,+ balance: remote.Balance,+ dueDate: remote.DueDate+ }),+ dateIssued: remote.TxnDate ?? null,+ dateDue: remote.DueDate ?? null,+ datePaid: remote.Balance === 0 ? new Date().toISOString() : null,+ totalAmount: remote.TotalAmt ?? 0,+ balance: remote.Balance ?? 0,+ lines,+ updatedAt:+ parseQboDate(remote.MetaData?.LastUpdatedTime)?.toISOString() ??+ new Date().toISOString()+ };+ }++ // =================================================================+ // 7. UPSERT LOCAL (update existing, or create from remote — Xero parity)+ // =================================================================++ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<Accounting.Bill>,+ remoteId: string+ ): Promise<string> {+ const existingLocalId = await this.getLocalId(remoteId);++ // Resolve supplier from the QBO VendorRef via the vendor mapping+ let supplierId: string | null = null;+ if (data.supplierExternalId) {+ const txMappingService = createMappingService(tx, this.companyId);+ supplierId = await txMappingService.getEntityId(+ this.provider.id,+ data.supplierExternalId,+ "vendor"+ );+ }++ if (existingLocalId) {+ await tx+ .updateTable("purchaseInvoice")+ .set({+ supplierId,+ status: data.status,+ dateIssued: data.dateIssued,+ dateDue: data.dateDue,+ datePaid: data.datePaid,+ totalAmount: data.totalAmount,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", existingLocalId)+ .where("companyId", "=", this.companyId)+ .execute();++ await this.upsertLines(tx, existingLocalId, data.lines ?? []);++ return existingLocalId;+ }++ // Create a new purchase invoice from QBO (Xero-syncer parity)+ if (!supplierId) {+ throw new Error(+ `Cannot create purchase invoice from QuickBooks Online: Vendor ${data.supplierExternalId} not found in Carbon. Sync the vendor first.`+ );+ }++ const defaultUser = await this.getDefaultUser(tx);+ if (!defaultUser) {+ throw new Error(+ `Cannot create purchase invoice from QuickBooks Online: No default user found for company ${this.companyId}`+ );+ }++ const supplierInteraction = await tx+ .insertInto("supplierInteraction")+ .values({+ companyId: this.companyId,+ supplierId+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ const sequenceResult = await sql<{ get_next_sequence: string }>`+ SELECT get_next_sequence('purchaseInvoice', ${this.companyId}) as get_next_sequence+ `.execute(tx);++ const invoiceId =+ sequenceResult.rows[0]?.get_next_sequence ??+ data.invoiceId ??+ `QBO-${remoteId.slice(0, 8)}`;++ const newInvoice = await tx+ .insertInto("purchaseInvoice")+ .values({+ invoiceId,+ companyId: this.companyId,+ createdBy: defaultUser,+ supplierId,+ supplierInteractionId: supplierInteraction.id,+ status: data.status ?? "Draft",+ dateIssued: data.dateIssued ?? null,+ dateDue: data.dateDue ?? null,+ datePaid: data.datePaid ?? null,+ currencyCode: data.currencyCode ?? "USD",+ exchangeRate: data.exchangeRate ?? 1,+ subtotal: data.subtotal ?? 0,+ totalTax: data.totalTax ?? 0,+ totalDiscount: data.totalDiscount ?? 0,+ totalAmount: data.totalAmount ?? 0,+ supplierReference: data.supplierReference ?? null+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ await this.upsertLines(tx, newInvoice.id, data.lines ?? []);++ return newInvoice.id;+ }++ /**+ * Default user for system-generated records: company group owner, then+ * first active employee (Xero-syncer parity).+ */+ private async getDefaultUser(tx: KyselyTx): Promise<string | null> {+ const group = await tx+ .selectFrom("company")+ .innerJoin("companyGroup", "companyGroup.id", "company.companyGroupId")+ .select("companyGroup.ownerId")+ .where("company.id", "=", this.companyId)+ .executeTakeFirst();++ if (group?.ownerId) {+ return group.ownerId;+ }++ const employee = await tx+ .selectFrom("employeeJob")+ .innerJoin("user", "user.id", "employeeJob.id")+ .select("employeeJob.id")+ .where("employeeJob.companyId", "=", this.companyId)+ .where("user.active", "=", true)+ .orderBy("user.createdAt", "asc")+ .limit(1)+ .executeTakeFirst();++ return employee?.id ?? null;+ }++ private async upsertLines(+ tx: KyselyTx,+ invoiceId: string,+ lines: Accounting.BillLine[]+ ): Promise<void> {+ await tx+ .deleteFrom("purchaseInvoiceLine")+ .where("invoiceId", "=", invoiceId)+ .execute();++ if (lines.length === 0) return;++ const invoice = await tx+ .selectFrom("purchaseInvoice")+ .select(["companyId", "createdBy", "exchangeRate"])+ .where("id", "=", invoiceId)+ .executeTakeFirstOrThrow();++ for (const line of lines) {+ await tx+ .insertInto("purchaseInvoiceLine")+ .values({+ invoiceId,+ companyId: invoice.companyId,+ createdBy: invoice.createdBy,+ description: line.description,+ quantity: line.quantity,+ unitPrice: line.unitPrice,+ supplierUnitPrice: line.unitPrice,+ itemId: line.itemId,+ accountId: line.accountId ?? null,+ taxPercent: line.taxPercent,+ taxAmount: line.taxAmount,+ supplierTaxAmount: line.taxAmount ?? 0,+ totalAmount: line.totalAmount,+ supplierExtendedPrice: line.totalAmount,+ exchangeRate: invoice.exchangeRate,+ invoiceLineType: line.itemId ? "Part" : "G/L Account",+ supplierShippingCost: 0+ })+ .execute();+ }+ }++ // =================================================================+ // 8. UPSERT REMOTE (create, or sparse update with SyncToken retry)+ // =================================================================++ protected async upsertRemote(+ data: Omit<Qbo.Bill, QboWriteOmit>,+ localId: string+ ): Promise<string> {+ const existingRemoteId = await this.getRemoteId(localId);++ if (!existingRemoteId) {+ const created = await this.qboProvider.createBill(data);+ this.rememberRemoteEntity(created);+ return created.Id;+ }++ const updated = await updateWithSyncTokenRetry({+ entityLabel: "bill",+ remoteId: existingRemoteId,+ fetchCurrent: () => this.qboProvider.getBill(existingRemoteId),+ update: (syncToken) =>+ this.qboProvider.updateBill({+ ...data,+ Id: existingRemoteId,+ SyncToken: syncToken+ })+ });+ this.rememberRemoteEntity(updated);+ return updated.Id;+ }++ protected async upsertRemoteBatch(+ data: Array<{+ localId: string;+ payload: Omit<Qbo.Bill, QboWriteOmit>;+ }>+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>();+ for (const { localId, payload } of data) {+ result.set(localId, await this.upsertRemote(payload, localId));+ }+ return result;+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/customer.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/customer.tsnew file mode 100644index 0000000000..d647454673--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/customer.ts@@ -0,0 +1,406 @@+import type { KyselyTx } from "@carbon/database/client";+import type { Accounting } from "../../../core/types";+import type { Qbo } from "../models";+import {+ escapeQboQueryValue,+ mapContactToQboContact,+ mapQboContactToLocal,+ QboEntitySyncer,+ type QboWriteOmit,+ toQboNameExistsError,+ updateWithSyncTokenRetry+} from "./shared";++/**+ * QboCustomerSyncer — Carbon customers ↔ QBO Customer objects.+ *+ * QBO keeps customers and vendors as SEPARATE objects (unlike Xero's+ * dual-flag Contact), so none of the Xero ContactSyncer's+ * IsCustomer/IsSupplier dual-mapping applies: this syncer reads and writes+ * the customer tables only, and the mapping rows live under entityType+ * "customer".+ *+ * Push (two-way, owner accounting per DEFAULT_SYNC_CONFIG): name →+ * DisplayName (100-char cap → structured NAME_TOO_LONG Warning; a+ * Duplicate Name Exists fault → structured NAME_EXISTS Warning — QBO's+ * name namespace is shared across customers, vendors and employees).+ * Updates are read-modify-write with the current SyncToken, sent sparse,+ * with ONE refetch-and-retry on a stale token. Pull maps+ * DisplayName/email/phone/BillAddr back onto the customer + its primary+ * contact person.+ */++// Row shape for customer queries with address and contact joins (mirrors+// the Xero ContactSyncer's row so the Contact build stays identical)+type CustomerRow = {+ id: string;+ name: string;+ companyId: string;+ taxId: string | null;+ phone: string | null;+ fax: string | null;+ website: string | null;+ currencyCode: string | null;+ updatedAt: string | null;+ locationName: string | null;+ addressLine1: string | null;+ addressLine2: string | null;+ city: string | null;+ postalCode: string | null;+ contactFirstName: string | null;+ contactLastName: string | null;+ contactEmail: string | null;+ contactMobilePhone: string | null;+ contactHomePhone: string | null;+ contactWorkPhone: string | null;+};++export class QboCustomerSyncer extends QboEntitySyncer<+ Accounting.Contact,+ Qbo.Customer+> {+ // =================================================================+ // 1. ID MAPPING — default implementation (entityType "customer")+ // =================================================================++ // =================================================================+ // 2. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.Contact | null> {+ const customers = await this.fetchCustomersByIds([id]);+ return customers.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.Contact>> {+ return this.fetchCustomersByIds(ids);+ }++ private async fetchCustomersByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.Contact>> {+ if (ids.length === 0) return new Map();++ const rows = await (this.database as any)+ .selectFrom("customer")+ .leftJoin("customerTax", "customerTax.customerId", "customer.id")+ .leftJoin(+ "customerLocation",+ "customerLocation.customerId",+ "customer.id"+ )+ .leftJoin("address", "address.id", "customerLocation.addressId")+ .leftJoin("customerContact", "customerContact.customerId", "customer.id")+ .leftJoin("contact", "contact.id", "customerContact.contactId")+ .select([+ "customer.id",+ "customer.name",+ "customer.companyId",+ "customerTax.taxId as taxId",+ "customer.phone",+ "customer.fax",+ "customer.website",+ "customer.currencyCode",+ "customer.updatedAt",+ "customerLocation.name as locationName",+ "address.addressLine1",+ "address.addressLine2",+ "address.city",+ "address.postalCode",+ "contact.firstName as contactFirstName",+ "contact.lastName as contactLastName",+ "contact.email as contactEmail",+ "contact.mobilePhone as contactMobilePhone",+ "contact.homePhone as contactHomePhone",+ "contact.workPhone as contactWorkPhone"+ ])+ .where("customer.id", "in", ids)+ .where("customer.companyId", "=", this.companyId)+ .execute();++ return this.groupAndTransformRows(rows as CustomerRow[]);+ }++ private groupAndTransformRows(+ rows: CustomerRow[]+ ): Map<string, Accounting.Contact> {+ const result = new Map<string, Accounting.Contact>();++ const groups = new Map<string, CustomerRow[]>();+ for (const row of rows) {+ const existing = groups.get(row.id) ?? [];+ existing.push(row);+ groups.set(row.id, existing);+ }++ for (const [id, groupRows] of groups) {+ const first = groupRows[0]!;+ const addresses = groupRows+ .filter((r) => r.addressLine1 || r.city)+ .map((r) => ({+ label: r.locationName ?? null,+ type: null,+ line1: r.addressLine1 ?? null,+ line2: r.addressLine2 ?? null,+ city: r.city ?? null,+ country: null,+ region: null,+ postalCode: r.postalCode ?? null+ }));++ result.set(id, {+ id: first.id,+ name: first.name,+ firstName: first.contactFirstName ?? "",+ lastName: first.contactLastName ?? "",+ companyId: first.companyId,+ email: first.contactEmail ?? undefined,+ website: first.website ?? null,+ taxId: first.taxId ?? null,+ currencyCode: first.currencyCode ?? "USD",+ balance: null,+ creditLimit: null,+ paymentTerms: null,+ updatedAt: first.updatedAt ?? new Date().toISOString(),+ workPhone: first.contactWorkPhone ?? first.phone ?? null,+ mobilePhone: first.contactMobilePhone ?? null,+ fax: first.fax ?? null,+ homePhone: first.contactHomePhone ?? null,+ isVendor: false,+ isCustomer: true,+ addresses,+ raw: first+ });+ }++ return result;+ }++ // =================================================================+ // 3. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Qbo.Customer | null> {+ const customer = await this.qboProvider.getCustomer(id);+ this.rememberRemoteEntity(customer);+ return customer;+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Qbo.Customer>> {+ const result = new Map<string, Qbo.Customer>();+ if (ids.length === 0) return result;++ const values = ids.map((id) => `'${escapeQboQueryValue(id)}'`).join(", ");+ const customers = await this.qboProvider.query<Qbo.Customer>(+ "Customer",+ `Id IN (${values})`+ );++ for (const customer of customers) {+ this.rememberRemoteEntity(customer);+ result.set(customer.Id, customer);+ }++ return result;+ }++ // =================================================================+ // 4. TRANSFORMATION (Carbon -> QBO)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.Contact+ ): Promise<Omit<Qbo.Customer, QboWriteOmit>> {+ return mapContactToQboContact(local, "customer");+ }++ // =================================================================+ // 5. TRANSFORMATION (QBO -> Carbon)+ // =================================================================++ protected async mapToLocal(+ remote: Qbo.Customer+ ): Promise<Partial<Accounting.Contact>> {+ return mapQboContactToLocal(remote, { isCustomer: true, isVendor: false });+ }++ // =================================================================+ // 6. UPSERT LOCAL+ // =================================================================++ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ remoteId: string+ ): Promise<string> {+ let existingLocalId = await this.getLocalId(remoteId);++ // Smart match: QBO DisplayNames and Carbon customer names are both+ // unique per company — match by name during backfill to avoid+ // duplicates when no mapping exists yet.+ if (!existingLocalId && data.name) {+ const match = await tx+ .selectFrom("customer")+ .select("id")+ .where("name", "=", data.name)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();+ existingLocalId = match?.id ?? null;+ }++ const customerId = await this.upsertCustomer(tx, data, existingLocalId);+ await this.upsertContactAndLink(tx, data, customerId);++ return customerId;+ }++ private async upsertCustomer(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ existingId: string | null+ ): Promise<string> {+ if (existingId) {+ await tx+ .updateTable("customer")+ .set({+ name: data.name,+ phone: data.workPhone,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", existingId)+ .execute();+ return existingId;+ }++ const result = await tx+ .insertInto("customer")+ .values({+ companyId: this.companyId,+ name: data.name!,+ phone: data.workPhone,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString()+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ return result.id;+ }++ private async upsertContactAndLink(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ customerId: string+ ): Promise<void> {+ const existingJunction = await tx+ .selectFrom("customerContact")+ .select("contactId")+ .where("customerId", "=", customerId)+ .executeTakeFirst();++ // QBO customers often only carry a DisplayName — fall back to it so the+ // contact person isn't blank (same fallback as the Xero syncer).+ const firstName = data.firstName || data.name || "";+ const lastName = data.lastName ?? "";++ if (existingJunction) {+ await tx+ .updateTable("contact")+ .set({+ email: data.email ?? null,+ firstName,+ lastName,+ workPhone: data.workPhone ?? null+ })+ .where("id", "=", existingJunction.contactId)+ .execute();+ return;+ }++ const contact = await tx+ .insertInto("contact")+ .values({+ companyId: this.companyId,+ email: data.email ?? null,+ firstName,+ lastName,+ workPhone: data.workPhone ?? null,+ isCustomer: true+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ await tx+ .insertInto("customerContact")+ .values({+ companyId: this.companyId,+ customerId,+ contactId: contact.id+ })+ .execute();+ }++ // =================================================================+ // 7. UPSERT REMOTE (create, or sparse update with SyncToken retry)+ // =================================================================++ protected async upsertRemote(+ data: Omit<Qbo.Customer, QboWriteOmit>,+ localId: string+ ): Promise<string> {+ let existingRemoteId = await this.getRemoteId(localId);++ // Smart match: QBO DisplayNames are unique — search before creating so+ // backfills against a populated QBO company link instead of colliding.+ if (!existingRemoteId && data.DisplayName) {+ existingRemoteId = await this.findRemoteCustomerByName(data.DisplayName);+ }++ try {+ if (!existingRemoteId) {+ const created = await this.qboProvider.createCustomer(data);+ this.rememberRemoteEntity(created);+ return created.Id;+ }++ const remoteId = existingRemoteId;+ const updated = await updateWithSyncTokenRetry({+ entityLabel: "customer",+ remoteId,+ fetchCurrent: () => this.qboProvider.getCustomer(remoteId),+ update: (syncToken) =>+ this.qboProvider.updateCustomer({+ ...data,+ Id: remoteId,+ SyncToken: syncToken+ })+ });+ this.rememberRemoteEntity(updated);+ return updated.Id;+ } catch (error) {+ const nameExists = toQboNameExistsError(error, {+ entityLabel: "customer",+ name: data.DisplayName+ });+ if (nameExists) throw nameExists;+ throw error;+ }+ }++ private async findRemoteCustomerByName(name: string): Promise<string | null> {+ const matches = await this.qboProvider.query<Qbo.Customer>(+ "Customer",+ `DisplayName = '${escapeQboQueryValue(name)}'`+ );++ const match = matches[0];+ if (!match) return null;++ this.rememberRemoteEntity(match);+ return match.Id;+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice.tsnew file mode 100644index 0000000000..5083c202fd--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/invoice.ts@@ -0,0 +1,509 @@+import type { KyselyTx } from "@carbon/database/client";+import { createMappingService } from "../../../core/external-mapping";+import { roundCurrency } from "../../../core/posting";+import {+ type Accounting,+ BaseEntitySyncer,+ type ShouldSyncContext+} from "../../../core/types";+import { parseQboDate, type Qbo } from "../models";+import type { QboProvider } from "../provider";+import {+ buildQboDocNumberFields,+ type QboDocNumberSource,+ type QboWriteOmit,+ updateWithSyncTokenRetry+} from "./shared";++/**+ * QboSalesInvoiceSyncer — Carbon sales invoices ↔ QBO Invoice objects+ * (two-way, owner accounting per DEFAULT_SYNC_CONFIG; entityType+ * "invoice" like the Xero counterpart).+ *+ * Push: only posted invoices (same status gate as Xero's+ * SalesInvoiceSyncer). Customer and line items are JIT-synced via+ * ensureDependencySynced before the document; lines become+ * SalesItemLineDetail with ItemRef (the item's QBO id) + Qty/UnitPrice.+ * DocNumber carries the Carbon readable id when it fits QBO's 21-char cap;+ * otherwise PrivateNote carries it ("Carbon <id>"), QBO auto-numbers, and+ * the mapping metadata records which happened (`docNumberSource`).+ *+ * Pull mirrors the Xero counterpart's field set: dates and amounts come+ * back onto the Carbon document, with status derived from Balance/TotalAmt+ * (QBO invoices carry no status enum). Update-only — invoices are never+ * created from QBO.+ */++// Only posted invoices are pushed (behavior copied from the Xero syncer)+const SYNCABLE_STATUSES: Accounting.SalesInvoice["status"][] = [+ "Pending",+ "Submitted",+ "Partially Paid",+ "Paid",+ "Overdue"+];++// Row shapes for sales invoice queries (mirror the Xero syncer's)+type InvoiceRow = {+ id: string;+ invoiceId: string;+ companyId: string;+ customerId: string;+ status: Accounting.SalesInvoice["status"];+ currencyCode: string;+ exchangeRate: number;+ dateIssued: string | null;+ dateDue: string | null;+ datePaid: string | null;+ customerReference: string | null;+ subtotal: number;+ totalTax: number;+ totalDiscount: number;+ totalAmount: number;+ balance: number;+ updatedAt: string | null;+};++type InvoiceLineRow = {+ id: string;+ invoiceId: string;+ invoiceLineType: string;+ itemId: string | null;+ description: string | null;+ quantity: number;+ unitPrice: number;+ taxPercent: number;+ itemReadableIdWithRevision: string | null;+};++/**+ * Derive the Carbon invoice status from QBO's Balance/TotalAmt (QBO has no+ * invoice status enum). Pure — exported for tests.+ */+export function deriveCarbonInvoiceStatus(+ totalAmt: number | undefined,+ balance: number | undefined+): Accounting.SalesInvoice["status"] | undefined {+ if (balance === undefined) return undefined;+ if (balance <= 0) return "Paid";+ if (totalAmt !== undefined && balance < totalAmt) return "Partially Paid";+ return "Submitted";+}++/**+ * Build QBO SalesItemLineDetail lines from Carbon invoice lines. Pure —+ * exported for tests. `itemRemoteIds` maps Carbon itemId → QBO item id+ * (resolved by ensureDependencySynced before mapping); lines without an+ * item ship without an ItemRef.+ */+export function buildQboInvoiceLines(+ lines: Accounting.SalesInvoiceLine[],+ itemRemoteIds: ReadonlyMap<string, string>+): Array<Omit<Qbo.InvoiceLine, "Id">> {+ return lines.map((line) => {+ const remoteItemId = line.itemId ? itemRemoteIds.get(line.itemId) : null;++ return {+ Description: line.description ?? undefined,+ Amount: roundCurrency(line.quantity * line.unitPrice),+ DetailType: "SalesItemLineDetail",+ SalesItemLineDetail: {+ ItemRef: remoteItemId ? { value: remoteItemId } : undefined,+ Qty: line.quantity,+ UnitPrice: line.unitPrice+ }+ };+ });+}++export class QboSalesInvoiceSyncer extends BaseEntitySyncer<+ Accounting.SalesInvoice,+ Qbo.Invoice,+ QboWriteOmit+> {+ // Bookkeeping for linkEntities: concurrency metadata per remote id and+ // the DocNumber carrier per local id (recorded during mapToRemote)+ private remoteMetaById = new Map<+ string,+ { syncToken?: string; lastUpdatedTime?: string }+ >();+ private docNumberSourceByLocalId = new Map<string, QboDocNumberSource>();++ private get qboProvider(): QboProvider {+ return this.provider as QboProvider;+ }++ private rememberRemoteEntity(+ remote: Pick<Qbo.Invoice, "Id" | "SyncToken" | "MetaData"> | null+ ): void {+ if (!remote?.Id) return;+ this.remoteMetaById.set(remote.Id, {+ syncToken: remote.SyncToken,+ lastUpdatedTime: remote.MetaData?.LastUpdatedTime+ });+ }++ // =================================================================+ // 1. ID MAPPING — mapping metadata records the DocNumber carrier+ // =================================================================++ protected async linkEntities(+ tx: KyselyTx,+ localId: string,+ remoteId: string,+ remoteUpdatedAt?: Date+ ): Promise<void> {+ const seen = this.remoteMetaById.get(remoteId);+ const docNumberSource = this.docNumberSourceByLocalId.get(localId);++ const metadata: Record<string, unknown> = {};+ if (seen?.syncToken !== undefined) metadata.syncToken = seen.syncToken;+ if (docNumberSource) metadata.docNumberSource = docNumberSource;++ const txMappingService = createMappingService(tx, this.companyId);+ await txMappingService.link(+ "invoice",+ localId,+ this.provider.id,+ remoteId,+ {+ remoteUpdatedAt:+ remoteUpdatedAt ?? parseQboDate(seen?.lastUpdatedTime) ?? undefined,+ ...(Object.keys(metadata).length > 0 ? { metadata } : {})+ }+ );++ // Also update updatedAt on salesInvoice (Xero-syncer parity)+ await tx+ .updateTable("salesInvoice")+ .set({ updatedAt: new Date().toISOString() })+ .where("id", "=", localId)+ .execute();+ }++ // =================================================================+ // 2. TIMESTAMP EXTRACTION+ // =================================================================++ protected getRemoteUpdatedAt(remote: Qbo.Invoice): Date | null {+ return parseQboDate(remote.MetaData?.LastUpdatedTime);+ }++ // =================================================================+ // 3. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.SalesInvoice | null> {+ const invoices = await this.fetchInvoicesByIds([id]);+ return invoices.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.SalesInvoice>> {+ return this.fetchInvoicesByIds(ids);+ }++ private async fetchInvoicesByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.SalesInvoice>> {+ if (ids.length === 0) return new Map();++ const invoiceRows = await this.database+ .selectFrom("salesInvoice")+ // `balance` is derived and lives only on the `salesInvoices` view+ .leftJoin("salesInvoices", "salesInvoices.id", "salesInvoice.id")+ .select([+ "salesInvoice.id",+ "salesInvoice.invoiceId",+ "salesInvoice.companyId",+ "salesInvoice.customerId",+ "salesInvoice.status",+ "salesInvoice.currencyCode",+ "salesInvoice.exchangeRate",+ "salesInvoice.dateIssued",+ "salesInvoice.dateDue",+ "salesInvoice.datePaid",+ "salesInvoice.customerReference",+ "salesInvoice.subtotal",+ "salesInvoice.totalTax",+ "salesInvoice.totalDiscount",+ "salesInvoice.totalAmount",+ "salesInvoices.balance",+ "salesInvoice.updatedAt"+ ])+ .where("salesInvoice.id", "in", ids)+ .where("salesInvoice.companyId", "=", this.companyId)+ .execute();++ if (invoiceRows.length === 0) return new Map();++ const lineRows = await this.database+ .selectFrom("salesInvoiceLine")+ .leftJoin("item", "item.id", "salesInvoiceLine.itemId")+ .select([+ "salesInvoiceLine.id",+ "salesInvoiceLine.invoiceId",+ "salesInvoiceLine.invoiceLineType",+ "salesInvoiceLine.itemId",+ "salesInvoiceLine.description",+ "salesInvoiceLine.quantity",+ "salesInvoiceLine.unitPrice",+ "salesInvoiceLine.taxPercent",+ "item.readableIdWithRevision as itemReadableIdWithRevision"+ ])+ .where(+ "salesInvoiceLine.invoiceId",+ "in",+ invoiceRows.map((r) => r.id)+ )+ .execute();++ const linesByInvoiceId = new Map<string, InvoiceLineRow[]>();+ for (const line of lineRows as InvoiceLineRow[]) {+ const existing = linesByInvoiceId.get(line.invoiceId) ?? [];+ existing.push(line);+ linesByInvoiceId.set(line.invoiceId, existing);+ }++ const result = new Map<string, Accounting.SalesInvoice>();+ for (const row of invoiceRows as InvoiceRow[]) {+ const lines = linesByInvoiceId.get(row.id) ?? [];++ result.set(row.id, {+ id: row.id,+ invoiceId: row.invoiceId,+ companyId: row.companyId,+ customerId: row.customerId,+ customerExternalId: null, // Resolved during mapToRemote+ status: row.status,+ currencyCode: row.currencyCode,+ exchangeRate: Number(row.exchangeRate) || 1,+ dateIssued: row.dateIssued,+ dateDue: row.dateDue,+ datePaid: row.datePaid,+ customerReference: row.customerReference,+ subtotal: Number(row.subtotal) || 0,+ totalTax: Number(row.totalTax) || 0,+ totalDiscount: Number(row.totalDiscount) || 0,+ totalAmount: Number(row.totalAmount) || 0,+ balance: Number(row.balance) || 0,+ lines: lines.map((line) => {+ const quantity = Number(line.quantity) || 0;+ const unitPrice = Number(line.unitPrice) || 0;+ return {+ id: line.id,+ invoiceLineType: line.invoiceLineType,+ itemId: line.itemId,+ itemCode: line.itemReadableIdWithRevision,+ description: line.description,+ quantity,+ unitPrice,+ taxPercent: Number(line.taxPercent) || 0,+ lineAmount: quantity * unitPrice+ };+ }),+ updatedAt: row.updatedAt ?? new Date().toISOString(),+ raw: row+ });+ }++ return result;+ }++ // =================================================================+ // 4. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Qbo.Invoice | null> {+ const invoice = await this.qboProvider.getInvoice(id);+ this.rememberRemoteEntity(invoice);+ return invoice;+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Qbo.Invoice>> {+ const result = new Map<string, Qbo.Invoice>();+ for (const id of ids) {+ const invoice = await this.fetchRemote(id);+ if (invoice) result.set(invoice.Id, invoice);+ }+ return result;+ }++ // =================================================================+ // 5. TRANSFORMATION (Carbon -> QBO)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.SalesInvoice+ ): Promise<Omit<Qbo.Invoice, QboWriteOmit>> {+ // JIT dependencies: customer, then every line item, before the document+ const customerRemoteId = await this.ensureDependencySynced(+ "customer",+ local.customerId+ );++ const itemRemoteIds = new Map<string, string>();+ for (const line of local.lines) {+ if (line.itemId && !itemRemoteIds.has(line.itemId)) {+ itemRemoteIds.set(+ line.itemId,+ await this.ensureDependencySynced("item", line.itemId)+ );+ }+ }++ // Due date: use dateDue if provided, otherwise default to Net 30+ // (Xero-syncer parity)+ let dueDate = local.dateDue;+ if (!dueDate && local.dateIssued) {+ const issued = new Date(local.dateIssued);+ issued.setDate(issued.getDate() + 30);+ dueDate = issued.toISOString().split("T")[0];+ } else if (!dueDate) {+ const now = new Date();+ now.setDate(now.getDate() + 30);+ dueDate = now.toISOString().split("T")[0];+ }++ const docNumber = buildQboDocNumberFields(local.invoiceId);+ this.docNumberSourceByLocalId.set(local.id, docNumber.source);++ return {+ DocNumber: docNumber.DocNumber,+ PrivateNote: docNumber.PrivateNote,+ TxnDate: local.dateIssued ?? undefined,+ DueDate: dueDate,+ CustomerRef: { value: customerRemoteId },+ Line: buildQboInvoiceLines(local.lines, itemRemoteIds)+ };+ }++ // =================================================================+ // 6. TRANSFORMATION (QBO -> Carbon)+ // =================================================================++ protected async mapToLocal(+ remote: Qbo.Invoice+ ): Promise<Partial<Accounting.SalesInvoice>> {+ const lines: Accounting.SalesInvoiceLine[] = (remote.Line ?? [])+ .filter((line) => line.DetailType === "SalesItemLineDetail")+ .map((line, index) => ({+ id: line.Id ?? `line-${index}`,+ invoiceLineType: "Part",+ itemId: null, // Resolved by ItemRef mapping during upsertLocal if needed+ itemCode: null,+ description: line.Description ?? null,+ quantity: line.SalesItemLineDetail?.Qty ?? 0,+ unitPrice: line.SalesItemLineDetail?.UnitPrice ?? 0,+ taxPercent: 0,+ lineAmount: line.Amount+ }));++ return {+ status: deriveCarbonInvoiceStatus(remote.TotalAmt, remote.Balance),+ dateIssued: remote.TxnDate ?? null,+ dateDue: remote.DueDate ?? null,+ totalAmount: remote.TotalAmt ?? 0,+ balance: remote.Balance ?? 0,+ lines+ };+ }++ // =================================================================+ // 7. UPSERT LOCAL (Update existing only)+ // =================================================================++ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<Accounting.SalesInvoice>,+ remoteId: string+ ): Promise<string> {+ const existingLocalId = await this.getLocalId(remoteId);++ if (!existingLocalId) {+ throw new Error(+ `Cannot create new invoices from QuickBooks Online. Invoice with remote ID ${remoteId} not found locally.`+ );+ }++ await tx+ .updateTable("salesInvoice")+ .set({+ status: data.status,+ dateIssued: data.dateIssued,+ dateDue: data.dateDue,+ totalAmount: data.totalAmount,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", existingLocalId)+ .execute();++ // Line items are not updated from QBO to preserve Carbon's line+ // structure (Xero-syncer parity)++ return existingLocalId;+ }++ // =================================================================+ // 8. UPSERT REMOTE (create, or sparse update with SyncToken retry)+ // =================================================================++ protected async upsertRemote(+ data: Omit<Qbo.Invoice, QboWriteOmit>,+ localId: string+ ): Promise<string> {+ const existingRemoteId = await this.getRemoteId(localId);++ if (!existingRemoteId) {+ const created = await this.qboProvider.createInvoice(data);+ this.rememberRemoteEntity(created);+ return created.Id;+ }++ const updated = await updateWithSyncTokenRetry({+ entityLabel: "invoice",+ remoteId: existingRemoteId,+ fetchCurrent: () => this.qboProvider.getInvoice(existingRemoteId),+ update: (syncToken) =>+ this.qboProvider.updateInvoice({+ ...data,+ Id: existingRemoteId,+ SyncToken: syncToken+ })+ });+ this.rememberRemoteEntity(updated);+ return updated.Id;+ }++ protected async upsertRemoteBatch(+ data: Array<{+ localId: string;+ payload: Omit<Qbo.Invoice, QboWriteOmit>;+ }>+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>();+ for (const { localId, payload } of data) {+ result.set(localId, await this.upsertRemote(payload, localId));+ }+ return result;+ }++ // =================================================================+ // 9. SHOULD SYNC (same gate as the Xero counterpart)+ // =================================================================++ protected shouldSync(+ context: ShouldSyncContext<Accounting.SalesInvoice, Qbo.Invoice>+ ): boolean | string {+ if (context.direction === "push" && context.localEntity) {+ if (!SYNCABLE_STATUSES.includes(context.localEntity.status)) {+ return `Invoice must be posted before syncing (current status: ${context.localEntity.status})`;+ }+ }++ return true;+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/item.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/item.tsnew file mode 100644index 0000000000..77a1615f71--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/item.ts@@ -0,0 +1,460 @@+import type { KyselyTx } from "@carbon/database/client";+import { JournalEntrySyncError } from "../../../core/posting";+import type { Accounting } from "../../../core/types";+import type { Qbo, QboCreatePayload } from "../models";+import {+ escapeQboQueryValue,+ loadQboAccountRefsById,+ QBO_NAME_MAX_LENGTH,+ QboEntitySyncer,+ type QboWriteOmit,+ qboNameTooLongError,+ toQboNameExistsError,+ updateWithSyncTokenRetry+} from "./shared";++/**+ * QboItemSyncer — push-only (owner carbon, direction push-to-accounting per+ * DEFAULT_SYNC_CONFIG): Carbon items become QBO Items typed `Service`+ * (Carbon item type "Service") or `NonInventory` (every physical type) —+ * NEVER `Inventory`: QBO item-level quantity tracking stays off so the+ * posting sync's inventory journals are the single source of COGS+ * (double-COGS guard).+ *+ * QBO `Name` is the unique item key (100-char cap → structured+ * NAME_TOO_LONG Warning) and maps from Carbon's unique item code+ * (readableIdWithRevision) — the same role Xero's Item.Code plays.+ *+ * IncomeAccountRef/ExpenseAccountRef resolve through the account-mapping+ * service (entityType "account", integration "quickbooks" — mapping+ * externalId is the QBO account id) from the company's accountDefault+ * sales / cost-of-goods-sold accounts (items carry no per-item posting+ * accounts since the posting-group matrix was dropped). Unmapped accounts+ * → structured UNMAPPED_ACCOUNTS Warning, same errorCode as the journal+ * pre-flight.+ */++// Row shape for item queries with cost/price joins (mirrors Xero's)+type ItemRow = {+ id: string;+ readableId: string;+ readableIdWithRevision: string | null;+ name: string;+ description: string | null;+ companyId: string | null;+ type: "Part" | "Material" | "Tool" | "Service" | "Consumable" | "Fixture";+ unitOfMeasureCode: string | null;+ replenishmentSystem: "Buy" | "Make" | "Buy and Make";+ itemTrackingType: string;+ updatedAt: string | null;+ unitCost: number | null;+ unitSalePrice: number | null;+};++/**+ * Map a Carbon item to the QBO Item write payload. Pure — exported for+ * tests.+ *+ * - `incomeAccountId`/`expenseAccountId` are the Carbon account.ids the+ * refs resolve from (accountDefault salesAccount /+ * costOfGoodsSoldAccount); `accountRefsById` maps Carbon account.id →+ * QBO AccountRef (mapping externalId).+ * - Throws NAME_TOO_LONG (Warning) when the code exceeds QBO's 100-char+ * Name cap — no silent truncation.+ * - Throws UNMAPPED_ACCOUNTS (Warning) when a required account is missing+ * or has no mapping: income is always required (all items are sellable),+ * expense only for purchased items.+ */+export function mapItemToQboItem(args: {+ item: Accounting.Item;+ accountRefsById: ReadonlyMap<string, Qbo.Ref>;+ incomeAccountId: string | null;+ expenseAccountId: string | null;+}): QboCreatePayload<Qbo.Item> {+ const { item } = args;++ if (item.code.length > QBO_NAME_MAX_LENGTH) {+ throw qboNameTooLongError({ entityLabel: "item", name: item.code });+ }++ const incomeRef = args.incomeAccountId+ ? args.accountRefsById.get(args.incomeAccountId)+ : undefined;+ const expenseRef = args.expenseAccountId+ ? args.accountRefsById.get(args.expenseAccountId)+ : undefined;++ const unmappedAccountIds: string[] = [];+ const missingDefaults: string[] = [];++ if (item.isSold) {+ if (!args.incomeAccountId) {+ missingDefaults.push("salesAccount");+ } else if (!incomeRef) {+ unmappedAccountIds.push(args.incomeAccountId);+ }+ }++ if (item.isPurchased) {+ if (!args.expenseAccountId) {+ missingDefaults.push("costOfGoodsSoldAccount");+ } else if (!expenseRef) {+ unmappedAccountIds.push(args.expenseAccountId);+ }+ }++ if (unmappedAccountIds.length > 0 || missingDefaults.length > 0) {+ const parts: string[] = [];+ if (unmappedAccountIds.length > 0) {+ parts.push(+ `${unmappedAccountIds.length} default posting account(s) have no QuickBooks Online account mapping`+ );+ }+ if (missingDefaults.length > 0) {+ parts.push(+ `company account defaults are missing: ${missingDefaults.join(", ")}`+ );+ }+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync item ${item.code}: ${parts.join(+ "; "+ )}. Map the account(s) on the integration settings page, then retry.`,+ warning: true,+ metadata: {+ itemId: item.id,+ unmappedAccountIds,+ ...(missingDefaults.length > 0 ? { missingDefaults } : {})+ }+ });+ }++ return {+ Name: item.code,+ Description: (item.description ?? item.name).slice(0, 4000),+ // NEVER "Inventory" — QBO quantity tracking stays off (double-COGS guard)+ Type: item.type === "Service" ? "Service" : "NonInventory",+ Active: true,+ UnitPrice: item.unitSalePrice,+ PurchaseCost: item.unitCost,+ IncomeAccountRef: item.isSold ? incomeRef : undefined,+ ExpenseAccountRef: item.isPurchased ? expenseRef : undefined+ };+}++export class QboItemSyncer extends QboEntitySyncer<Accounting.Item, Qbo.Item> {+ // Cached per instance — a drain reuses one syncer across its claimed+ // operations, so mappings and account defaults are fetched at most once+ private accountRefsByIdPromise?: Promise<Map<string, Qbo.Ref>>;+ private defaultItemAccountsPromise?: Promise<{+ incomeAccountId: string | null;+ expenseAccountId: string | null;+ }>;++ // =================================================================+ // 1. ACCOUNT RESOLUTION (account-mapping service, journal-syncer path)+ // =================================================================++ /**+ * Carbon account.id → QBO AccountRef from the account-mapping rows+ * (entityType "account") — the journal syncer's resolution path, cached+ * per instance.+ */+ private getAccountRefsById(): Promise<Map<string, Qbo.Ref>> {+ if (!this.accountRefsByIdPromise) {+ this.accountRefsByIdPromise = loadQboAccountRefsById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountRefsByIdPromise;+ }++ /**+ * The item posting defaults: accountDefault.salesAccount (income) and+ * accountDefault.costOfGoodsSoldAccount (expense). Items carry no+ * per-item posting accounts, so these are the source the refs resolve+ * from.+ */+ private getDefaultItemAccounts(): Promise<{+ incomeAccountId: string | null;+ expenseAccountId: string | null;+ }> {+ if (!this.defaultItemAccountsPromise) {+ this.defaultItemAccountsPromise = (async () => {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select(["salesAccount", "costOfGoodsSoldAccount"])+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return {+ incomeAccountId: defaults?.salesAccount ?? null,+ expenseAccountId: defaults?.costOfGoodsSoldAccount ?? null+ };+ })();+ }+ return this.defaultItemAccountsPromise;+ }++ // =================================================================+ // 2. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.Item | null> {+ const items = await this.fetchItemsByIds([id]);+ return items.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.Item>> {+ return this.fetchItemsByIds(ids);+ }++ private async fetchItemsByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.Item>> {+ if (ids.length === 0) return new Map();++ const rows = await this.database+ .selectFrom("item")+ .leftJoin("itemCost", "itemCost.itemId", "item.id")+ .leftJoin("itemUnitSalePrice", "itemUnitSalePrice.itemId", "item.id")+ .select([+ "item.id",+ "item.readableId",+ "item.readableIdWithRevision",+ "item.name",+ "item.description",+ "item.companyId",+ "item.type",+ "item.unitOfMeasureCode",+ "item.replenishmentSystem",+ "item.itemTrackingType",+ "item.updatedAt",+ "itemCost.unitCost",+ "itemUnitSalePrice.unitSalePrice"+ ])+ .where("item.id", "in", ids)+ .where("item.companyId", "=", this.companyId)+ .execute();++ const result = new Map<string, Accounting.Item>();+ for (const row of rows as ItemRow[]) {+ const isPurchased =+ row.replenishmentSystem === "Buy" ||+ row.replenishmentSystem === "Buy and Make";++ result.set(row.id, {+ id: row.id,+ code: row.readableIdWithRevision ?? row.readableId,+ name: row.name,+ description: row.description,+ companyId: row.companyId!,+ type: row.type,+ unitOfMeasureCode: row.unitOfMeasureCode,+ unitCost: Number(row.unitCost) || 0,+ unitSalePrice: Number(row.unitSalePrice) || 0,+ isPurchased,+ isSold: true, // Assume all items can be sold (Xero parity)+ isTrackedAsInventory: row.itemTrackingType !== "None",+ updatedAt: row.updatedAt ?? new Date().toISOString(),+ raw: row+ });+ }++ return result;+ }++ // =================================================================+ // 3. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Qbo.Item | null> {+ const item = await this.qboProvider.getItem(id);+ this.rememberRemoteEntity(item);+ return item;+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Qbo.Item>> {+ const result = new Map<string, Qbo.Item>();+ if (ids.length === 0) return result;++ const values = ids.map((id) => `'${escapeQboQueryValue(id)}'`).join(", ");+ const items = await this.qboProvider.query<Qbo.Item>(+ "Item",+ `Id IN (${values})`+ );++ for (const item of items) {+ this.rememberRemoteEntity(item);+ result.set(item.Id, item);+ }++ return result;+ }++ // =================================================================+ // 4. TRANSFORMATION (Carbon -> QBO) with account resolution+ // =================================================================++ protected async mapToRemote(+ local: Accounting.Item+ ): Promise<Omit<Qbo.Item, QboWriteOmit>> {+ const accountRefsById = await this.getAccountRefsById();+ const { incomeAccountId, expenseAccountId } =+ await this.getDefaultItemAccounts();++ return mapItemToQboItem({+ item: local,+ accountRefsById,+ incomeAccountId,+ expenseAccountId+ });+ }++ // =================================================================+ // 5. TRANSFORMATION (QBO -> Carbon) - Update only (Carbon owns items)+ // =================================================================++ protected async mapToLocal(+ remote: Qbo.Item+ ): Promise<Partial<Accounting.Item>> {+ return {+ // QBO Name carries the Carbon item code (see mapItemToQboItem)+ code: remote.Name,+ description: remote.Description ?? null,+ unitCost: remote.PurchaseCost ?? 0,+ unitSalePrice: remote.UnitPrice ?? 0+ };+ }++ // =================================================================+ // 6. UPSERT LOCAL (Update existing only - Carbon is source of truth)+ // =================================================================++ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<Accounting.Item>,+ remoteId: string+ ): Promise<string> {+ let existingLocalId = await this.getLocalId(remoteId);++ // Smart match: QBO Item.Name carries the Carbon item code+ // (readableIdWithRevision or readableId).+ if (!existingLocalId && data.code) {+ const match = await tx+ .selectFrom("item")+ .select("id")+ .where("companyId", "=", this.companyId)+ .where((eb) =>+ eb.or([+ eb("readableIdWithRevision" as any, "=", data.code!),+ eb("readableId", "=", data.code!)+ ])+ )+ .executeTakeFirst();+ existingLocalId = match?.id ?? null;+ }++ if (!existingLocalId) {+ throw new Error(+ `Cannot create new items from QuickBooks Online. Item with remote ID ${remoteId} (name: ${+ data.code ?? "unknown"+ }) not found locally.`+ );+ }++ // Update the item description only — QBO Name is the Carbon code, not+ // the item's display name+ await tx+ .updateTable("item")+ .set({+ description: data.description,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", existingLocalId)+ .execute();++ if (data.unitCost !== undefined) {+ await tx+ .updateTable("itemCost")+ .set({ unitCost: data.unitCost })+ .where("itemId", "=", existingLocalId)+ .execute();+ }++ if (data.unitSalePrice !== undefined) {+ await tx+ .updateTable("itemUnitSalePrice")+ .set({ unitSalePrice: data.unitSalePrice })+ .where("itemId", "=", existingLocalId)+ .execute();+ }++ return existingLocalId;+ }++ // =================================================================+ // 7. UPSERT REMOTE (create, or sparse update with SyncToken retry)+ // =================================================================++ protected async upsertRemote(+ data: Omit<Qbo.Item, QboWriteOmit>,+ localId: string+ ): Promise<string> {+ let existingRemoteId = await this.getRemoteId(localId);++ // Smart match: QBO item names are unique — search by Name (the Carbon+ // code) before creating.+ if (!existingRemoteId && data.Name) {+ existingRemoteId = await this.findRemoteItemByName(data.Name);+ }++ try {+ if (!existingRemoteId) {+ const created = await this.qboProvider.createItem(data);+ this.rememberRemoteEntity(created);+ return created.Id;+ }++ const remoteId = existingRemoteId;+ const updated = await updateWithSyncTokenRetry({+ entityLabel: "item",+ remoteId,+ fetchCurrent: () => this.qboProvider.getItem(remoteId),+ update: (syncToken) =>+ this.qboProvider.updateItem({+ ...data,+ Id: remoteId,+ SyncToken: syncToken+ })+ });+ this.rememberRemoteEntity(updated);+ return updated.Id;+ } catch (error) {+ const nameExists = toQboNameExistsError(error, {+ entityLabel: "item",+ name: data.Name+ });+ if (nameExists) throw nameExists;+ throw error;+ }+ }++ private async findRemoteItemByName(name: string): Promise<string | null> {+ const matches = await this.qboProvider.query<Qbo.Item>(+ "Item",+ `Name = '${escapeQboQueryValue(name)}'`+ );++ const match = matches[0];+ if (!match) return null;++ this.rememberRemoteEntity(match);+ return match.Id;+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/journal-entry.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/journal-entry.tsnew file mode 100644index 0000000000..06f61290dd--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/journal-entry.ts@@ -0,0 +1,875 @@+import type { KyselyTx } from "@carbon/database/client";+import {+ buildDimensionValueMappingEntityId,+ buildDimensionValueMappingLookup,+ ensureDimensionValueExternalIds,+ getDimensionValueMappings,+ loadJournalLineDimensions,+ resolveDimensionValueLabels,+ upsertDimensionValueMapping+} from "../../../core/dimension-mapping";+import type { PostingSyncDimensionSlot } from "../../../core/models";+import {+ getPostingSyncSourceTypeSkipReason,+ JournalEntrySyncError,+ type PostingSyncSettings,+ parseJournalEntrySyncEntityId,+ resolvePostingSyncSettings,+ roundCurrency,+ runJournalEntryPreflight,+ toDebitSignedAmount,+ toPostingDateString+} from "../../../core/posting";+import {+ type Accounting,+ BaseEntitySyncer,+ type BatchSyncResult,+ type ShouldSyncContext,+ type SyncResult+} from "../../../core/types";+import { withTriggersDisabled } from "../../../core/utils";+import { parseQboDate, type Qbo, type QboCreatePayload } from "../models";+import {+ isQboAccountPeriodClosedError,+ QBO_DIMENSION_TARGET_CLASS,+ QBO_DIMENSION_TARGET_DEPARTMENT,+ QBO_FAULT_CODES,+ type QboProvider+} from "../provider";+import {+ buildQboDocNumberFields,+ loadQboAccountRefsById,+ type QboWriteOmit+} from "./shared";++/**+ * QboJournalEntrySyncer — pushes Posted Carbon journals (`journal` ++ * `journalLine`) to QuickBooks Online as JournalEntry objects. PUSH-ONLY:+ * pull methods return descriptive not-supported errors. Mirrors the Xero+ * JournalEntrySyncer's structure; only `mapToRemote` (unsigned lines with+ * PostingType) and the lock-date source (manual settings only) differ.+ *+ * Sign convention: Carbon `journalLine.amount` is signed (positive = debit,+ * negative = credit); QBO journal lines are UNSIGNED — `Amount` =+ * abs(amount) and the side lives in `JournalEntryLineDetail.PostingType`+ * ("Debit" for positive Carbon amounts, "Credit" otherwise). TODO: verify+ * the mapping against a real/sandbox QBO journal entry before enabling for+ * production companies (Task C10) — if QBO rejects or books sides+ * inverted, document and invert.+ *+ * Reversal contract (same as Xero): when a sync operation carries+ * `metadata.reversal: true`, the drain pushes entity id+ * `"<journal.id>:reversal"` (see getJournalEntrySyncEntityId). The syncer+ * then loads the ORIGINAL journal, requires status `Reversed` plus an+ * existing original mapping, negates every signed amount (flipping each+ * line's PostingType), uses PrivateNote `"Carbon reversal of+ * <journalEntryId>"`, and stores the reversal's mapping under the suffixed+ * entity id — the original mapping is never touched.+ *+ * Failure channel: pre-flight failures (UNMAPPED_ACCOUNTS,+ * CONTROL_ACCOUNT_LINE, PERIOD_LOCKED park, UNBALANCED_JOURNAL) throw+ * JournalEntrySyncError inside the mapping step; pushToAccounting converts+ * them to `SyncResult.error` carrying the structured+ * JournalEntrySyncFailure object. The drain detects them with+ * isJournalEntrySyncFailure and records them via failOperation({+ * errorCode, errorMessage, warning }). shouldSync gates (wrong status,+ * disabled posting sync, excluded sourceType, already mapped) keep the+ * skip-reason-string channel (`SyncResult.status === "skipped"`).+ *+ * Closed books: the pre-flight lock date comes ONLY from the manually+ * captured `settings.lockDate`+ * (companyIntegration.metadata.settings.postingSync) — the QBO API cannot+ * read the company's close-the-books date, so there is no org-lock-date+ * fetch like Xero's. When the stored date is stale, QBO itself rejects the+ * create with fault 6210, which upsertRemote converts into the SAME+ * structured PERIOD_LOCKED Warning (toQboPeriodClosedError) as the+ * pre-flight would have produced.+ *+ * Consolidation-aware: the drain resolves the same posting-sync settings+ * (including `consolidation`) from the integration metadata to hold+ * journal operations for the daily consolidation cron instead of pushing+ * them individually.+ */++/**+ * The effective lock date (YYYY-MM-DD) for QuickBooks Online: the manual+ * `settings.lockDate` ONLY — QBO's API cannot read the close-the-books+ * date (no organisation endpoint like Xero's PeriodLockDate), so the+ * settings field is the sole pre-flight source and the 6210 fault mapping+ * is the backstop for staleness. Null when no date is stored.+ */+export function getQboLockDate(settings: PostingSyncSettings): string | null {+ return settings.lockDate ? settings.lockDate.slice(0, 10) : null;+}++/**+ * Convert QBO's Account Period Closed fault (Intuit code 6210) into the+ * structured PERIOD_LOCKED Warning — the backstop for a stale manual lock+ * date (pre-flight passed but QBO's real close date is later). Returns+ * null for any other error.+ */+export function toQboPeriodClosedError(+ error: unknown,+ args: { journalLabel: string; txnDate?: string }+): JournalEntrySyncError | null {+ if (!isQboAccountPeriodClosedError(error)) return null;++ return new JournalEntrySyncError({+ errorCode: "PERIOD_LOCKED",+ message: `QuickBooks Online rejected journal ${args.journalLabel}${+ args.txnDate ? ` dated ${args.txnDate}` : ""+ }: the accounting period is closed (Intuit fault 6210). Update the "Books lock date" in the posting sync settings to match QuickBooks Online (or reopen the period there), then retry.`,+ warning: true,+ metadata: {+ ...(args.txnDate ? { txnDate: args.txnDate } : {}),+ qboFaultCode: QBO_FAULT_CODES.ACCOUNT_PERIOD_CLOSED+ }+ });+}++/**+ * Map one Carbon journal to a QBO JournalEntry payload. Pure — exported+ * for tests (and for a future QBO daily-consolidation path, mirroring the+ * Xero mapper's contract).+ *+ * - Lines: one QBO Line per journalLine — `Amount` = abs(signed Carbon+ * amount) at 2dp, `JournalEntryLineDetail.PostingType` = "Debit" when+ * the signed amount is positive else "Credit" (Carbon convention:+ * positive = debit; reversals negate first, flipping every side),+ * `AccountRef` from the account mapping (externalId = QBO Account.Id),+ * Description = line description falling back to the journal+ * description.+ * - DocNumber: the Carbon journalEntryId when it fits QBO's 21-char cap+ * (C7's buildQboDocNumberFields rule); omitted otherwise (QBO+ * auto-numbers) — PrivateNote always carries the Carbon ids, so no+ * extra carrier is needed on overflow.+ * - PrivateNote: "Carbon <journalEntryId> <journal.id>" (or+ * "Carbon reversal of <journalEntryId>"), with+ * " | original date <postingDate>" appended when the period-lock redate+ * policy moved the push date.+ */+/**+ * Slot config + resolved value refs for the QBO journal mapper: `slots`+ * are the company's dimension slots (targets "class" / "department");+ * `refsByValue` resolves `<dimensionId>:<valueId>` → QBO entity ref.+ * Slotted line dimensions with no resolvable ref are OMITTED — the warn+ * policy parks in pre-flight before mapping, so an unresolved value here+ * is the recorded drop path.+ */+export type QboJournalDimensionArgs = {+ slots: ReadonlyArray<+ Pick<PostingSyncDimensionSlot, "dimensionId" | "target">+ >;+ refsByValue: ReadonlyMap<string, Qbo.Ref>;+};++export function mapJournalEntryToQboJournalEntry(args: {+ journal: Accounting.JournalEntry;+ accountRefsById: ReadonlyMap<string, Qbo.Ref>;+ pushDate: string;+ redatedFromDate?: string;+ dimensions?: QboJournalDimensionArgs;+}): QboCreatePayload<Qbo.JournalEntry> {+ const { journal } = args;+ const sign = journal.reversal ? -1 : 1;++ const lines: Qbo.JournalEntryLine[] = journal.lines.map((line) => {+ const accountRef = line.accountId+ ? args.accountRefsById.get(line.accountId)+ : undefined;++ if (!accountRef) {+ // runJournalEntryPreflight fails before mapping; this guards direct+ // callers (consolidation, tests) against unmapped input+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `No QuickBooks Online account mapped for account ${+ line.accountId ?? "(none)"+ } on journal ${journal.journalEntryId}`,+ warning: true,+ metadata: {+ unmappedAccountIds: line.accountId ? [line.accountId] : []+ }+ });+ }++ const signedAmount = sign * line.amount;++ const detail: Qbo.JournalEntryLineDetail = {+ PostingType: signedAmount > 0 ? "Debit" : "Credit",+ AccountRef: accountRef+ };++ if (args.dimensions) {+ for (const slot of args.dimensions.slots) {+ const dimension = line.dimensions?.find(+ (candidate) => candidate.dimensionId === slot.dimensionId+ );+ if (!dimension) continue;+ const ref = args.dimensions.refsByValue.get(+ buildDimensionValueMappingEntityId(+ dimension.dimensionId,+ dimension.valueId+ )+ );+ if (!ref) continue; // drop policy — recorded by the caller+ if (slot.target === QBO_DIMENSION_TARGET_CLASS) {+ detail.ClassRef = ref;+ } else if (slot.target === QBO_DIMENSION_TARGET_DEPARTMENT) {+ detail.DepartmentRef = ref;+ }+ }+ }++ return {+ Amount: roundCurrency(Math.abs(signedAmount)),+ DetailType: "JournalEntryLineDetail",+ Description: line.description ?? journal.description ?? undefined,+ JournalEntryLineDetail: detail+ };+ });++ let privateNote = journal.reversal+ ? `Carbon reversal of ${journal.journalEntryId}`+ : `Carbon ${journal.journalEntryId} ${journal.id}`;+ if (args.redatedFromDate) {+ privateNote += ` | original date ${args.redatedFromDate}`;+ }++ // 21-char DocNumber rule from C7; the helper's PrivateNote carrier is+ // superseded by the journal narration above, which always carries the+ // Carbon ids+ const { DocNumber } = buildQboDocNumberFields(journal.journalEntryId);++ return {+ DocNumber,+ PrivateNote: privateNote,+ TxnDate: args.pushDate,+ Line: lines+ };+}++export class QboJournalEntrySyncer extends BaseEntitySyncer<+ Accounting.JournalEntry,+ Qbo.JournalEntry,+ QboWriteOmit+> {+ // Per-instance caches — a drain reuses one syncer across its claimed+ // operations, so settings, account refs, control accounts and the+ // dimension-value lookup are each fetched at most once per drain+ private postingSyncSettingsPromise?: Promise<PostingSyncSettings>;+ private accountRefsByIdPromise?: Promise<Map<string, Qbo.Ref>>;+ private controlAccountIdsPromise?: Promise<Set<string>>;+ private dimensionValueMappingsPromise?: Promise<Map<string, string>>;++ private get qboProvider(): QboProvider {+ return this.provider as QboProvider;+ }++ // =================================================================+ // 1. SETTINGS + PRE-FLIGHT INPUTS (cached per instance)+ // =================================================================++ /**+ * Per-company posting-sync settings from+ * `companyIntegration.metadata.settings.postingSync`. Public so the+ * drain can gate on `consolidation` ("daily" journals wait for the+ * consolidation cron instead of draining individually).+ */+ public getPostingSyncSettings(): Promise<PostingSyncSettings> {+ if (!this.postingSyncSettingsPromise) {+ this.postingSyncSettingsPromise = (async () => {+ const integration = await this.database+ .selectFrom("companyIntegration")+ .select("metadata")+ .where("id", "=", this.provider.id)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return resolvePostingSyncSettings(integration?.metadata);+ })();+ }+ return this.postingSyncSettingsPromise;+ }++ /**+ * Carbon account.id → QBO AccountRef, from the account-mapping rows+ * (entityType "account", mapping externalId = QBO Account.Id — the same+ * resolution path the item/bill syncers use via loadQboAccountRefsById).+ * Mappings without a stored externalId are treated as unmapped. Public+ * (like getPostingSyncSettings) so a future QBO daily-consolidation path+ * can run the same pre-flights on its aggregate.+ */+ public getAccountRefsById(): Promise<Map<string, Qbo.Ref>> {+ if (!this.accountRefsByIdPromise) {+ this.accountRefsByIdPromise = loadQboAccountRefsById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountRefsByIdPromise;+ }++ /**+ * AR/AP control accounts (accountDefault.receivablesAccount /+ * payablesAccount) — journal lines on these never push. Public for+ * consolidation parity (same pre-flight inputs as individual pushes).+ */+ public getControlAccountIds(): Promise<Set<string>> {+ if (!this.controlAccountIdsPromise) {+ this.controlAccountIdsPromise = (async () => {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select(["receivablesAccount", "payablesAccount"])+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return new Set(+ [defaults?.receivablesAccount, defaults?.payablesAccount].filter(+ (id): id is string => typeof id === "string" && id.length > 0+ )+ );+ })();+ }+ return this.controlAccountIdsPromise;+ }++ /**+ * `<dimensionId>:<valueId>` → QBO Class/Department id from the+ * dimension-value mapping rows (entityType "dimensionValue"). Mutated+ * in place by the autoCreate flow so later pushes in the same drain+ * reuse the created ids.+ */+ public getDimensionValueMappings(): Promise<Map<string, string>> {+ if (!this.dimensionValueMappingsPromise) {+ this.dimensionValueMappingsPromise = (async () => {+ const mappings = await getDimensionValueMappings(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ if (mappings.error) {+ throw new Error(+ `Failed to load dimension value mappings: ${mappings.error}`+ );+ }+ return buildDimensionValueMappingLookup(mappings.data ?? []);+ })();+ }+ return this.dimensionValueMappingsPromise;+ }++ /**+ * autoCreate (opt-in per slot for QBO): create missing Classes /+ * Departments BY NAME — the value's resolved READABLE label — then+ * store the mapping and update the lookup in place.+ */+ private async ensureAutoCreatedDimensionValues(+ journal: Accounting.JournalEntry,+ settings: PostingSyncSettings,+ mappings: Map<string, string>+ ): Promise<void> {+ await ensureDimensionValueExternalIds({+ lines: journal.lines,+ slots: settings.dimensionSlots,+ defaultAutoCreate: false, // QBO: opt-in avoids surprise list writes+ mappings,+ resolveLabels: (values) =>+ resolveDimensionValueLabels(this.database, { values }),+ createExternalValue: async (slot, label) => {+ if (slot.target === QBO_DIMENSION_TARGET_CLASS) {+ const created = await this.qboProvider.createClass({ Name: label });+ return created.Id;+ }+ if (slot.target === QBO_DIMENSION_TARGET_DEPARTMENT) {+ const created = await this.qboProvider.createDepartment({+ Name: label+ });+ return created.Id;+ }+ throw new Error(+ `Unknown QuickBooks Online dimension target "${slot.target}"`+ );+ },+ persistMapping: async (value, externalId, label) => {+ const persisted = await upsertDimensionValueMapping(this.database, {+ companyId: this.companyId,+ integration: this.provider.id,+ dimensionId: value.dimensionId,+ valueId: value.valueId,+ externalId,+ externalName: label+ });+ if (persisted.error) {+ throw new Error(+ `Failed to store dimension value mapping: ${persisted.error}`+ );+ }+ }+ });+ }++ // =================================================================+ // 2. TIMESTAMP EXTRACTION+ // =================================================================++ protected getRemoteUpdatedAt(remote: Qbo.JournalEntry): Date | null {+ return parseQboDate(remote.MetaData?.LastUpdatedTime);+ }++ // =================================================================+ // 3. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(entityId: string): Promise<Accounting.JournalEntry | null> {+ const { journalId, reversal } = parseJournalEntrySyncEntityId(entityId);++ const journal = await this.database+ .selectFrom("journal")+ .select([+ "id",+ "companyId",+ "journalEntryId",+ "description",+ "postingDate",+ "status",+ "sourceType",+ "reversalOfId",+ "reversedById",+ "postedAt",+ "createdAt",+ "updatedAt"+ ])+ .where("id", "=", journalId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (!journal) return null;++ const lines = await this.database+ .selectFrom("journalLine")+ .leftJoin("account", "account.id", "journalLine.accountId")+ .select([+ "journalLine.id",+ "journalLine.accountId",+ "journalLine.amount",+ "journalLine.description",+ "account.class as accountClass"+ ])+ .where("journalId", "=", journalId)+ .where("companyId", "=", this.companyId)+ .orderBy("journalLineReference", "asc")+ .execute();++ const dimensionsByLine = await loadJournalLineDimensions(this.database, {+ companyId: this.companyId,+ journalLineIds: lines.map((line) => line.id)+ });++ return {+ id: journal.id,+ companyId: journal.companyId,+ journalEntryId: journal.journalEntryId,+ description: journal.description ?? null,+ postingDate: toPostingDateString(journal.postingDate),+ status: journal.status,+ sourceType: journal.sourceType ?? null,+ reversalOfId: journal.reversalOfId ?? null,+ reversedById: journal.reversedById ?? null,+ reversal,+ lines: lines.map((line) => {+ const dimensions = dimensionsByLine.get(line.id);+ return {+ id: line.id,+ accountId: line.accountId ?? null,+ // Carbon stores natural-balance-signed amounts; the engine expects+ // debit-signed (see toDebitSignedAmount)+ amount: toDebitSignedAmount(+ line.accountClass,+ Number(line.amount) || 0+ ),+ description: line.description ?? null,+ ...(dimensions ? { dimensions } : {})+ };+ }),+ updatedAt: journal.updatedAt ?? journal.postedAt ?? journal.createdAt+ };+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.JournalEntry>> {+ const result = new Map<string, Accounting.JournalEntry>();+ for (const id of ids) {+ const journal = await this.fetchLocal(id);+ if (journal) result.set(id, journal);+ }+ return result;+ }++ // =================================================================+ // 4. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Qbo.JournalEntry | null> {+ return this.qboProvider.getJournalEntry(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Qbo.JournalEntry>> {+ const result = new Map<string, Qbo.JournalEntry>();+ for (const id of ids) {+ const journalEntry = await this.qboProvider.getJournalEntry(id);+ if (journalEntry) result.set(journalEntry.Id, journalEntry);+ }+ return result;+ }++ // =================================================================+ // 5. SHOULD SYNC (skip-reason gate)+ // =================================================================++ protected async shouldSync(+ context: ShouldSyncContext<Accounting.JournalEntry, Qbo.JournalEntry>+ ): Promise<boolean | string> {+ if (context.direction === "pull") {+ return "Journal entries are push-only; pulling journal entries from QuickBooks Online is not supported";+ }++ const local = context.localEntity;+ if (!local) return "Journal could not be loaded";++ // Idempotency: a mapped journal push is never repeated+ if (!context.isFirstSync) {+ return "Journal already pushed to QuickBooks Online (mapping exists)";+ }++ if (local.reversal) {+ if (local.status !== "Reversed") {+ return `Reversal push requires a Reversed journal (current status: ${local.status})`;+ }+ // Reversal-by-reference: only reverse what was actually pushed+ const originalRemoteId = await this.getRemoteId(local.id);+ if (!originalRemoteId) {+ return `Original journal ${local.journalEntryId} was never pushed to QuickBooks Online; nothing to reverse`;+ }+ } else if (local.status !== "Posted") {+ return `Journal must be Posted before syncing (current status: ${local.status})`;+ }++ const settings = await this.getPostingSyncSettings();+ const sourceTypeSkipReason = getPostingSyncSourceTypeSkipReason(+ local.sourceType,+ settings,+ {+ inventoryAdjustmentEntitySyncEnabled:+ this.provider.getSyncConfig("inventoryAdjustment")?.enabled ?? false+ }+ );+ if (sourceTypeSkipReason) return sourceTypeSkipReason;++ return true;+ }++ // =================================================================+ // 6. TRANSFORMATION (Carbon -> QBO) with pre-flight+ // =================================================================++ protected async mapToRemote(+ local: Accounting.JournalEntry+ ): Promise<QboCreatePayload<Qbo.JournalEntry>> {+ const settings = await this.getPostingSyncSettings();+ const accountRefsById = await this.getAccountRefsById();+ const controlAccountIds = await this.getControlAccountIds();+ const lockDate = getQboLockDate(settings);++ // The shared pre-flight takes account "codes"; for QBO that role is+ // played by the account Id (the ref value)+ const accountIdsByCarbonId = new Map(+ [...accountRefsById].map(+ ([accountId, ref]) => [accountId, ref.value] as const+ )+ );++ // Dimension slots: resolve the value-mapping lookup and auto-create+ // missing Classes/Departments (opt-in per slot) BEFORE pre-flight so+ // freshly created options never park as unmapped+ let dimensionValueMappings: Map<string, string> | undefined;+ if (settings.dimensionSlots.length > 0) {+ dimensionValueMappings = await this.getDimensionValueMappings();+ await this.ensureAutoCreatedDimensionValues(+ local,+ settings,+ dimensionValueMappings+ );+ }++ const preflight = runJournalEntryPreflight({+ journal: local,+ accountCodesById: accountIdsByCarbonId,+ controlAccountIds,+ lockDate,+ settings,+ dimensionValueMappings+ });++ if (preflight.failure) {+ throw new JournalEntrySyncError(preflight.failure);+ }++ if (preflight.droppedDimensionValues?.length) {+ // "drop" policy: pushed without these dimensions. The drain has no+ // success-metadata channel yet, so the record lives in the logs.+ console.warn(+ "[QboJournalEntrySyncer] dropped unmapped dimension values",+ {+ journalId: local.id,+ droppedDimensionValues: preflight.droppedDimensionValues+ }+ );+ }++ return mapJournalEntryToQboJournalEntry({+ journal: local,+ accountRefsById,+ pushDate: preflight.pushDate,+ redatedFromDate: preflight.redatedFromDate,+ ...(dimensionValueMappings+ ? {+ dimensions: {+ slots: settings.dimensionSlots,+ refsByValue: new Map(+ [...dimensionValueMappings].map(+ ([key, externalId]) => [key, { value: externalId }] as const+ )+ )+ }+ }+ : {})+ });+ }++ // =================================================================+ // 7. TRANSFORMATION (QBO -> Carbon) - Not supported (push-only)+ // =================================================================++ protected async mapToLocal(+ _remote: Qbo.JournalEntry+ ): Promise<Partial<Accounting.JournalEntry>> {+ throw new Error(+ "Journal entries are push-only. Cannot map from QuickBooks Online to Carbon."+ );+ }++ protected async upsertLocal(+ _tx: KyselyTx,+ _data: Partial<Accounting.JournalEntry>,+ _remoteId: string+ ): Promise<string> {+ throw new Error(+ "Journal entries are push-only. Cannot upsert locally from QuickBooks Online."+ );+ }++ // =================================================================+ // 8. UPSERT REMOTE (Single + Batch)+ // =================================================================++ protected async upsertRemote(+ data: QboCreatePayload<Qbo.JournalEntry>,+ localId: string+ ): Promise<string> {+ // Create-only: posted journals are immutable and pushToAccounting+ // hard-skips already-mapped ids, so the SyncToken update path never+ // applies here+ try {+ const created = await this.qboProvider.createJournalEntry(data);+ return created.Id;+ } catch (error) {+ // Closed-books backstop: the manual lock date can be stale (the QBO+ // API cannot read the real close date) — surface QBO's 6210 fault as+ // the same structured PERIOD_LOCKED Warning the pre-flight produces+ const periodClosed = toQboPeriodClosedError(error, {+ journalLabel: data.DocNumber ?? localId,+ txnDate: data.TxnDate+ });+ if (periodClosed) throw periodClosed;+ throw error;+ }+ }++ protected async upsertRemoteBatch(+ data: Array<{+ localId: string;+ payload: QboCreatePayload<Qbo.JournalEntry>;+ }>+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>();+ // One journal per POST keeps per-journal idempotency simple; journal+ // volumes per drain are small (claim limit 20)+ for (const { localId, payload } of data) {+ const remoteId = await this.upsertRemote(payload, localId);+ result.set(localId, remoteId);+ }+ return result;+ }++ // =================================================================+ // 9. PUSH WORKFLOW (structured pre-flight failures)+ // =================================================================++ /**+ * Reimplements the base push workflow so pre-flight failures reach the+ * caller as structured JournalEntrySyncFailure objects on+ * `SyncResult.error` (the base catch flattens every throw to a string,+ * which would lose errorCode/warning/metadata). Also replaces the base+ * lastSyncedAt bailout with a hard skip-when-mapped: posted journals are+ * immutable, so an existing mapping means the push already happened.+ */+ async pushToAccounting(entityId: string): Promise<SyncResult> {+ if (!this.config.enabled) {+ return {+ status: "skipped",+ action: "none",+ error: "Sync disabled in config"+ };+ }++ try {+ const existingMapping = await this.mappingService.getByEntity(+ this.entityType,+ entityId,+ this.provider.id+ );++ if (existingMapping?.externalId) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ remoteId: existingMapping.externalId,+ error:+ "Journal already pushed to QuickBooks Online — skipping (idempotent)"+ };+ }++ const localEntity = await this.fetchLocal(entityId);+ if (!localEntity) {+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: `Entity ${entityId} not found in Carbon`+ };+ }++ const shouldSyncResult = await this.shouldSync({+ direction: "push",+ localEntity,+ isFirstSync: true,+ entityId+ });++ if (shouldSyncResult !== true) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error:+ typeof shouldSyncResult === "string"+ ? shouldSyncResult+ : "Entity not eligible for sync"+ };+ }++ const remotePayload = await this.mapToRemote(localEntity);+ const remoteId = await this.upsertRemote(remotePayload, entityId);++ await withTriggersDisabled(this.database, async (tx) => {+ await this.linkEntities(tx, entityId, remoteId);+ });++ return {+ status: "success",+ action: "created",+ localId: entityId,+ remoteId+ };+ } catch (err) {+ if (err instanceof JournalEntrySyncError) {+ console.error("[QboJournalEntrySyncer] pre-flight failure", {+ entityId,+ ...err.failure+ });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err.failure+ };+ }++ console.error("[QboJournalEntrySyncer] push failed", { entityId, err });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err instanceof Error ? err.message : String(err)+ };+ }+ }++ /**+ * Batch push composes the overridden single push so structured pre-flight+ * failures survive the batch path too — the base implementation runs its+ * own catch-and-flatten loop, which would reduce JournalEntrySyncError to+ * a string for drains that push journals in groups (individual-mode+ * posting sync). Journals arrive in claim-sized batches (≤20), so a+ * sequential loop costs nothing.+ */+ async pushBatchToAccounting(entityIds: string[]): Promise<BatchSyncResult> {+ const results: SyncResult[] = [];++ for (const entityId of entityIds) {+ results.push(await this.pushToAccounting(entityId));+ }++ return {+ results,+ successCount: results.filter((r) => r.status === "success").length,+ errorCount: results.filter((r) => r.status === "error").length,+ skippedCount: results.filter((r) => r.status === "skipped").length+ };+ }++ // =================================================================+ // 10. PULL WORKFLOW - Not supported (push-only)+ // =================================================================++ async pullFromAccounting(remoteId: string): Promise<SyncResult> {+ return {+ status: "error",+ action: "none",+ remoteId,+ error:+ "Journal entries are push-only: pulling journal entries from QuickBooks Online into Carbon is not supported"+ };+ }++ async pullBatchFromAccounting(remoteIds: string[]): Promise<BatchSyncResult> {+ const results: SyncResult[] = remoteIds.map((remoteId) => ({+ status: "error",+ action: "none",+ remoteId,+ error:+ "Journal entries are push-only: pulling journal entries from QuickBooks Online into Carbon is not supported"+ }));++ return {+ results,+ successCount: 0,+ errorCount: results.length,+ skippedCount: 0+ };+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/payment.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/payment.tsnew file mode 100644index 0000000000..7d498e7ca7--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/payment.ts@@ -0,0 +1,445 @@+import type { NormalizedPayment } from "../../../core/payment-application";+import {+ type PaymentPushContext,+ PaymentSyncerBase+} from "../../../core/payment-syncer";+import { JournalEntrySyncError } from "../../../core/posting";+import type { ShouldSyncContext } from "../../../core/types";+import { parseQboDate, type Qbo } from "../models";+import type { QboProvider } from "../provider";+import { loadQboAccountRefsById } from "./shared";++/**+ * QboPaymentSyncer — the first QBO payment syncer, on the shared+ * `PaymentSyncerBase`. QBO `BillPayment` objects settle Carbon purchase+ * invoices (AP); QBO `Payment` objects settle Carbon sales invoices (AR). The+ * base writes a Draft `payment` + `invoiceSettlement` and then invokes the+ * native `post-payment` edge function (GL journal + Posted/Voided status).+ * Two-way as of Phase G: a Carbon-born Posted payment pushes back out as a QBO+ * Payment (AR) / BillPayment (AP) document (see `pushRemotePayment`).+ *+ * Entity-id contract: the sync operation's entityId is a COMPOSITE, kept+ * identical to the Rillet AP convention. AR is prefix-less+ * `"<invoiceRemoteId>:<paymentRemoteId>"`; AP is+ * `"bill:<primaryBillRemoteId>:<billPaymentRemoteId>"`. For a multi-bill+ * BillPayment the composite carries the FIRST linked bill (for+ * `dependsOnMapping` + the ownership skip), and `mapToNormalized` returns+ * `linkedDocuments` for ALL `Line[].LinkedTxn{TxnType:"Bill"}` so the core fans+ * settlements out over the mapped ones. The `bill:` prefix is also the family+ * discriminator the syncer branches on.+ *+ * Unlike Rillet, QBO payments are directly addressable by id, so `fetchRemote`+ * parses out the `paymentRemoteId` and queries the object directly; the+ * document half of the composite is only used for `dependsOnMapping` + the+ * shouldSync ownership skip.+ */++const SYNC_ID_SEPARATOR = ":";+/** AP composite-id family discriminator prefix. AR is prefix-less. */+const BILL_PREFIX = "bill:";++/** Composite sync entity id for one QBO invoice payment (AR, prefix-less). */+export function getQboPaymentSyncEntityId(+ invoiceRemoteId: string,+ paymentRemoteId: string+): string {+ return `${invoiceRemoteId}${SYNC_ID_SEPARATOR}${paymentRemoteId}`;+}++/** Composite sync entity id for one QBO bill payment (AP, `bill:` prefix). */+export function getQboBillPaymentSyncEntityId(+ billRemoteId: string,+ billPaymentRemoteId: string+): string {+ return `${BILL_PREFIX}${billRemoteId}${SYNC_ID_SEPARATOR}${billPaymentRemoteId}`;+}++/**+ * Split a composite payment entity id into its family, primary document remote+ * id, and payment remote id. A `bill:` prefix marks the AP form; anything else+ * is the AR form. Throws on a malformed id.+ */+export function parseQboPaymentSyncEntityId(entityId: string): {+ family: "ar" | "ap";+ documentRemoteId: string;+ paymentRemoteId: string;+} {+ const isBill = entityId.startsWith(BILL_PREFIX);+ const remainder = isBill ? entityId.slice(BILL_PREFIX.length) : entityId;++ const separatorIndex = remainder.indexOf(SYNC_ID_SEPARATOR);+ if (separatorIndex <= 0 || separatorIndex === remainder.length - 1) {+ throw new Error(+ `Invalid QuickBooks Online payment sync entity id "${entityId}" — expected "<invoiceRemoteId>:<paymentRemoteId>" or "bill:<billRemoteId>:<billPaymentRemoteId>"`+ );+ }+ return {+ family: isBill ? "ap" : "ar",+ documentRemoteId: remainder.slice(0, separatorIndex),+ paymentRemoteId: remainder.slice(separatorIndex + 1)+ };+}++/** Either QBO payment wire shape the syncer handles (AR Payment / AP BillPayment). */+export type QboPayment = Qbo.Payment | Qbo.BillPayment;++/**+ * Every document (Bill for AP, Invoice for AR) a QBO payment applies to, with+ * the per-line applied amount. Reads `Line[].LinkedTxn` filtered to the+ * family's `TxnType`. A line with several LinkedTxn contributes each matching+ * one at the line's `Amount` (QBO writes one Bill/Invoice per line in+ * practice). Pure — exported for tests.+ */+export function getQboPaymentLinkedDocuments(+ remote: QboPayment,+ txnType: "Bill" | "Invoice"+): { remoteId: string; amount: number }[] {+ const docs: { remoteId: string; amount: number }[] = [];+ for (const line of remote.Line ?? []) {+ for (const linked of line.LinkedTxn ?? []) {+ if (linked.TxnType === txnType) {+ docs.push({ remoteId: linked.TxnId, amount: line.Amount ?? 0 });+ }+ }+ }+ return docs;+}++/**+ * Build the canonical composite sync entity id + primary document remote id+ * from a fetched QBO payment object. Used by both the CDC `listChanges` sweep+ * and the notification-only webhook so BOTH enqueue the IDENTICAL composite —+ * the composite is the `payment` mapping key, so a mismatch between the two+ * paths would double-record the settlement. Returns null when the payment+ * settles no Bill/Invoice (nothing for Carbon to settle). Pure — exported for+ * tests + the webhook route.+ */+export function buildQboPaymentSyncChange(+ remote: QboPayment,+ family: "ar" | "ap"+): { entityId: string; documentRemoteId: string } | null {+ const docs = getQboPaymentLinkedDocuments(+ remote,+ family === "ap" ? "Bill" : "Invoice"+ );+ const primary = docs[0];+ if (!primary) return null;++ return {+ documentRemoteId: primary.remoteId,+ entityId:+ family === "ap"+ ? getQboBillPaymentSyncEntityId(primary.remoteId, remote.Id)+ : getQboPaymentSyncEntityId(primary.remoteId, remote.Id)+ };+}++export class QboPaymentSyncer extends PaymentSyncerBase<QboPayment> {+ private get qboProvider(): QboProvider {+ return this.provider as QboProvider;+ }++ /** QBO accepts Carbon-born payments back out (Phase G). */+ protected supportsPaymentPush = true;++ /** Carbon account.id → QBO AccountRef, read once per syncer instance. */+ private accountRefsByIdPromise?: Promise<Map<string, Qbo.Ref>>;++ private getAccountRefsById(): Promise<Map<string, Qbo.Ref>> {+ if (!this.accountRefsByIdPromise) {+ this.accountRefsByIdPromise = loadQboAccountRefsById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountRefsByIdPromise;+ }++ // =================================================================+ // 1. REMOTE FETCH — composite id → the payment is addressable by id+ // =================================================================++ async fetchRemote(entityId: string): Promise<QboPayment | null> {+ const { family, paymentRemoteId } = parseQboPaymentSyncEntityId(entityId);+ const remote =+ family === "ap"+ ? await this.qboProvider.getBillPayment(paymentRemoteId)+ : await this.qboProvider.getPayment(paymentRemoteId);++ // Not found → a hard-deleted payment. The pull sweep only enqueues a+ // composite whose payment mapping still exists (it resolves the composite+ // FROM that mapping when a CDC tombstone arrives), so a 404 here means the+ // QBO object was deleted after we recorded it. Return a tombstone marker so+ // the base flows into the void path: `mapToNormalized` reads no amount/lines+ // → amount 0 → status "void", reversing the previously-recorded Carbon+ // payment. A first-ever pull that 404s is caught by shouldSync's+ // first-seen-void skip, so nothing is voided that was never recorded.+ if (!remote) {+ return { Id: paymentRemoteId } as QboPayment;+ }+ return remote;+ }++ /** Keyed by the COMPOSITE entity id (the base pull flow keys results by it). */+ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, QboPayment>> {+ const result = new Map<string, QboPayment>();+ for (const entityId of ids) {+ const payment = await this.fetchRemote(entityId);+ if (payment) result.set(entityId, payment);+ }+ return result;+ }++ // =================================================================+ // 2. TIMESTAMP + SHOULD SYNC+ // =================================================================++ protected getRemoteUpdatedAt(remote: QboPayment): Date | null {+ return parseQboDate(remote.MetaData?.LastUpdatedTime);+ }++ protected async shouldSync(+ context: ShouldSyncContext<QboPayment, QboPayment>+ ): Promise<boolean | string> {+ // Push is gated entirely in PaymentSyncerBase.pushToAccounting (origin,+ // documents-mode, single-settlement, FX) — shouldSync only governs the pull.+ const { family, documentRemoteId } = parseQboPaymentSyncEntityId(+ context.entityId+ );++ // Documents-mode gate: inbound payment sync-back is allowed only when the+ // payment's AR/AP family is in `documents` mode (Carbon owns the settled+ // documents). A `journals`/`none` family does not pull payments — a benign+ // skip, like the ownership skip below. An unconfigured integration defaults+ // to documents.+ if (!(await this.isPaymentSyncbackEnabled(family))) {+ return `payment sync-back is disabled: the ${family} family is not in documents mode`;+ }++ // Ownership gate: the pushed document's mapping is the ownership record. No+ // local mapping means the bill/invoice belongs to another Carbon instance+ // or was created directly in QBO — a benign skip, not a failure.+ const docType = family === "ap" ? "bill" : "invoice";+ const localDocId = await this.mappingService.getEntityId(+ this.provider.id,+ documentRemoteId,+ docType+ );+ if (!localDocId) {+ return `QuickBooks Online ${docType} ${documentRemoteId} has no Carbon mapping — the payment belongs to another Carbon instance or to a ${docType} created directly in QuickBooks Online`;+ }++ // A payment first seen as voided (TotalAmt 0) was never recorded — nothing+ // to void. (QBO has no payment status enum; a void zeroes TotalAmt.)+ if (context.isFirstSync && (context.remoteEntity?.TotalAmt ?? 0) === 0) {+ return "Voided QuickBooks Online payment was never recorded in Carbon — nothing to do";+ }++ return true;+ }++ // =================================================================+ // 3. NORMALIZATION (QBO -> family-agnostic NormalizedPayment)+ // =================================================================++ protected mapToNormalized(+ remote: QboPayment,+ entityId: string+ ): NormalizedPayment {+ const { family, documentRemoteId, paymentRemoteId } =+ parseQboPaymentSyncEntityId(entityId);++ const totalAmt = remote.TotalAmt ?? 0;+ const linked = getQboPaymentLinkedDocuments(+ remote,+ family === "ap" ? "Bill" : "Invoice"+ );++ // TotalAmt fallback for a single linked document whose line amount is+ // absent (QBO usually populates line Amount, but be defensive).+ if (linked.length === 1 && linked[0] && linked[0].amount === 0) {+ linked[0].amount = totalAmt;+ }++ // Settlement fan-out only over positive applications; a void (TotalAmt 0,+ // zeroed lines) drops to the documentRemoteId fallback in the core, which+ // resolves the existing payment mapping to reverse it.+ const linkedDocuments = linked.filter((doc) => doc.amount > 0);++ const paidDate = (remote.TxnDate ?? new Date().toISOString()).slice(0, 10);++ return {+ family,+ documentRemoteId,+ paymentRemoteId,+ amount: totalAmt,+ currencyCode: remote.CurrencyRef?.value ?? null,+ exchangeRate: remote.ExchangeRate ?? 1,+ paidDate,+ // The QBO (bill) payment Id is the human/provider reference.+ reference: paymentRemoteId,+ // No status enum on QBO payments; a void zeroes TotalAmt.+ status: totalAmt === 0 ? "void" : "settled",+ ...(linkedDocuments.length > 0 ? { linkedDocuments } : {})+ };+ }++ // =================================================================+ // 4. PUSH (Phase G — Carbon-born payment → QBO Payment / BillPayment)+ // =================================================================++ /**+ * Create one QBO payment document for the settled document. Resolves the+ * settled document's QBO id, the counterparty ref (QBO requires CustomerRef on+ * a Payment / VendorRef on a BillPayment), and the bank account's QBO ref from+ * the mappings. A missing document/counterparty mapping → UNSYNCED_DOCUMENT+ * Warning (sync the dependency first); a missing bank ref → UNMAPPED_ACCOUNTS+ * Warning (map it on the integration settings page). AP → POST /billpayment,+ * AR → POST /payment; each links its `Amount` to the Bill/Invoice via+ * LinkedTxn. Returns the created id + the composite mapping id.+ */+ protected async pushRemotePayment(+ context: PaymentPushContext+ ): Promise<{ remoteId: string; compositeEntityId: string }> {+ const documentRemoteId = await this.mappingService.getExternalId(+ context.family === "ar" ? "invoice" : "bill",+ context.targetDocumentId,+ this.provider.id+ );+ if (!documentRemoteId) {+ throw new JournalEntrySyncError({+ errorCode: "UNSYNCED_DOCUMENT",+ message: `The settled ${+ context.family === "ar" ? "invoice" : "bill"+ } has not synced to QuickBooks Online yet — sync it, then retry the payment`,+ warning: true,+ metadata: { targetDocumentId: context.targetDocumentId }+ });+ }++ const bankRef = (await this.getAccountRefsById()).get(+ context.bankAccountId+ );+ if (!bankRef) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `The payment's bank/cash account is not mapped to a QuickBooks Online account — map it on the integration settings page, then retry`,+ warning: true,+ metadata: { bankAccountId: context.bankAccountId }+ });+ }++ // QBO requires the counterparty ref (CustomerRef on a Payment, VendorRef on+ // a BillPayment); it is NOT inferable from the LinkedTxn alone.+ const counterpartyRef = await this.resolveCounterpartyRef(context);++ if (context.family === "ap") {+ // VERIFY (QBO sandbox): a bank-cleared BillPayment uses PayType "Check"+ // with CheckPayment.BankAccountRef; confirm this is accepted for a plain+ // bank disbursement (vs "CreditCard"/other) and that BankAccountRef takes+ // the Account id value.+ const remoteId = await this.qboProvider.createBillPayment({+ VendorRef: counterpartyRef,+ TotalAmt: context.amount,+ TxnDate: context.paidDate,+ PayType: "Check",+ CheckPayment: { BankAccountRef: bankRef },+ Line: [+ {+ Amount: context.amount,+ LinkedTxn: [{ TxnId: documentRemoteId, TxnType: "Bill" }]+ }+ ]+ });+ return {+ remoteId,+ compositeEntityId: getQboBillPaymentSyncEntityId(+ documentRemoteId,+ remoteId+ )+ };+ }++ // VERIFY (QBO sandbox): a Payment deposits to DepositToAccountRef (the+ // Account id value); confirm the receipt lands in the mapped bank account.+ const remoteId = await this.qboProvider.createPayment({+ CustomerRef: counterpartyRef,+ TotalAmt: context.amount,+ TxnDate: context.paidDate,+ DepositToAccountRef: bankRef,+ Line: [+ {+ Amount: context.amount,+ LinkedTxn: [{ TxnId: documentRemoteId, TxnType: "Invoice" }]+ }+ ]+ });+ return {+ remoteId,+ compositeEntityId: getQboPaymentSyncEntityId(documentRemoteId, remoteId)+ };+ }++ /**+ * Resolve the settled document's counterparty as a QBO ref: the Carbon+ * salesInvoice.customerId (AR) / purchaseInvoice.supplierId (AP), then that+ * entity's QBO mapping. A missing customer/supplier or an unsynced one →+ * UNSYNCED_DOCUMENT Warning (a dependency-ordering issue the operator fixes by+ * syncing the master record).+ */+ private async resolveCounterpartyRef(+ context: PaymentPushContext+ ): Promise<Qbo.Ref> {+ const counterpartyId =+ context.family === "ar"+ ? ((+ await this.database+ .selectFrom("salesInvoice")+ .select("customerId")+ .where("id", "=", context.targetDocumentId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst()+ )?.customerId ?? null)+ : ((+ await this.database+ .selectFrom("purchaseInvoice")+ .select("supplierId")+ .where("id", "=", context.targetDocumentId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst()+ )?.supplierId ?? null);++ if (!counterpartyId) {+ throw new JournalEntrySyncError({+ errorCode: "UNSYNCED_DOCUMENT",+ message: `The settled ${+ context.family === "ar" ? "sales invoice" : "purchase invoice"+ } ${context.targetDocumentId} has no ${+ context.family === "ar" ? "customer" : "supplier"+ } — cannot record the payment's counterparty in QuickBooks Online`,+ warning: true,+ metadata: { targetDocumentId: context.targetDocumentId }+ });+ }++ const counterpartyRemoteId = await this.mappingService.getExternalId(+ context.family === "ar" ? "customer" : "vendor",+ counterpartyId,+ this.provider.id+ );+ if (!counterpartyRemoteId) {+ throw new JournalEntrySyncError({+ errorCode: "UNSYNCED_DOCUMENT",+ message: `The payment's ${+ context.family === "ar" ? "customer" : "supplier"+ } has not synced to QuickBooks Online yet — sync it, then retry the payment`,+ warning: true,+ metadata: { counterpartyId }+ });+ }++ return { value: counterpartyRemoteId };+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/purchase-order.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/purchase-order.tsnew file mode 100644index 0000000000..171cc6aeb5--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/purchase-order.ts@@ -0,0 +1,463 @@+import type { KyselyTx } from "@carbon/database/client";+import { createMappingService } from "../../../core/external-mapping";+import {+ type Accounting,+ BaseEntitySyncer,+ type ShouldSyncContext+} from "../../../core/types";+import { parseQboDate, type Qbo } from "../models";+import type { QboProvider } from "../provider";+import {+ buildQboDocNumberFields,+ buildQboExpenseLines,+ loadQboAccountRefsById,+ type QboWriteOmit,+ updateWithSyncTokenRetry+} from "./shared";++/**+ * QboPurchaseOrderSyncer — Carbon purchase orders → QBO PurchaseOrder+ * objects (push-to-accounting, owner carbon per DEFAULT_SYNC_CONFIG;+ * entityType "purchaseOrder" like the Xero counterpart).+ *+ * Push: only POs in a locked status (same gate as the Xero counterpart).+ * VendorRef via JIT vendor sync, POEmail from the supplier's primary+ * contact, lines per the model (ItemBasedExpenseLineDetail for item lines,+ * AccountBasedExpenseLineDetail with the mapped account otherwise),+ * DocNumber under QBO's 21-char cap else PrivateNote. POStatus maps from+ * the Carbon status (Completed/Closed → Closed, else Open).+ *+ * Pull is update-only (dates/status back onto the Carbon PO) — POs are+ * never created from QBO, mirroring the Xero counterpart.+ */++// Only sync POs in locked statuses (behavior copied from the Xero syncer)+const SYNCABLE_STATUSES: Accounting.PurchaseOrder["status"][] = [+ "To Receive",+ "To Receive and Invoice",+ "To Invoice",+ "Completed"+];++// Row shapes (mirror the Xero PO syncer's, plus line accountId for the+// account-mapping resolution QBO needs)+type PurchaseOrderRow = {+ id: string;+ companyId: string;+ purchaseOrderId: string;+ supplierId: string;+ status: Accounting.PurchaseOrder["status"];+ orderDate: string | null;+ currencyCode: string | null;+ exchangeRate: number | null;+ supplierReference: string | null;+ updatedAt: string | null;+};++type PurchaseOrderLineRow = {+ id: string;+ purchaseOrderId: string;+ description: string | null;+ purchaseQuantity: number | null;+ unitPrice: number | null;+ itemId: string | null;+ accountId: string | null;+ accountNumber: string | null;+ taxPercent: number | null;+ taxAmount: number | null;+ extendedPrice: number | null;+ quantityReceived: number | null;+ quantityInvoiced: number | null;+ itemCode: string | null;+};++/** Carbon PO status → QBO POStatus. Pure — exported for tests. */+export function mapCarbonPoStatusToQbo(+ status: Accounting.PurchaseOrder["status"]+): "Open" | "Closed" {+ return status === "Completed" || status === "Closed" ? "Closed" : "Open";+}++/** QBO POStatus → Carbon PO status. Pure — exported for tests. */+export function mapQboPoStatusToCarbon(+ status: "Open" | "Closed" | undefined+): Accounting.PurchaseOrder["status"] | undefined {+ if (!status) return undefined;+ return status === "Closed" ? "Closed" : "To Receive";+}++export class QboPurchaseOrderSyncer extends BaseEntitySyncer<+ Accounting.PurchaseOrder,+ Qbo.PurchaseOrder,+ QboWriteOmit+> {+ private accountRefsByIdPromise?: Promise<Map<string, Qbo.Ref>>;++ private get qboProvider(): QboProvider {+ return this.provider as QboProvider;+ }++ private getAccountRefsById(): Promise<Map<string, Qbo.Ref>> {+ if (!this.accountRefsByIdPromise) {+ this.accountRefsByIdPromise = loadQboAccountRefsById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountRefsByIdPromise;+ }++ // =================================================================+ // 1. ID MAPPING — default implementation (entityType "purchaseOrder")+ // =================================================================++ // =================================================================+ // 2. TIMESTAMP EXTRACTION+ // =================================================================++ protected getRemoteUpdatedAt(remote: Qbo.PurchaseOrder): Date | null {+ return parseQboDate(remote.MetaData?.LastUpdatedTime);+ }++ // =================================================================+ // 3. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.PurchaseOrder | null> {+ const orders = await this.fetchOrdersByIds([id]);+ return orders.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.PurchaseOrder>> {+ return this.fetchOrdersByIds(ids);+ }++ private async fetchOrdersByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.PurchaseOrder>> {+ if (ids.length === 0) return new Map();++ const orderRows = await this.database+ .selectFrom("purchaseOrder")+ .select([+ "id",+ "companyId",+ "purchaseOrderId",+ "supplierId",+ "status",+ "orderDate",+ "currencyCode",+ "exchangeRate",+ "supplierReference",+ "updatedAt"+ ])+ .where("id", "in", ids)+ .where("companyId", "=", this.companyId)+ .execute();++ if (orderRows.length === 0) return new Map();++ const lineRows = await this.database+ .selectFrom("purchaseOrderLine")+ .leftJoin("item", "item.id", "purchaseOrderLine.itemId")+ .leftJoin("account", "account.id", "purchaseOrderLine.accountId")+ .select([+ "purchaseOrderLine.id",+ "purchaseOrderLine.purchaseOrderId",+ "purchaseOrderLine.description",+ "purchaseOrderLine.purchaseQuantity",+ "purchaseOrderLine.unitPrice",+ "purchaseOrderLine.itemId",+ "purchaseOrderLine.accountId",+ "purchaseOrderLine.taxPercent",+ "purchaseOrderLine.taxAmount",+ "purchaseOrderLine.extendedPrice",+ "purchaseOrderLine.quantityReceived",+ "purchaseOrderLine.quantityInvoiced",+ "item.readableId as itemCode",+ "account.number as accountNumber"+ ])+ .where(+ "purchaseOrderLine.purchaseOrderId",+ "in",+ orderRows.map((o) => o.id)+ )+ .execute();++ // Supplier external IDs (entityType "vendor" — what the vendor syncer+ // stores)+ const supplierExternalIds = new Map<string, string | null>();+ const mappingService = createMappingService(this.database, this.companyId);+ for (const row of orderRows) {+ if (!supplierExternalIds.has(row.supplierId)) {+ supplierExternalIds.set(+ row.supplierId,+ await mappingService.getExternalId(+ "vendor",+ row.supplierId,+ this.provider.id+ )+ );+ }+ }++ const linesByOrder = new Map<string, PurchaseOrderLineRow[]>();+ for (const line of lineRows as PurchaseOrderLineRow[]) {+ const existing = linesByOrder.get(line.purchaseOrderId) ?? [];+ existing.push(line);+ linesByOrder.set(line.purchaseOrderId, existing);+ }++ const result = new Map<string, Accounting.PurchaseOrder>();+ for (const row of orderRows as PurchaseOrderRow[]) {+ const lines = linesByOrder.get(row.id) ?? [];++ let subtotal = 0;+ let totalTax = 0;+ for (const line of lines) {+ subtotal += Number(line.extendedPrice) || 0;+ totalTax += Number(line.taxAmount) || 0;+ }++ result.set(row.id, {+ id: row.id,+ companyId: row.companyId,+ purchaseOrderId: row.purchaseOrderId,+ supplierId: row.supplierId,+ supplierExternalId: supplierExternalIds.get(row.supplierId) ?? null,+ status: row.status,+ orderDate: row.orderDate,+ deliveryDate: null,+ deliveryAddress: null,+ deliveryInstructions: null,+ currencyCode: row.currencyCode,+ exchangeRate: Number(row.exchangeRate) || 1,+ subtotal,+ totalTax,+ totalAmount: subtotal + totalTax,+ supplierReference: row.supplierReference,+ lines: lines.map((line) => ({+ id: line.id,+ description: line.description,+ quantity: Number(line.purchaseQuantity) || 0,+ unitPrice: Number(line.unitPrice) || 0,+ itemId: line.itemId,+ itemCode: line.itemCode,+ accountId: line.accountId,+ accountNumber: line.accountNumber,+ taxPercent: line.taxPercent != null ? Number(line.taxPercent) : null,+ taxAmount: line.taxAmount != null ? Number(line.taxAmount) : null,+ totalAmount: Number(line.extendedPrice) || 0,+ quantityReceived:+ line.quantityReceived != null+ ? Number(line.quantityReceived)+ : null,+ quantityInvoiced:+ line.quantityInvoiced != null ? Number(line.quantityInvoiced) : null+ })),+ updatedAt: row.updatedAt ?? new Date().toISOString(),+ raw: row+ });+ }++ return result;+ }++ // =================================================================+ // 4. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Qbo.PurchaseOrder | null> {+ return this.qboProvider.getPurchaseOrder(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Qbo.PurchaseOrder>> {+ const result = new Map<string, Qbo.PurchaseOrder>();+ for (const id of ids) {+ const purchaseOrder = await this.fetchRemote(id);+ if (purchaseOrder) result.set(purchaseOrder.Id, purchaseOrder);+ }+ return result;+ }++ // =================================================================+ // 5. TRANSFORMATION (Carbon -> QBO)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.PurchaseOrder+ ): Promise<Omit<Qbo.PurchaseOrder, QboWriteOmit>> {+ // JIT dependency: vendor before the document+ let vendorRemoteId = local.supplierExternalId;+ if (!vendorRemoteId && local.supplierId) {+ vendorRemoteId = await this.ensureDependencySynced(+ "vendor",+ local.supplierId+ );+ }++ if (!vendorRemoteId) {+ throw new Error(+ `Cannot sync PO ${local.id}: No supplier linked or supplier not synced to QuickBooks Online`+ );+ }++ // JIT dependencies: line items before the document+ const itemRemoteIds = new Map<string, string>();+ for (const line of local.lines) {+ if (line.itemId && !itemRemoteIds.has(line.itemId)) {+ itemRemoteIds.set(+ line.itemId,+ await this.ensureDependencySynced("item", line.itemId)+ );+ }+ }++ const accountRefsById = await this.getAccountRefsById();+ const supplierEmail = await this.getSupplierEmail(local.supplierId);++ const docNumber = buildQboDocNumberFields(+ local.purchaseOrderId,+ local.supplierReference ? `Ref ${local.supplierReference}` : undefined+ );++ return {+ DocNumber: docNumber.DocNumber,+ PrivateNote: docNumber.PrivateNote,+ TxnDate: local.orderDate ?? undefined,+ VendorRef: { value: vendorRemoteId },+ POEmail: supplierEmail ? { Address: supplierEmail } : undefined,+ POStatus: mapCarbonPoStatusToQbo(local.status),+ Line: buildQboExpenseLines({+ lines: local.lines,+ itemRemoteIds,+ accountRefsById,+ documentLabel: `purchase order ${local.purchaseOrderId}`+ })+ };+ }++ /** Email of the supplier's first linked contact (for POEmail). */+ private async getSupplierEmail(supplierId: string): Promise<string | null> {+ const row = await this.database+ .selectFrom("supplierContact")+ .innerJoin("contact", "contact.id", "supplierContact.contactId")+ .select("contact.email")+ .where("supplierContact.supplierId", "=", supplierId)+ .executeTakeFirst();++ return row?.email ?? null;+ }++ // =================================================================+ // 6. TRANSFORMATION (QBO -> Carbon)+ // =================================================================++ protected async mapToLocal(+ remote: Qbo.PurchaseOrder+ ): Promise<Partial<Accounting.PurchaseOrder>> {+ return {+ purchaseOrderId: remote.DocNumber ?? remote.Id,+ supplierExternalId: remote.VendorRef.value,+ status: mapQboPoStatusToCarbon(remote.POStatus),+ orderDate: remote.TxnDate ?? null,+ totalAmount: remote.TotalAmt ?? 0,+ updatedAt:+ parseQboDate(remote.MetaData?.LastUpdatedTime)?.toISOString() ??+ new Date().toISOString()+ };+ }++ // =================================================================+ // 7. UPSERT LOCAL (Update existing only — Xero parity)+ // =================================================================++ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<Accounting.PurchaseOrder>,+ remoteId: string+ ): Promise<string> {+ const existingLocalId = await this.getLocalId(remoteId);++ if (!existingLocalId) {+ throw new Error(+ `Cannot create new purchase order from QuickBooks Online. PO with ID ${remoteId} must be created in Carbon first and then synced.`+ );+ }++ await tx+ .updateTable("purchaseOrder")+ .set({+ status: data.status,+ orderDate: data.orderDate,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", existingLocalId)+ .where("companyId", "=", this.companyId)+ .execute();++ return existingLocalId;+ }++ // =================================================================+ // 8. UPSERT REMOTE (create, or sparse update with SyncToken retry)+ // =================================================================++ protected async upsertRemote(+ data: Omit<Qbo.PurchaseOrder, QboWriteOmit>,+ localId: string+ ): Promise<string> {+ const existingRemoteId = await this.getRemoteId(localId);++ if (!existingRemoteId) {+ const created = await this.qboProvider.createPurchaseOrder(data);+ return created.Id;+ }++ const updated = await updateWithSyncTokenRetry({+ entityLabel: "purchase order",+ remoteId: existingRemoteId,+ fetchCurrent: () => this.qboProvider.getPurchaseOrder(existingRemoteId),+ update: (syncToken) =>+ this.qboProvider.updatePurchaseOrder({+ ...data,+ Id: existingRemoteId,+ SyncToken: syncToken+ })+ });+ return updated.Id;+ }++ protected async upsertRemoteBatch(+ data: Array<{+ localId: string;+ payload: Omit<Qbo.PurchaseOrder, QboWriteOmit>;+ }>+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>();+ for (const { localId, payload } of data) {+ result.set(localId, await this.upsertRemote(payload, localId));+ }+ return result;+ }++ // =================================================================+ // 9. SHOULD SYNC (same gate as the Xero counterpart)+ // =================================================================++ protected shouldSync(+ context: ShouldSyncContext<Accounting.PurchaseOrder, Qbo.PurchaseOrder>+ ): boolean | string {+ if (context.direction === "push" && context.localEntity) {+ if (!SYNCABLE_STATUSES.includes(context.localEntity.status)) {+ return `Purchase order must be in a locked status to sync (current: ${context.localEntity.status})`;+ }+ }++ return true;+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/shared.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/shared.tsnew file mode 100644index 0000000000..5b7c89f3b8--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/shared.ts@@ -0,0 +1,560 @@+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";+import { getAccountMappings } from "../../../core/account-mapping";+import { createMappingService } from "../../../core/external-mapping";+import { JournalEntrySyncError, roundCurrency } from "../../../core/posting";+import {+ type Accounting,+ BaseEntitySyncer,+ type BatchSyncResult,+ type SyncResult+} from "../../../core/types";+import { withTriggersDisabled } from "../../../core/utils";+import {+ parseQboDate,+ type Qbo,+ type QboCreatePayload,+ type QboEntityFields+} from "../models";+import {+ isQboDuplicateNameError,+ isQboStaleObjectError,+ QBO_FAULT_CODES,+ type QboProvider+} from "../provider";++/**+ * Shared plumbing for the QuickBooks Online entity syncers:+ *+ * - `QboEntitySyncer` — a thin BaseEntitySyncer specialization that (a)+ * preserves structured JournalEntrySyncFailure envelopes on+ * `SyncResult.error` for the master-data name failures (NAME_EXISTS,+ * NAME_TOO_LONG) via the same pushToAccounting-override pattern the Xero+ * JournalEntrySyncer established, and (b) records QBO's SyncToken ++ * MetaData.LastUpdatedTime on the mapping row (metadata / remoteUpdatedAt,+ * the Xero pattern).+ * - Pure mapping helpers (contact payloads, DocNumber 21-char rule, name+ * guards, the stale-SyncToken retry) exported for tests — client mocking+ * is impractical here, so behavior lives in pure functions per the+ * established pattern.+ */++/** Server-owned fields every QBO write payload omits (create) or echoes (update). */+export type QboWriteOmit = "Id" | "SyncToken" | "MetaData";++/** QBO caps entity names (Customer/Vendor DisplayName, Item Name) at 100 chars. */+export const QBO_NAME_MAX_LENGTH = 100;++/** QBO caps transaction DocNumber at 21 characters. */+export const QBO_DOC_NUMBER_MAX_LENGTH = 21;++/** Which field carries the Carbon readable id on a pushed QBO transaction. */+export type QboDocNumberSource = "docNumber" | "privateNote";++/** Escape a string literal for a QBO query WHERE clause (single quotes). */+export function escapeQboQueryValue(value: string): string {+ return value.replace(/'/g, "\\'");+}++/**+ * Apply QBO's 21-char DocNumber cap: a readable id that fits becomes the+ * DocNumber; a longer one moves to PrivateNote ("Carbon <id>") and QBO+ * auto-numbers the transaction. The `source` is recorded in the mapping+ * metadata so reconciliation knows where to find the Carbon id.+ */+export function buildQboDocNumberFields(+ readableId: string,+ extraNote?: string | null+): { DocNumber?: string; PrivateNote?: string; source: QboDocNumberSource } {+ if (readableId.length <= QBO_DOC_NUMBER_MAX_LENGTH) {+ return {+ DocNumber: readableId,+ PrivateNote: extraNote ?? undefined,+ source: "docNumber"+ };+ }++ const carrier = `Carbon ${readableId}`;+ return {+ PrivateNote: extraNote ? `${carrier} | ${extraNote}` : carrier,+ source: "privateNote"+ };+}++/**+ * Structured NAME_TOO_LONG failure (Warning — user-fixable by shortening+ * the name in Carbon; no silent truncation).+ */+export function qboNameTooLongError(args: {+ entityLabel: string;+ name: string;+}): JournalEntrySyncError {+ return new JournalEntrySyncError({+ errorCode: "NAME_TOO_LONG",+ message: `The ${args.entityLabel} name is ${args.name.length} characters; QuickBooks Online caps names at ${QBO_NAME_MAX_LENGTH}. Shorten the name in Carbon, then retry.`,+ warning: true,+ metadata: {+ entityLabel: args.entityLabel,+ name: args.name,+ maxLength: QBO_NAME_MAX_LENGTH+ }+ });+}++/**+ * Convert QBO's Duplicate Name Exists fault (Intuit code 6240 — QBO+ * customers, vendors and employees share one name namespace) into the+ * structured NAME_EXISTS Warning. Returns null for any other error.+ */+export function toQboNameExistsError(+ error: unknown,+ args: { entityLabel: string; name: string }+): JournalEntrySyncError | null {+ if (!isQboDuplicateNameError(error)) return null;++ return new JournalEntrySyncError({+ errorCode: "NAME_EXISTS",+ message: `QuickBooks Online already has an entity named "${args.name}" — QBO customers, vendors and employees share one name namespace. Rename the ${args.entityLabel} in Carbon or the conflicting entity in QuickBooks Online, then retry.`,+ warning: true,+ metadata: {+ entityLabel: args.entityLabel,+ name: args.name,+ qboFaultCode: QBO_FAULT_CODES.DUPLICATE_NAME_EXISTS+ }+ });+}++/**+ * Read-modify-write with QBO's optimistic concurrency: fetch the current+ * SyncToken, send the update, and on a Stale Object fault (5010) refetch+ * the token and retry EXACTLY once — a second stale fault propagates (the+ * operation lands Failed).+ */+export async function updateWithSyncTokenRetry<T>(args: {+ entityLabel: string;+ remoteId: string;+ fetchCurrent: () => Promise<{ SyncToken: string } | null>;+ update: (syncToken: string) => Promise<T>;+ isStaleTokenError?: (error: unknown) => boolean;+}): Promise<T> {+ const isStale = args.isStaleTokenError ?? isQboStaleObjectError;++ const current = await args.fetchCurrent();+ if (!current) {+ throw new Error(+ `Cannot update ${args.entityLabel} ${args.remoteId}: entity not found in QuickBooks Online`+ );+ }++ try {+ return await args.update(current.SyncToken);+ } catch (error) {+ if (!isStale(error)) throw error;++ const refetched = await args.fetchCurrent();+ if (!refetched) throw error;++ return args.update(refetched.SyncToken);+ }+}++/**+ * Carbon account.id → QBO AccountRef from the account-mapping rows+ * (entityType "account", integration "quickbooks"). QBO refs point at the+ * account Id, so the mapping's externalId is the ref value; the stored+ * externalName is display-only. Same resolution path the journal syncer+ * uses — QBO just needs the id where Xero needs the code.+ */+export async function loadQboAccountRefsById(+ database: Kysely<KyselyDatabase>,+ args: { companyId: string; integration: string }+): Promise<Map<string, Qbo.Ref>> {+ const mappings = await getAccountMappings(database, {+ companyId: args.companyId,+ integration: args.integration+ });++ if (mappings.error) {+ throw new Error(`Failed to load account mappings: ${mappings.error}`);+ }++ const refsById = new Map<string, Qbo.Ref>();+ for (const mapping of mappings.data ?? []) {+ if (mapping.externalId) {+ refsById.set(mapping.accountId, {+ value: mapping.externalId,+ name: mapping.externalName ?? undefined+ });+ }+ }+ return refsById;+}++/** Line input shared by Bill and PurchaseOrder expense-line building. */+export type QboExpenseLineInput = {+ itemId?: string | null;+ accountId?: string | null;+ description?: string | null;+ quantity: number;+ unitPrice: number;+ totalAmount: number;+};++/**+ * Build QBO expense-style lines (Bill / PurchaseOrder): item lines carry+ * ItemBasedExpenseLineDetail (ItemRef = the item's QBO id, resolved via+ * ensureDependencySynced before mapping), non-item lines carry+ * AccountBasedExpenseLineDetail with the mapped account. Pure — exported+ * for tests. Throws a plain Error (Failed, not Warning) when a non-item+ * line has no account or the account has no QBO mapping.+ */+export function buildQboExpenseLines(args: {+ lines: readonly QboExpenseLineInput[];+ itemRemoteIds: ReadonlyMap<string, string>;+ accountRefsById: ReadonlyMap<string, Qbo.Ref>;+ documentLabel: string;+}): Array<Omit<Qbo.ExpenseLine, "Id">> {+ return args.lines.map((line) => {+ const base = {+ Description: line.description ?? undefined,+ Amount: roundCurrency(line.totalAmount)+ };++ if (line.itemId) {+ const remoteItemId = args.itemRemoteIds.get(line.itemId);+ if (!remoteItemId) {+ throw new Error(+ `Cannot sync ${args.documentLabel}: item ${line.itemId} has not been synced to QuickBooks Online`+ );+ }+ return {+ ...base,+ DetailType: "ItemBasedExpenseLineDetail",+ ItemBasedExpenseLineDetail: {+ ItemRef: { value: remoteItemId },+ Qty: line.quantity,+ UnitPrice: line.unitPrice+ }+ };+ }++ if (!line.accountId) {+ throw new Error(+ `Cannot sync ${args.documentLabel}: a line has neither an item nor a G/L account`+ );+ }++ const accountRef = args.accountRefsById.get(line.accountId);+ if (!accountRef) {+ throw new Error(+ `Cannot sync ${args.documentLabel}: account ${line.accountId} has no QuickBooks Online account mapping. Map it on the integration settings page, then retry.`+ );+ }++ return {+ ...base,+ DetailType: "AccountBasedExpenseLineDetail",+ AccountBasedExpenseLineDetail: { AccountRef: accountRef }+ };+ });+}++/**+ * Map a Carbon customer/supplier to the QBO Customer/Vendor write payload+ * (identical shapes — QBO keeps them as separate objects, unlike Xero's+ * dual-flag Contact). Throws the structured NAME_TOO_LONG Warning when the+ * name exceeds QBO's 100-char DisplayName cap.+ */+export function mapContactToQboContact(+ local: Accounting.Contact,+ entityLabel: "customer" | "vendor"+): QboCreatePayload<Qbo.Customer> {+ if (local.name.length > QBO_NAME_MAX_LENGTH) {+ throw qboNameTooLongError({ entityLabel, name: local.name });+ }++ const phone = local.workPhone ?? local.mobilePhone ?? local.homePhone;+ const address = local.addresses[0];++ return {+ DisplayName: local.name,+ PrimaryEmailAddr: local.email ? { Address: local.email } : undefined,+ PrimaryPhone: phone ? { FreeFormNumber: phone } : undefined,+ BillAddr: address+ ? {+ Line1: address.line1 ?? undefined,+ Line2: address.line2 ?? undefined,+ City: address.city ?? undefined,+ CountrySubDivisionCode: address.region ?? undefined,+ Country: address.country ?? undefined,+ PostalCode: address.postalCode ?? undefined+ }+ : undefined,+ Active: true+ };+}++/**+ * Map a QBO Customer/Vendor back onto the Carbon contact shape (two-way+ * pull, owner accounting): name, email, phone and billing address per the+ * models. The caller sets the isCustomer/isVendor flags for its entity.+ */+export function mapQboContactToLocal(+ remote: Qbo.Customer | Qbo.Vendor,+ flags: { isCustomer: boolean; isVendor: boolean }+): Partial<Accounting.Contact> {+ const addresses: Accounting.Contact["addresses"] = remote.BillAddr+ ? [+ {+ label: null,+ type: "BILLING",+ line1: remote.BillAddr.Line1 ?? null,+ line2: remote.BillAddr.Line2 ?? null,+ city: remote.BillAddr.City ?? null,+ region: remote.BillAddr.CountrySubDivisionCode ?? null,+ country: remote.BillAddr.Country ?? null,+ postalCode: remote.BillAddr.PostalCode ?? null+ }+ ]+ : [];++ return {+ name: remote.DisplayName,+ email: remote.PrimaryEmailAddr?.Address ?? undefined,+ workPhone: remote.PrimaryPhone?.FreeFormNumber ?? null,+ isCustomer: flags.isCustomer,+ isVendor: flags.isVendor,+ addresses+ };+}++/**+ * Base class for the QBO master-data syncers (customer, vendor, item).+ *+ * Reimplements the push workflow with the SAME behavior as+ * BaseEntitySyncer.pushToAccounting (mapping check, shouldSync gate,+ * lastSyncedAt fast bailout, map → upsert → link) so that a thrown+ * JournalEntrySyncError reaches the caller as the structured failure object+ * on `SyncResult.error` — the base catch flattens every throw to a string,+ * which would lose errorCode/warning/metadata. The jobs drain detects the+ * envelope generically (isJournalEntrySyncFailure) and records Warning+ * operations for NAME_EXISTS / NAME_TOO_LONG. Everything that is not a+ * structured failure behaves exactly like the base workflow.+ *+ * Also centralizes the Xero-pattern mapping bookkeeping: `Id` is the+ * externalId, `SyncToken` goes into mapping metadata, and+ * `MetaData.LastUpdatedTime` fills `remoteUpdatedAt`.+ */+export abstract class QboEntitySyncer<+ TLocal,+ TRemote extends QboEntityFields+> extends BaseEntitySyncer<TLocal, TRemote, QboWriteOmit> {+ /**+ * SyncToken/LastUpdatedTime observed per remote id (from reads and write+ * responses), flushed into the mapping row by linkEntities. Bounded by+ * the drain's claim size — a syncer instance is short-lived.+ */+ private seenRemoteMeta = new Map<+ string,+ { syncToken?: string; lastUpdatedTime?: string }+ >();++ protected get qboProvider(): QboProvider {+ return this.provider as QboProvider;+ }++ /** Record a remote entity's concurrency metadata for the next linkEntities. */+ protected rememberRemoteEntity(+ remote: QboEntityFields | null | undefined+ ): void {+ if (!remote?.Id) return;+ this.seenRemoteMeta.set(remote.Id, {+ syncToken: remote.SyncToken,+ lastUpdatedTime: remote.MetaData?.LastUpdatedTime+ });+ }++ protected getRemoteUpdatedAt(remote: TRemote): Date | null {+ return parseQboDate(remote.MetaData?.LastUpdatedTime);+ }++ protected async linkEntities(+ tx: KyselyTx,+ localId: string,+ remoteId: string,+ remoteUpdatedAt?: Date+ ): Promise<void> {+ const seen = this.seenRemoteMeta.get(remoteId);+ const effectiveUpdatedAt =+ remoteUpdatedAt ?? parseQboDate(seen?.lastUpdatedTime) ?? undefined;++ const txMappingService = createMappingService(tx, this.companyId);+ await txMappingService.link(+ this.entityType,+ localId,+ this.provider.id,+ remoteId,+ {+ remoteUpdatedAt: effectiveUpdatedAt,+ ...(seen?.syncToken !== undefined+ ? { metadata: { syncToken: seen.syncToken } }+ : {})+ }+ );+ }++ /**+ * QBO has no bulk upsert endpoint for these entities — batch writes are+ * sequential single upserts (same per-entity SyncToken handling).+ */+ protected async upsertRemoteBatch(+ data: Array<{ localId: string; payload: Omit<TRemote, QboWriteOmit> }>+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>();+ for (const { localId, payload } of data) {+ result.set(localId, await this.upsertRemote(payload, localId));+ }+ return result;+ }++ /**+ * Base push workflow, verbatim in behavior, plus: a thrown+ * JournalEntrySyncError returns its structured failure on+ * `SyncResult.error` instead of a flattened string.+ */+ async pushToAccounting(entityId: string): Promise<SyncResult> {+ if (!this.config.enabled) {+ return {+ status: "skipped",+ action: "none",+ error: "Sync disabled in config"+ };+ }++ try {+ // 1. Check if already linked+ const existingMapping = await this.mappingService.getByEntity(+ this.entityType,+ entityId,+ this.provider.id+ );++ // 2. Fetch local entity+ const localEntity = await this.fetchLocal(entityId);+ if (!localEntity) {+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: `Entity ${entityId} not found in Carbon`+ };+ }++ // 3. Optional business-logic gate+ if (this.shouldSync) {+ const shouldSyncResult = await this.shouldSync({+ direction: "push",+ localEntity,+ isFirstSync: !existingMapping,+ entityId+ });++ if (shouldSyncResult !== true) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error:+ typeof shouldSyncResult === "string"+ ? shouldSyncResult+ : "Entity not eligible for sync"+ };+ }+ }++ const localUpdatedAt = new Date((localEntity as any).updatedAt);++ // 4. Fast bailout: already synced and local unchanged+ if (existingMapping?.lastSyncedAt) {+ if (localUpdatedAt <= new Date(existingMapping.lastSyncedAt)) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ remoteId: existingMapping.externalId,+ error: "Already synced - local unchanged"+ };+ }+ }++ // 5. Map and push+ const remotePayload = await this.mapToRemote(localEntity);+ const remoteId = await this.upsertRemote(remotePayload, entityId);++ // 6. Update mapping+ await withTriggersDisabled(this.database, async (tx) => {+ await this.linkEntities(tx, entityId, remoteId);+ });++ console.log("[SyncLog]", {+ direction: "PUSH",+ entity: this.entityType,+ localId: entityId,+ remoteId,+ status: "success"+ });++ return {+ status: "success",+ action: existingMapping ? "updated" : "created",+ localId: entityId,+ remoteId+ };+ } catch (err) {+ if (err instanceof JournalEntrySyncError) {+ console.error(`[${this.constructor.name}] structured push failure`, {+ entityId,+ ...err.failure+ });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err.failure+ };+ }++ console.error(`[${this.constructor.name}] push failed`, {+ entityId,+ err+ });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err instanceof Error ? err.message : String(err)+ };+ }+ }++ /**+ * Batch push composes the overridden single push so the structured+ * failures survive the drain's batch path too (the base batch loop+ * flattens errors to strings). Master-data operations arrive in+ * claim-sized batches, so a sequential loop costs nothing — and QBO has+ * no bulk endpoint to lose.+ */+ async pushBatchToAccounting(entityIds: string[]): Promise<BatchSyncResult> {+ const results: SyncResult[] = [];++ for (const entityId of entityIds) {+ results.push(await this.pushToAccounting(entityId));+ }++ return {+ results,+ successCount: results.filter((r) => r.status === "success").length,+ errorCount: results.filter((r) => r.status === "error").length,+ skippedCount: results.filter((r) => r.status === "skipped").length+ };+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/entities/vendor.ts b/packages/ee/src/accounting/providers/quickbooks-online/entities/vendor.tsnew file mode 100644index 0000000000..f617b91cb2--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/entities/vendor.ts@@ -0,0 +1,393 @@+import type { KyselyTx } from "@carbon/database/client";+import type { Accounting } from "../../../core/types";+import type { Qbo } from "../models";+import {+ escapeQboQueryValue,+ mapContactToQboContact,+ mapQboContactToLocal,+ QboEntitySyncer,+ type QboWriteOmit,+ toQboNameExistsError,+ updateWithSyncTokenRetry+} from "./shared";++/**+ * QboVendorSyncer — Carbon suppliers ↔ QBO Vendor objects.+ *+ * The vendor half of what Xero handles with one dual-flag ContactSyncer:+ * QBO Vendors are a separate object, so this syncer reads and writes the+ * supplier tables only, with mapping rows under entityType "vendor".+ * Same contract as QboCustomerSyncer: DisplayName 100-char cap →+ * NAME_TOO_LONG Warning, Duplicate Name Exists (6240) → NAME_EXISTS+ * Warning (shared name namespace), sparse updates with one+ * stale-SyncToken retry, two-way pull of name/email/phone/address.+ */++// Row shape for supplier queries with address and contact joins+type SupplierRow = {+ id: string;+ name: string;+ companyId: string;+ taxId: string | null;+ phone: string | null;+ fax: string | null;+ website: string | null;+ currencyCode: string | null;+ updatedAt: string | null;+ locationName: string | null;+ addressLine1: string | null;+ addressLine2: string | null;+ city: string | null;+ postalCode: string | null;+ contactFirstName: string | null;+ contactLastName: string | null;+ contactEmail: string | null;+ contactMobilePhone: string | null;+ contactHomePhone: string | null;+ contactWorkPhone: string | null;+};++export class QboVendorSyncer extends QboEntitySyncer<+ Accounting.Contact,+ Qbo.Vendor+> {+ // =================================================================+ // 1. ID MAPPING — default implementation (entityType "vendor")+ // =================================================================++ // =================================================================+ // 2. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.Contact | null> {+ const suppliers = await this.fetchSuppliersByIds([id]);+ return suppliers.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.Contact>> {+ return this.fetchSuppliersByIds(ids);+ }++ private async fetchSuppliersByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.Contact>> {+ if (ids.length === 0) return new Map();++ const rows = await (this.database as any)+ .selectFrom("supplier")+ .leftJoin("supplierTax", "supplierTax.supplierId", "supplier.id")+ .leftJoin(+ "supplierLocation",+ "supplierLocation.supplierId",+ "supplier.id"+ )+ .leftJoin("address", "address.id", "supplierLocation.addressId")+ .leftJoin("supplierContact", "supplierContact.supplierId", "supplier.id")+ .leftJoin("contact", "contact.id", "supplierContact.contactId")+ .select([+ "supplier.id",+ "supplier.name",+ "supplier.companyId",+ "supplierTax.taxId as taxId",+ "supplier.phone",+ "supplier.fax",+ "supplier.website",+ "supplier.currencyCode",+ "supplier.updatedAt",+ "supplierLocation.name as locationName",+ "address.addressLine1",+ "address.addressLine2",+ "address.city",+ "address.postalCode",+ "contact.firstName as contactFirstName",+ "contact.lastName as contactLastName",+ "contact.email as contactEmail",+ "contact.mobilePhone as contactMobilePhone",+ "contact.homePhone as contactHomePhone",+ "contact.workPhone as contactWorkPhone"+ ])+ .where("supplier.id", "in", ids)+ .where("supplier.companyId", "=", this.companyId)+ .execute();++ return this.groupAndTransformRows(rows as SupplierRow[]);+ }++ private groupAndTransformRows(+ rows: SupplierRow[]+ ): Map<string, Accounting.Contact> {+ const result = new Map<string, Accounting.Contact>();++ const groups = new Map<string, SupplierRow[]>();+ for (const row of rows) {+ const existing = groups.get(row.id) ?? [];+ existing.push(row);+ groups.set(row.id, existing);+ }++ for (const [id, groupRows] of groups) {+ const first = groupRows[0]!;+ const addresses = groupRows+ .filter((r) => r.addressLine1 || r.city)+ .map((r) => ({+ label: r.locationName ?? null,+ type: null,+ line1: r.addressLine1 ?? null,+ line2: r.addressLine2 ?? null,+ city: r.city ?? null,+ country: null,+ region: null,+ postalCode: r.postalCode ?? null+ }));++ result.set(id, {+ id: first.id,+ name: first.name,+ firstName: first.contactFirstName ?? "",+ lastName: first.contactLastName ?? "",+ companyId: first.companyId,+ email: first.contactEmail ?? undefined,+ website: first.website ?? null,+ taxId: first.taxId ?? null,+ currencyCode: first.currencyCode ?? "USD",+ balance: null,+ creditLimit: null,+ paymentTerms: null,+ updatedAt: first.updatedAt ?? new Date().toISOString(),+ workPhone: first.contactWorkPhone ?? first.phone ?? null,+ mobilePhone: first.contactMobilePhone ?? null,+ fax: first.fax ?? null,+ homePhone: first.contactHomePhone ?? null,+ isVendor: true,+ isCustomer: false,+ addresses,+ raw: first+ });+ }++ return result;+ }++ // =================================================================+ // 3. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Qbo.Vendor | null> {+ const vendor = await this.qboProvider.getVendor(id);+ this.rememberRemoteEntity(vendor);+ return vendor;+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Qbo.Vendor>> {+ const result = new Map<string, Qbo.Vendor>();+ if (ids.length === 0) return result;++ const values = ids.map((id) => `'${escapeQboQueryValue(id)}'`).join(", ");+ const vendors = await this.qboProvider.query<Qbo.Vendor>(+ "Vendor",+ `Id IN (${values})`+ );++ for (const vendor of vendors) {+ this.rememberRemoteEntity(vendor);+ result.set(vendor.Id, vendor);+ }++ return result;+ }++ // =================================================================+ // 4. TRANSFORMATION (Carbon -> QBO)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.Contact+ ): Promise<Omit<Qbo.Vendor, QboWriteOmit>> {+ return mapContactToQboContact(local, "vendor");+ }++ // =================================================================+ // 5. TRANSFORMATION (QBO -> Carbon)+ // =================================================================++ protected async mapToLocal(+ remote: Qbo.Vendor+ ): Promise<Partial<Accounting.Contact>> {+ return mapQboContactToLocal(remote, { isCustomer: false, isVendor: true });+ }++ // =================================================================+ // 6. UPSERT LOCAL+ // =================================================================++ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ remoteId: string+ ): Promise<string> {+ let existingLocalId = await this.getLocalId(remoteId);++ // Smart match by name during backfill (QBO DisplayNames and Carbon+ // supplier names are both unique per company).+ if (!existingLocalId && data.name) {+ const match = await tx+ .selectFrom("supplier")+ .select("id")+ .where("name", "=", data.name)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();+ existingLocalId = match?.id ?? null;+ }++ const supplierId = await this.upsertSupplier(tx, data, existingLocalId);+ await this.upsertContactAndLink(tx, data, supplierId);++ return supplierId;+ }++ private async upsertSupplier(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ existingId: string | null+ ): Promise<string> {+ if (existingId) {+ await tx+ .updateTable("supplier")+ .set({+ name: data.name,+ phone: data.workPhone,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", existingId)+ .execute();+ return existingId;+ }++ const result = await tx+ .insertInto("supplier")+ .values({+ companyId: this.companyId,+ name: data.name!,+ phone: data.workPhone,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString()+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ return result.id;+ }++ private async upsertContactAndLink(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ supplierId: string+ ): Promise<void> {+ const existingJunction = await tx+ .selectFrom("supplierContact")+ .select("contactId")+ .where("supplierId", "=", supplierId)+ .executeTakeFirst();++ const firstName = data.firstName || data.name || "";+ const lastName = data.lastName ?? "";++ if (existingJunction) {+ await tx+ .updateTable("contact")+ .set({+ email: data.email ?? null,+ firstName,+ lastName,+ workPhone: data.workPhone ?? null+ })+ .where("id", "=", existingJunction.contactId)+ .execute();+ return;+ }++ const contact = await tx+ .insertInto("contact")+ .values({+ companyId: this.companyId,+ email: data.email ?? null,+ firstName,+ lastName,+ workPhone: data.workPhone ?? null,+ isCustomer: false+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ await tx+ .insertInto("supplierContact")+ .values({+ companyId: this.companyId,+ supplierId,+ contactId: contact.id+ })+ .execute();+ }++ // =================================================================+ // 7. UPSERT REMOTE (create, or sparse update with SyncToken retry)+ // =================================================================++ protected async upsertRemote(+ data: Omit<Qbo.Vendor, QboWriteOmit>,+ localId: string+ ): Promise<string> {+ let existingRemoteId = await this.getRemoteId(localId);++ if (!existingRemoteId && data.DisplayName) {+ existingRemoteId = await this.findRemoteVendorByName(data.DisplayName);+ }++ try {+ if (!existingRemoteId) {+ const created = await this.qboProvider.createVendor(data);+ this.rememberRemoteEntity(created);+ return created.Id;+ }++ const remoteId = existingRemoteId;+ const updated = await updateWithSyncTokenRetry({+ entityLabel: "vendor",+ remoteId,+ fetchCurrent: () => this.qboProvider.getVendor(remoteId),+ update: (syncToken) =>+ this.qboProvider.updateVendor({+ ...data,+ Id: remoteId,+ SyncToken: syncToken+ })+ });+ this.rememberRemoteEntity(updated);+ return updated.Id;+ } catch (error) {+ const nameExists = toQboNameExistsError(error, {+ entityLabel: "vendor",+ name: data.DisplayName+ });+ if (nameExists) throw nameExists;+ throw error;+ }+ }++ private async findRemoteVendorByName(name: string): Promise<string | null> {+ const matches = await this.qboProvider.query<Qbo.Vendor>(+ "Vendor",+ `DisplayName = '${escapeQboQueryValue(name)}'`+ );++ const match = matches[0];+ if (!match) return null;++ this.rememberRemoteEntity(match);+ return match.Id;+ }+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/index.ts b/packages/ee/src/accounting/providers/quickbooks-online/index.tsnew file mode 100644index 0000000000..4745846cf6--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/index.ts@@ -0,0 +1,58 @@+import { ProviderID } from "../../core/models";+import { type SyncerRegistry, SyncFactory } from "../../core/sync";+import { QboBillSyncer } from "./entities/bill";+import { QboCustomerSyncer } from "./entities/customer";+import { QboSalesInvoiceSyncer } from "./entities/invoice";+import { QboItemSyncer } from "./entities/item";+import { QboJournalEntrySyncer } from "./entities/journal-entry";+import { QboPaymentSyncer } from "./entities/payment";+import { QboPurchaseOrderSyncer } from "./entities/purchase-order";+import { QboVendorSyncer } from "./entities/vendor";++export * from "./entities/bill";+export * from "./entities/customer";+export * from "./entities/invoice";+export * from "./entities/item";+// journal-entry exports mapJournalEntryToQboJournalEntry + the syncer for a+// future QBO daily-consolidation path, mirroring the Xero barrel's contract+export * from "./entities/journal-entry";+// payment exports the composite entity-id helpers + buildQboPaymentSyncChange+// the inbound QBO webhook route uses to enqueue operations+export * from "./entities/payment";+export * from "./entities/purchase-order";+export * from "./entities/shared";+export * from "./entities/vendor";+export * from "./models";+export * from "./provider";++/**+ * Every syncer QuickBooks Online implements, keyed by entity type. The+ * module-scope SyncFactory.register call below runs whenever this barrel+ * is imported — same contract as the Xero barrel (every consumer path+ * evaluates it before SyncFactory.getSyncer can be called with a QBO+ * context).+ */+export const qboSyncerRegistry: SyncerRegistry = {+ // Master Data — QBO keeps Customer and Vendor as separate objects+ // (no Xero-style dual-flag Contact), so each has its own syncer+ customer: QboCustomerSyncer,+ vendor: QboVendorSyncer,+ item: QboItemSyncer,++ // Transaction Data+ bill: QboBillSyncer,+ invoice: QboSalesInvoiceSyncer,+ purchaseOrder: QboPurchaseOrderSyncer,++ // Posting sync (push-only journal entries -> QBO JournalEntry objects)+ journalEntry: QboJournalEntrySyncer,++ // Pull-only (forced by buildQboSyncConfig): QBO Payment (AR) / BillPayment+ // (AP) settlements flow back onto Carbon sales/purchase invoices+ payment: QboPaymentSyncer++ // Not yet implemented:+ // - salesOrder / inventoryAdjustment / employee+};++SyncFactory.register(ProviderID.QUICKBOOKS, qboSyncerRegistry);diff --git a/packages/ee/src/accounting/providers/quickbooks-online/models.ts b/packages/ee/src/accounting/providers/quickbooks-online/models.tsnew file mode 100644index 0000000000..5764597147--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/models.ts@@ -0,0 +1,412 @@+import { z } from "zod";++/**+ * QuickBooks Online API entity schemas. Field sets are deliberately limited+ * to what the syncers map — QBO objects carry many more fields, and zod+ * strips unknown keys on parse. Reads (`query`, GET by id) return the full+ * shape including `Id`/`SyncToken`; create payloads omit them (`SyncToken`+ * is QBO's optimistic-concurrency token — every sparse update must echo the+ * latest value back).+ */+export namespace Qbo {+ /** Reference to another QBO entity, e.g. `{ value: "42", name: "Sales" }`. */+ export const RefSchema = z.object({+ value: z.string(),+ name: z.string().optional()+ });++ export type Ref = z.infer<typeof RefSchema>;++ export const MetaDataSchema = z.object({+ CreateTime: z.string().optional(),+ LastUpdatedTime: z.string()+ });++ export type MetaData = z.infer<typeof MetaDataSchema>;++ export const EmailAddressSchema = z.object({+ Address: z.string().optional()+ });++ export type EmailAddress = z.infer<typeof EmailAddressSchema>;++ export const TelephoneNumberSchema = z.object({+ FreeFormNumber: z.string().optional()+ });++ export type TelephoneNumber = z.infer<typeof TelephoneNumberSchema>;++ export const PhysicalAddressSchema = z.object({+ Id: z.string().optional(),+ Line1: z.string().optional(),+ Line2: z.string().optional(),+ City: z.string().optional(),+ /** State/province/region, e.g. "CA". */+ CountrySubDivisionCode: z.string().optional(),+ Country: z.string().optional(),+ PostalCode: z.string().optional()+ });++ export type PhysicalAddress = z.infer<typeof PhysicalAddressSchema>;++ /**+ * QBO Customer. `DisplayName` is unique across the shared name namespace+ * (customers, vendors and employees together).+ */+ export const CustomerSchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ DisplayName: z.string(),+ PrimaryEmailAddr: EmailAddressSchema.optional(),+ PrimaryPhone: TelephoneNumberSchema.optional(),+ BillAddr: PhysicalAddressSchema.optional(),+ Active: z.boolean().optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type Customer = z.infer<typeof CustomerSchema>;++ /** QBO Vendor — same field set as Customer (separate object in QBO). */+ export const VendorSchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ DisplayName: z.string(),+ PrimaryEmailAddr: EmailAddressSchema.optional(),+ PrimaryPhone: TelephoneNumberSchema.optional(),+ BillAddr: PhysicalAddressSchema.optional(),+ Active: z.boolean().optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type Vendor = z.infer<typeof VendorSchema>;++ /**+ * QBO Item. Carbon only ever writes `Service` or `NonInventory` — never+ * `Inventory` (QBO item-level tracking stays off; double-COGS guard).+ */+ export const ItemSchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ /** QBO caps item names at 100 characters. */+ Name: z.string().max(100),+ Description: z.string().optional(),+ Type: z.enum(["Service", "NonInventory"]),+ Active: z.boolean().optional(),+ UnitPrice: z.number().optional(),+ PurchaseCost: z.number().optional(),+ IncomeAccountRef: RefSchema.optional(),+ ExpenseAccountRef: RefSchema.optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type Item = z.infer<typeof ItemSchema>;++ export const SalesItemLineDetailSchema = z.object({+ ItemRef: RefSchema.optional(),+ Qty: z.number().optional(),+ UnitPrice: z.number().optional()+ });++ export type SalesItemLineDetail = z.infer<typeof SalesItemLineDetailSchema>;++ /**+ * Invoice line. `DetailType` stays a plain string because pulled invoices+ * include lines Carbon never writes (e.g. `SubTotalLineDetail`).+ */+ export const InvoiceLineSchema = z.object({+ Id: z.string().optional(),+ LineNum: z.number().optional(),+ Description: z.string().optional(),+ Amount: z.number(),+ DetailType: z.string(),+ SalesItemLineDetail: SalesItemLineDetailSchema.optional()+ });++ export type InvoiceLine = z.infer<typeof InvoiceLineSchema>;++ export const InvoiceSchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ /** QBO caps DocNumber at 21 characters. */+ DocNumber: z.string().optional(),+ TxnDate: z.string().optional(), // YYYY-MM-DD+ DueDate: z.string().optional(),+ CustomerRef: RefSchema,+ Line: z.array(InvoiceLineSchema),+ TotalAmt: z.number().optional(),+ Balance: z.number().optional(),+ PrivateNote: z.string().optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type Invoice = z.infer<typeof InvoiceSchema>;++ export const AccountBasedExpenseLineDetailSchema = z.object({+ AccountRef: RefSchema+ });++ export type AccountBasedExpenseLineDetail = z.infer<+ typeof AccountBasedExpenseLineDetailSchema+ >;++ export const ItemBasedExpenseLineDetailSchema = z.object({+ ItemRef: RefSchema.optional(),+ Qty: z.number().optional(),+ UnitPrice: z.number().optional()+ });++ export type ItemBasedExpenseLineDetail = z.infer<+ typeof ItemBasedExpenseLineDetailSchema+ >;++ /**+ * Expense-style line shared by Bill and PurchaseOrder: item lines carry+ * `ItemBasedExpenseLineDetail`, non-item lines carry+ * `AccountBasedExpenseLineDetail` with the mapped account.+ */+ export const ExpenseLineSchema = z.object({+ Id: z.string().optional(),+ LineNum: z.number().optional(),+ Description: z.string().optional(),+ Amount: z.number(),+ DetailType: z.string(),+ AccountBasedExpenseLineDetail:+ AccountBasedExpenseLineDetailSchema.optional(),+ ItemBasedExpenseLineDetail: ItemBasedExpenseLineDetailSchema.optional()+ });++ export type ExpenseLine = z.infer<typeof ExpenseLineSchema>;++ export const BillSchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ DocNumber: z.string().optional(),+ TxnDate: z.string().optional(),+ DueDate: z.string().optional(),+ VendorRef: RefSchema,+ Line: z.array(ExpenseLineSchema),+ /** ISO-4217 currency ref (`{ value: "EUR" }`) — set on FX bills. */+ CurrencyRef: RefSchema.optional(),+ /** Foreign→home exchange rate — set on FX bills (omitted at rate 1). */+ ExchangeRate: z.number().optional(),+ TotalAmt: z.number().optional(),+ Balance: z.number().optional(),+ PrivateNote: z.string().optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type Bill = z.infer<typeof BillSchema>;++ export const PurchaseOrderSchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ DocNumber: z.string().optional(),+ TxnDate: z.string().optional(),+ VendorRef: RefSchema,+ /** Email address the PO is sent to (supplier's primary contact). */+ POEmail: EmailAddressSchema.optional(),+ Line: z.array(ExpenseLineSchema),+ POStatus: z.enum(["Open", "Closed"]).optional(),+ TotalAmt: z.number().optional(),+ PrivateNote: z.string().optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type PurchaseOrder = z.infer<typeof PurchaseOrderSchema>;++ /**+ * A settled transaction referenced by a payment line. QBO BillPayment lines+ * carry `LinkedTxn[{ TxnId, TxnType:"Bill" }]`; Payment lines carry+ * `TxnType:"Invoice"`. Only the id + type are used (to resolve the Carbon+ * bill/invoice via the mapping table).+ */+ export const LinkedTxnSchema = z.object({+ TxnId: z.string(),+ TxnType: z.string(),+ TxnLineId: z.string().optional()+ });++ export type LinkedTxn = z.infer<typeof LinkedTxnSchema>;++ /**+ * A single application line on a Payment / BillPayment: `Amount` is the+ * amount applied to the linked document(s). `LinkedTxn` is normally a single+ * Bill/Invoice per line, but is modeled as an array (QBO's wire shape).+ */+ export const PaymentLineSchema = z.object({+ Amount: z.number().optional(),+ LinkedTxn: z.array(LinkedTxnSchema).optional()+ });++ export type PaymentLine = z.infer<typeof PaymentLineSchema>;++ /**+ * QBO Payment (Accounts Receivable): a customer payment applied to one or+ * more Invoices via `Line[].LinkedTxn{TxnType:"Invoice"}`. Lenient — only the+ * fields the payment syncer maps are modeled; QBO returns many more.+ */+ export const PaymentSchema = z.object({+ Id: z.string(),+ SyncToken: z.string().optional(),+ TxnDate: z.string().optional(), // YYYY-MM-DD+ TotalAmt: z.number().optional(),+ CurrencyRef: RefSchema.optional(),+ ExchangeRate: z.number().optional(),+ CustomerRef: RefSchema.optional(),+ PrivateNote: z.string().optional(),+ Line: z.array(PaymentLineSchema).optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type Payment = z.infer<typeof PaymentSchema>;++ /**+ * QBO BillPayment (Accounts Payable): a vendor payment applied to one or more+ * Bills via `Line[].LinkedTxn{TxnType:"Bill"}`. Same lenient contract as+ * PaymentSchema.+ */+ export const BillPaymentSchema = z.object({+ Id: z.string(),+ SyncToken: z.string().optional(),+ TxnDate: z.string().optional(),+ TotalAmt: z.number().optional(),+ CurrencyRef: RefSchema.optional(),+ ExchangeRate: z.number().optional(),+ VendorRef: RefSchema.optional(),+ PrivateNote: z.string().optional(),+ Line: z.array(PaymentLineSchema).optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type BillPayment = z.infer<typeof BillPaymentSchema>;++ export const JournalEntryLineDetailSchema = z.object({+ /** QBO journal lines are unsigned; the side lives here. */+ PostingType: z.enum(["Debit", "Credit"]),+ AccountRef: RefSchema,+ /** Dimension slot target "class" (QBO Class entity). */+ ClassRef: RefSchema.optional(),+ /** Dimension slot target "department" (QBO Department entity). */+ DepartmentRef: RefSchema.optional()+ });++ export type JournalEntryLineDetail = z.infer<+ typeof JournalEntryLineDetailSchema+ >;++ export const JournalEntryLineSchema = z.object({+ Id: z.string().optional(),+ Description: z.string().optional(),+ /** Always positive — direction comes from PostingType. */+ Amount: z.number(),+ DetailType: z.literal("JournalEntryLineDetail"),+ JournalEntryLineDetail: JournalEntryLineDetailSchema+ });++ export type JournalEntryLine = z.infer<typeof JournalEntryLineSchema>;++ export const JournalEntrySchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ DocNumber: z.string().optional(),+ TxnDate: z.string().optional(),+ PrivateNote: z.string().optional(),+ Line: z.array(JournalEntryLineSchema),+ MetaData: MetaDataSchema.optional()+ });++ export type JournalEntry = z.infer<typeof JournalEntrySchema>;++ /**+ * QBO Class — the class-tracking analytics entity journal lines+ * reference via `JournalEntryLineDetail.ClassRef`. Feature-gated by the+ * Intuit plan; orgs without class tracking reject the query.+ */+ export const ClassSchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ Name: z.string(),+ FullyQualifiedName: z.string().optional(),+ Active: z.boolean().optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type Class = z.infer<typeof ClassSchema>;++ /** QBO Department (a.k.a. Location) — referenced via `DepartmentRef`. */+ export const DepartmentSchema = z.object({+ Id: z.string(),+ SyncToken: z.string(),+ Name: z.string(),+ FullyQualifiedName: z.string().optional(),+ Active: z.boolean().optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type Department = z.infer<typeof DepartmentSchema>;++ /**+ * Chart-of-accounts entry. `AcctNum` is optional in QBO — the account+ * mapping falls back to `Id` when no number is assigned.+ */+ export const AccountSchema = z.object({+ Id: z.string(),+ Name: z.string(),+ AcctNum: z.string().optional(),+ AccountType: z.string(),+ /** "Asset" | "Liability" | "Equity" | "Revenue" | "Expense" */+ Classification: z.string().optional(),+ Active: z.boolean().optional()+ });++ export type Account = z.infer<typeof AccountSchema>;++ /** Company profile returned by GET /companyinfo/{realmId}. */+ export const CompanyInfoSchema = z.object({+ Id: z.string(),+ SyncToken: z.string().optional(),+ CompanyName: z.string(),+ LegalName: z.string().optional(),+ Country: z.string().optional(),+ MetaData: MetaDataSchema.optional()+ });++ export type CompanyInfo = z.infer<typeof CompanyInfoSchema>;+}++/**+ * Fields every persisted QBO entity carries. Reads return them; write+ * payloads treat them per QboCreatePayload/QboUpdatePayload below.+ */+export type QboEntityFields = {+ Id: string;+ SyncToken: string;+ MetaData?: Qbo.MetaData;+};++/**+ * Create payload: QBO assigns Id/SyncToken/MetaData, so a create POST body+ * omits them.+ */+export type QboCreatePayload<T extends QboEntityFields> = Omit<+ T,+ "Id" | "SyncToken" | "MetaData"+>;++/**+ * Update payload: QBO's optimistic concurrency requires echoing the current+ * SyncToken with the target Id; MetaData stays server-owned. Updates are+ * sent sparse (only the provided fields change).+ */+export type QboUpdatePayload<T extends QboEntityFields> = QboCreatePayload<T> &+ Pick<T, "Id" | "SyncToken">;++/**+ * Parse a QBO MetaData timestamp (ISO 8601 with offset, e.g.+ * "2026-07-01T13:07:59-07:00"). Returns null for missing/invalid values.+ */+export function parseQboDate(value: string | null | undefined): Date | null {+ if (!value) return null;+ const parsed = new Date(value);+ return Number.isNaN(parsed.getTime()) ? null : parsed;+}diff --git a/packages/ee/src/accounting/providers/quickbooks-online/provider.ts b/packages/ee/src/accounting/providers/quickbooks-online/provider.tsnew file mode 100644index 0000000000..4fc8b323ef--- /dev/null+++ b/packages/ee/src/accounting/providers/quickbooks-online/provider.ts@@ -0,0 +1,1203 @@+import { z } from "zod";+import { ProviderID } from "../../core/models";+import type {+ AccountingEntityType,+ DimensionTarget,+ GlobalSyncConfig,+ ListChangesResult,+ ProviderCapabilities,+ ProviderChange,+ ProviderConfig,+ ProviderCredentials+} from "../../core/types";+import { BaseProvider } from "../../core/types";+import {+ AccountingApiError,+ type ApiErrorDetails,+ createOAuthClient,+ HTTPClient,+ type HttpResponse+} from "../../core/utils";+import { buildQboPaymentSyncChange } from "./entities/payment";+import {+ parseQboDate,+ type Qbo,+ type QboCreatePayload,+ type QboUpdatePayload+} from "./models";++const QBO_PRODUCTION_HOST = "https://quickbooks.api.intuit.com";+const QBO_SANDBOX_HOST = "https://sandbox-quickbooks.api.intuit.com";++/**+ * Intuit's OAuth2 bearer endpoint handles both the authorization-code+ * exchange and the refresh_token grant. It requires+ * `Authorization: Basic base64(clientId:clientSecret)` — which is exactly+ * what `createOAuthClient` sends.+ */+const QBO_TOKEN_URL =+ "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer";+const QBO_AUTHORIZE_URL = "https://appcenter.intuit.com/connect/oauth2";++/** Pinned QBO API minor version — bump deliberately, in one place. */+export const QBO_MINOR_VERSION = "75";++/** QBO's hard upper bound for MAXRESULTS on /query. */+export const QBO_QUERY_MAX_RESULTS = 1000;++/**+ * Dimension slot target ids (stored on+ * settings.postingSync.dimensionSlots[].target): a slotted Carbon+ * dimension maps to the journal line's ClassRef or DepartmentRef.+ */+export const QBO_DIMENSION_TARGET_CLASS = "class";+export const QBO_DIMENSION_TARGET_DEPARTMENT = "department";++export type QboEnvironment = "sandbox" | "production";++// /********************************************************\+// * QBO fault parsing *+// \********************************************************/++/**+ * Intuit fault codes the syncers branch on. Codes arrive as strings in the+ * Fault body (`Fault.Error[].code`).+ */+export const QBO_FAULT_CODES = {+ /** "Duplicate Name Exists Error" — QBO's shared name namespace (customers, vendors, employees, items). */+ DUPLICATE_NAME_EXISTS: "6240",+ /** "Stale Object Error" — the SyncToken sent is no longer current. */+ STALE_OBJECT: "5010",+ /** "Account Period Closed" — books are closed for the transaction date. */+ ACCOUNT_PERIOD_CLOSED: "6210"+} as const;++type QboFaultError = {+ Message?: string;+ Detail?: string;+ code?: string;+ element?: string;+};++type QboFaultBody = {+ Fault?: {+ Error?: QboFaultError[];+ type?: string;+ };+};++/**+ * Parse a QBO error response into structured ApiErrorDetails. QBO returns+ * `{ Fault: { Error: [{ Message, Detail, code, element }], type } }`;+ * OAuth-shaped errors and plain strings fall through with a best-effort+ * message.+ */+export function extractQboErrorDetails(+ statusCode: number,+ statusText: string,+ responseData: unknown+): ApiErrorDetails {+ const details: ApiErrorDetails = {+ statusCode,+ statusText,+ rawResponse: responseData+ };++ let data: unknown = responseData;+ if (typeof responseData === "string") {+ try {+ data = JSON.parse(responseData);+ } catch {+ if (responseData.length < 500) {+ details.providerMessage = responseData;+ }+ return details;+ }+ }++ if (typeof data !== "object" || data === null) {+ return details;+ }++ const fault = (data as QboFaultBody).Fault;+ if (fault) {+ if (typeof fault.type === "string") {+ details.providerErrorType = fault.type;+ }++ const errors = Array.isArray(fault.Error) ? fault.Error : [];+ const first = errors[0];+ if (first?.code !== undefined) {+ details.providerErrorCode = first.code;+ }+ if (first?.Message || first?.Detail) {+ details.providerMessage = first.Detail ?? first.Message;+ }++ const validationErrors = errors+ .filter((error) => error.Message || error.Detail)+ .map((error) => ({+ field: error.element || undefined,+ message: error.Detail ?? error.Message ?? ""+ }));+ if (validationErrors.length > 0) {+ details.validationErrors = validationErrors;+ }++ return details;+ }++ // OAuth-style error body+ const obj = data as Record<string, unknown>;+ if (typeof obj.error_description === "string") {+ details.providerMessage = obj.error_description;+ details.providerErrorType = obj.error as string;+ } else if (typeof obj.message === "string") {+ details.providerMessage = obj.message;+ }++ return details;+}++/**+ * Creates, logs and throws an AccountingApiError from a failed QBO+ * response (parallel to throwXeroApiError).+ */+export function throwQboApiError(+ operation: string,+ response: { error: boolean; message: string; code: number; data: unknown }+): never {+ const details = extractQboErrorDetails(+ response.code,+ response.message,+ response.data+ );++ const error = new AccountingApiError("quickbooks", operation, details);++ console.error(`[QBO API Error] ${operation}`, {+ statusCode: details.statusCode,+ statusText: details.statusText,+ providerErrorType: details.providerErrorType,+ providerErrorCode: details.providerErrorCode,+ providerMessage: details.providerMessage,+ validationErrors: details.validationErrors+ });++ throw error;+}++/** The Intuit fault code carried by a thrown AccountingApiError, if any. */+export function getQboFaultCode(error: unknown): string | null {+ if (!(error instanceof AccountingApiError)) return null;+ const code = error.details.providerErrorCode;+ return code === undefined ? null : String(code);+}++/** True for QBO's Duplicate Name Exists fault (Intuit code 6240). */+export function isQboDuplicateNameError(error: unknown): boolean {+ return getQboFaultCode(error) === QBO_FAULT_CODES.DUPLICATE_NAME_EXISTS;+}++/** True for QBO's Stale Object fault (Intuit code 5010 — stale SyncToken). */+export function isQboStaleObjectError(error: unknown): boolean {+ return getQboFaultCode(error) === QBO_FAULT_CODES.STALE_OBJECT;+}++/**+ * True for QBO's Account Period Closed fault (Intuit code 6210 — the books+ * are closed for the transaction date).+ */+export function isQboAccountPeriodClosedError(error: unknown): boolean {+ return getQboFaultCode(error) === QBO_FAULT_CODES.ACCOUNT_PERIOD_CLOSED;+}++/**+ * Envelope returned by GET /query. The page rows live under the entity+ * name (e.g. `QueryResponse.Customer`).+ */+export type QboQueryResponse = {+ QueryResponse?: {+ startPosition?: number;+ maxResults?: number;+ totalCount?: number;+ } & Record<string, unknown>;+ time?: string;+};++function getOAuth2Credentials(+ credentials: ProviderCredentials+): Extract<ProviderCredentials, { type: "oauth2" }> {+ if (credentials.type !== "oauth2") {+ throw new Error(+ `QuickBooks Online requires oauth2 credentials, received "${credentials.type}"`+ );+ }+ return credentials;+}++/**+ * QBO stores its company id under `providerMetadata.realmId` (captured from+ * the OAuth callback query params). Throws when it is missing — every QBO+ * API path embeds the realm, and a descriptive error beats an opaque 401.+ */+function getQboRealmId(+ credentials: ProviderCredentials,+ fallbackRealmId?: string+): string {+ const { providerMetadata } = getOAuth2Credentials(credentials);+ const metadataRealmId = providerMetadata?.realmId;+ const realmId =+ typeof metadataRealmId === "string" && metadataRealmId.length > 0+ ? metadataRealmId+ : fallbackRealmId;++ if (!realmId) {+ throw new Error(+ "QuickBooks Online credentials are missing realmId (providerMetadata.realmId). Reconnect the QuickBooks Online integration to select a company."+ );+ }++ return realmId;+}++/**+ * Every QBO endpoint lives under /v3/company/{realmId} and carries the+ * pinned minorversion query param.+ */+function buildCompanyPath(realmId: string, url: string): string {+ const separator = url.includes("?") ? "&" : "?";+ return `/v3/company/${realmId}${url}${separator}minorversion=${QBO_MINOR_VERSION}`;+}++type QboProviderConfig = ProviderConfig<{+ clientId: string;+ clientSecret: string;+ redirectUri?: string;+ realmId?: string;+ /** Selects the Intuit host; production unless explicitly "sandbox". */+ environment?: QboEnvironment;+}> & {+ id: ProviderID.QUICKBOOKS;+ accessToken?: string;+ refreshToken?: string;+};++/**+ * Entities QBO syncs TWO-WAY: `payment`. Inbound (pull) — QBO Payment/BillPayment+ * settlements flow back onto Carbon sales/purchase invoices (Phase F). Outbound+ * (push) — Carbon-born Posted payments are written to QBO as Payment/BillPayment+ * documents so the settled invoice/bill closes (Phase G). Which direction fires+ * per record is decided by origin: a payment already carrying a `payment`+ * mapping is provider-known and skips push; a mapping-less Carbon payment is+ * pushed. Forced two-way AND enabled — both halves must work as soon as the+ * integration is connected (there is no per-company toggle for it; the+ * documents-mode families gate governs whether it actually runs). Mirrors+ * Rillet's RILLET_TWO_WAY_ENTITIES.+ */+export const QBO_TWO_WAY_ENTITIES = [+ "payment"+] as const satisfies readonly AccountingEntityType[];++/**+ * Master + document entities for which Carbon is the system of record:+ * customers, vendors, items, sales invoices, and bills. Forced+ * `push-to-accounting` / `owner: "carbon"` so QBO is a downstream mirror —+ * Carbon's edits always win, and an inbound QBO change to a linked record is+ * skipped by BaseEntitySyncer's owner guard. This is the standardized "Carbon+ * owns everything" stance that replaced the per-entity Source of Truth setting;+ * it mirrors Rillet's RILLET_PUSH_ONLY_ENTITIES. Their per-company `enabled`+ * flag survives — this constrains ownership, not whether they sync. `payment`+ * is deliberately excluded: the accounting system owns payments (see+ * QBO_TWO_WAY_ENTITIES).+ */+export const QBO_CARBON_OWNED_ENTITIES = [+ "customer",+ "vendor",+ "item",+ "invoice",+ "bill"+] as const satisfies readonly AccountingEntityType[];++/**+ * Overlay QBO's capability + ownership forcing on a resolved sync config:+ * customers/vendors/items/invoices/bills forced push-only + owner "carbon"+ * (Carbon owns them); `payment` forced two-way + enabled (the accounting system+ * owns it; Carbon-born payments push back out — Phase G). Every other entity+ * keeps its resolved config.+ */+export function buildQboSyncConfig(+ resolved: GlobalSyncConfig+): GlobalSyncConfig {+ const entities = Object.fromEntries(+ Object.entries(resolved.entities).map(([entityType, entityConfig]) => [+ entityType,+ { ...entityConfig }+ ])+ ) as GlobalSyncConfig["entities"];++ for (const entityType of QBO_CARBON_OWNED_ENTITIES) {+ entities[entityType] = {+ ...entities[entityType],+ direction: "push-to-accounting",+ owner: "carbon"+ };+ }++ for (const entityType of QBO_TWO_WAY_ENTITIES) {+ entities[entityType] = {+ ...entities[entityType],+ direction: "two-way",+ owner: "accounting",+ enabled: true+ };+ }++ // Always-on: automated postings sync whenever the integration is connected.+ // Forced here (defense-in-depth over the DEFAULT_SYNC_CONFIG default) so a+ // stale stored `enabled: false` override can't silently turn journals off.+ entities.journalEntry = { ...entities.journalEntry, enabled: true };++ return { entities };+}++export class QboProvider extends BaseProvider {+ static id = ProviderID.QUICKBOOKS;++ readonly capabilities: ProviderCapabilities = {+ transport: "rest",+ supportsWebhooks: false,+ supportsJournalPush: true,+ // One ClassRef + one DepartmentRef per journal line — 2 fixed slots+ maxJournalDimensionSlots: 2+ };++ http: HTTPClient;++ private readonly syncConfig!: GlobalSyncConfig;++ constructor(public config: Omit<QboProviderConfig, "id">) {+ super();+ // `payment` is forced two-way + enabled (see buildQboSyncConfig).+ this.syncConfig = buildQboSyncConfig(config.syncConfig);+ this.http = new HTTPClient(+ config.environment === "sandbox" ? QBO_SANDBOX_HOST : QBO_PRODUCTION_HOST+ );+ this.auth = createOAuthClient({+ clientId: config.clientId,+ clientSecret: config.clientSecret,+ accessToken: config.accessToken,+ refreshToken: config.refreshToken,+ redirectUri: config.redirectUri,+ tokenUrl: QBO_TOKEN_URL,+ onTokenRefresh: config.onTokenRefresh,+ getAuthUrl(scopes: string[], redirectURL: string): string {+ const params = new URLSearchParams({+ response_type: "code",+ client_id: config.clientId,+ redirect_uri: redirectURL,+ scope: scopes.join(" "),+ state: crypto.randomUUID()+ });++ return `${QBO_AUTHORIZE_URL}?${params.toString()}`;+ }+ });+ }++ get id(): ProviderID.QUICKBOOKS {+ return ProviderID.QUICKBOOKS;+ }++ getSyncConfig(entity: AccountingEntityType) {+ return this.syncConfig.entities[entity];+ }++ authenticate(+ code: string,+ redirectUri: string+ ): Promise<ProviderCredentials> {+ return this.auth.exchangeCode(code, redirectUri);+ }++ async request<T>(+ method: string,+ url: string,+ options?: RequestInit+ ): Promise<HttpResponse<T>> {+ const credentials = this.auth.getCredentials();+ const { accessToken } = getOAuth2Credentials(credentials);+ const realmId = getQboRealmId(credentials, this.config.realmId);++ const headers: Record<string, string> = {+ Authorization: `Bearer ${accessToken}`,+ Accept: "application/json",+ "Content-Type": "application/json",+ ...((options?.headers ?? {}) as Record<string, string>)+ };++ const path = buildCompanyPath(realmId, url);++ const response = await this.http.request<T>(method, path, {+ ...options,+ headers+ });++ if (response.code === 401) {+ // Single retry: refresh via Intuit's refresh_token grant (Basic auth,+ // handled by createOAuthClient which persists the new tokens through+ // the onTokenRefresh callback), then replay the request once.+ await this.auth.refresh();++ const { accessToken: refreshedAccessToken } = getOAuth2Credentials(+ this.auth.getCredentials()+ );++ const retryHeaders: Record<string, string> = {+ ...headers,+ Authorization: `Bearer ${refreshedAccessToken}`+ };++ return this.http.request<T>(method, path, {+ ...options,+ headers: retryHeaders+ });+ }++ return response;+ }++ /**+ * Run a QBO query (`SELECT * FROM <entity> [WHERE ...]`) and page through+ * the results with STARTPOSITION/MAXRESULTS until a short page signals+ * the end. `maxResults` is the page size, capped at QBO's limit of 1000.+ */+ async query<T>(+ entity: string,+ where?: string,+ startPosition = 1,+ maxResults = QBO_QUERY_MAX_RESULTS+ ): Promise<T[]> {+ const pageSize = Math.max(1, Math.min(maxResults, QBO_QUERY_MAX_RESULTS));+ const rows: T[] = [];+ let position = startPosition;++ while (true) {+ const statement = `SELECT * FROM ${entity}${+ where ? ` WHERE ${where}` : ""+ } STARTPOSITION ${position} MAXRESULTS ${pageSize}`;++ const response = await this.request<QboQueryResponse>(+ "GET",+ `/query?query=${encodeURIComponent(statement)}`+ );++ if (response.error) {+ throw new AccountingApiError("quickbooks", `query ${entity}`, {+ statusCode: response.code,+ statusText: response.message,+ rawResponse: response.data+ });+ }++ const page =+ (response.data?.QueryResponse?.[entity] as T[] | undefined) ?? [];+ rows.push(...page);++ if (page.length < pageSize) break;+ position += pageSize;+ }++ return rows;+ }++ async validate(): Promise<boolean> {+ try {+ const companyInfo = await this.getCompanyInfo();+ return companyInfo !== null;+ } catch (error) {+ console.error("QuickBooks Online validate error:", error);+ return false;+ }+ }++ /**+ * Fetch the QBO company profile (GET /companyinfo/{realmId}).+ * Returns null when the request fails.+ */+ async getCompanyInfo(): Promise<Qbo.CompanyInfo | null> {+ const realmId = getQboRealmId(+ this.auth.getCredentials(),+ this.config.realmId+ );++ const response = await this.request<{ CompanyInfo: Qbo.CompanyInfo }>(+ "GET",+ `/companyinfo/${realmId}`+ );++ if (response.error || !response.data?.CompanyInfo) {+ return null;+ }++ return response.data.CompanyInfo;+ }++ // =================================================================+ // Chart of accounts+ // =================================================================++ /**+ * Fetch the active QBO chart of accounts, normalized to the+ * `{ id, code, name }` shape the settings loader / account-mapping UI+ * consumes (the same shape it builds from XeroProvider's raw list).+ * QBO account numbers (`AcctNum`) are optional — `code` falls back to+ * the account `Id`. Returns [] on failure, mirroring Xero's forgiving+ * contract.+ */+ async listChartOfAccounts(): Promise<+ Array<{ id: string; code: string; name: string }>+ > {+ try {+ const accounts = await this.query<Qbo.Account>(+ "Account",+ "Active = true"+ );+ return accounts.map((account) => ({+ id: account.Id,+ code: account.AcctNum ?? account.Id,+ name: account.Name+ }));+ } catch (error) {+ console.error("Failed to fetch QuickBooks Online accounts:", error);+ return [];+ }+ }++ // =================================================================+ // Entity reads/writes (create = POST /{entity}; update = the same POST+ // echoing Id + the current SyncToken, sent sparse so unspecified fields+ // are preserved — the intent Xero's full-payload POST updates carry)+ // =================================================================++ private async readEntity<T>(+ resource: string,+ envelopeKey: string,+ id: string+ ): Promise<T | null> {+ const response = await this.request<Record<string, T>>(+ "GET",+ `/${resource}/${id}`+ );+ if (response.error) return null;+ return response.data?.[envelopeKey] ?? null;+ }++ private async writeEntity<T>(+ resource: string,+ envelopeKey: string,+ operation: string,+ payload: unknown+ ): Promise<T> {+ const response = await this.request<Record<string, T>>(+ "POST",+ `/${resource}`,+ { body: JSON.stringify(payload) }+ );++ if (response.error) {+ throwQboApiError(operation, response);+ }++ const entity = response.data?.[envelopeKey];+ if (!entity) {+ throw new Error(+ `QuickBooks Online returned success but no ${envelopeKey} was returned for ${operation}`+ );+ }++ return entity;+ }++ private updateBody<T extends { Id: string; SyncToken: string }>(+ payload: T+ ): T & { sparse: true } {+ return { ...payload, sparse: true };+ }++ async getCustomer(id: string): Promise<Qbo.Customer | null> {+ return this.readEntity<Qbo.Customer>("customer", "Customer", id);+ }++ async createCustomer(+ customer: QboCreatePayload<Qbo.Customer>+ ): Promise<Qbo.Customer> {+ return this.writeEntity(+ "customer",+ "Customer",+ "create customer",+ customer+ );+ }++ async updateCustomer(+ customer: QboUpdatePayload<Qbo.Customer>+ ): Promise<Qbo.Customer> {+ return this.writeEntity(+ "customer",+ "Customer",+ "update customer",+ this.updateBody(customer)+ );+ }++ async getVendor(id: string): Promise<Qbo.Vendor | null> {+ return this.readEntity<Qbo.Vendor>("vendor", "Vendor", id);+ }++ async createVendor(+ vendor: QboCreatePayload<Qbo.Vendor>+ ): Promise<Qbo.Vendor> {+ return this.writeEntity("vendor", "Vendor", "create vendor", vendor);+ }++ async updateVendor(+ vendor: QboUpdatePayload<Qbo.Vendor>+ ): Promise<Qbo.Vendor> {+ return this.writeEntity(+ "vendor",+ "Vendor",+ "update vendor",+ this.updateBody(vendor)+ );+ }++ async getItem(id: string): Promise<Qbo.Item | null> {+ return this.readEntity<Qbo.Item>("item", "Item", id);+ }++ async createItem(item: QboCreatePayload<Qbo.Item>): Promise<Qbo.Item> {+ return this.writeEntity("item", "Item", "create item", item);+ }++ async updateItem(item: QboUpdatePayload<Qbo.Item>): Promise<Qbo.Item> {+ return this.writeEntity(+ "item",+ "Item",+ "update item",+ this.updateBody(item)+ );+ }++ async getInvoice(id: string): Promise<Qbo.Invoice | null> {+ return this.readEntity<Qbo.Invoice>("invoice", "Invoice", id);+ }++ async createInvoice(+ invoice: QboCreatePayload<Qbo.Invoice>+ ): Promise<Qbo.Invoice> {+ return this.writeEntity("invoice", "Invoice", "create invoice", invoice);+ }++ async updateInvoice(+ invoice: QboUpdatePayload<Qbo.Invoice>+ ): Promise<Qbo.Invoice> {+ return this.writeEntity(+ "invoice",+ "Invoice",+ "update invoice",+ this.updateBody(invoice)+ );+ }++ async getBill(id: string): Promise<Qbo.Bill | null> {+ return this.readEntity<Qbo.Bill>("bill", "Bill", id);+ }++ async createBill(bill: QboCreatePayload<Qbo.Bill>): Promise<Qbo.Bill> {+ return this.writeEntity("bill", "Bill", "create bill", bill);+ }++ async updateBill(bill: QboUpdatePayload<Qbo.Bill>): Promise<Qbo.Bill> {+ return this.writeEntity(+ "bill",+ "Bill",+ "update bill",+ this.updateBody(bill)+ );+ }++ async getPurchaseOrder(id: string): Promise<Qbo.PurchaseOrder | null> {+ return this.readEntity<Qbo.PurchaseOrder>(+ "purchaseorder",+ "PurchaseOrder",+ id+ );+ }++ async createPurchaseOrder(+ purchaseOrder: QboCreatePayload<Qbo.PurchaseOrder>+ ): Promise<Qbo.PurchaseOrder> {+ return this.writeEntity(+ "purchaseorder",+ "PurchaseOrder",+ "create purchase order",+ purchaseOrder+ );+ }++ async updatePurchaseOrder(+ purchaseOrder: QboUpdatePayload<Qbo.PurchaseOrder>+ ): Promise<Qbo.PurchaseOrder> {+ return this.writeEntity(+ "purchaseorder",+ "PurchaseOrder",+ "update purchase order",+ this.updateBody(purchaseOrder)+ );+ }++ // =================================================================+ // Payments (two-way) — directly addressable by id+ // =================================================================++ /** GET /payment/{id} — a QBO Payment (Accounts Receivable). */+ async getPayment(id: string): Promise<Qbo.Payment | null> {+ return this.readEntity<Qbo.Payment>("payment", "Payment", id);+ }++ /** GET /billpayment/{id} — a QBO BillPayment (Accounts Payable). */+ async getBillPayment(id: string): Promise<Qbo.BillPayment | null> {+ return this.readEntity<Qbo.BillPayment>("billpayment", "BillPayment", id);+ }++ /**+ * Create a QBO Payment (POST /payment) — a customer payment applied to+ * Invoice(s) via `Line[].LinkedTxn{TxnType:"Invoice"}` (Phase G AR+ * write-back). The write payload carries CustomerRef + DepositToAccountRef,+ * which the read schema omits; writeEntity sends it as-is and QBO echoes back+ * the created Payment. Returns the created payment Id.+ */+ async createPayment(payload: QboPaymentCreatePayload): Promise<string> {+ const created = await this.writeEntity<Qbo.Payment>(+ "payment",+ "Payment",+ "create payment",+ payload+ );+ return created.Id;+ }++ /**+ * Create a QBO BillPayment (POST /billpayment) — a vendor payment applied to+ * Bill(s) via `Line[].LinkedTxn{TxnType:"Bill"}` (Phase G AP write-back). The+ * write payload carries VendorRef + PayType/CheckPayment, which the read+ * schema omits; writeEntity sends it as-is and QBO echoes back the created+ * BillPayment. Returns the created bill-payment Id.+ */+ async createBillPayment(+ payload: QboBillPaymentCreatePayload+ ): Promise<string> {+ const created = await this.writeEntity<Qbo.BillPayment>(+ "billpayment",+ "BillPayment",+ "create bill payment",+ payload+ );+ return created.Id;+ }++ async getJournalEntry(id: string): Promise<Qbo.JournalEntry | null> {+ return this.readEntity<Qbo.JournalEntry>(+ "journalentry",+ "JournalEntry",+ id+ );+ }++ /**+ * Create a QBO journal entry. No update counterpart: pushed journals are+ * immutable (the journal syncer hard-skips already-mapped ids), so the+ * SyncToken echo path never applies.+ */+ async createJournalEntry(+ journalEntry: QboCreatePayload<Qbo.JournalEntry>+ ): Promise<Qbo.JournalEntry> {+ return this.writeEntity(+ "journalentry",+ "JournalEntry",+ "create journal entry",+ journalEntry+ );+ }++ // =================================================================+ // Dimensions (Class / Department)+ // =================================================================++ /**+ * Active QBO Classes. Class tracking is feature-gated by the Intuit+ * plan — a query failure means the org doesn't have the feature, so+ * this returns [] instead of hard-failing (the settings UI then offers+ * no "class" target).+ */+ async listClasses(): Promise<Qbo.Class[]> {+ try {+ return await this.query<Qbo.Class>("Class", "Active = true");+ } catch (error) {+ console.warn(+ "Failed to fetch QuickBooks Online classes (class tracking likely unavailable on this plan):",+ error+ );+ return [];+ }+ }++ /**+ * Active QBO Departments (a.k.a. Locations). Same forgiving contract+ * as listClasses — [] when the feature is off.+ */+ async listDepartments(): Promise<Qbo.Department[]> {+ try {+ return await this.query<Qbo.Department>("Department", "Active = true");+ } catch (error) {+ console.warn(+ "Failed to fetch QuickBooks Online departments (location tracking likely unavailable on this plan):",+ error+ );+ return [];+ }+ }++ /** Create a QBO Class by name (dimension autoCreate). Throws on failure. */+ async createClass(payload: QboCreatePayload<Qbo.Class>): Promise<Qbo.Class> {+ return this.writeEntity("class", "Class", "create class", payload);+ }++ /** Create a QBO Department by name (dimension autoCreate). Throws on failure. */+ async createDepartment(+ payload: QboCreatePayload<Qbo.Department>+ ): Promise<Qbo.Department> {+ return this.writeEntity(+ "department",+ "Department",+ "create department",+ payload+ );+ }++ /**+ * The journal dimension targets this org actually supports: `class`+ * and/or `department`, each verified by a probe query so orgs without+ * the Intuit feature see an empty (or reduced) target list instead of a+ * push-time failure. A feature that is on but has no values yet still+ * yields its target.+ */+ async journalDimensionTargets(): Promise<DimensionTarget[]> {+ const targets: DimensionTarget[] = [];++ try {+ await this.query<Qbo.Class>("Class", "Active = true", 1, 1);+ targets.push({ id: QBO_DIMENSION_TARGET_CLASS, label: "Class" });+ } catch (error) {+ console.warn("QBO class tracking unavailable; omitting target:", error);+ }++ try {+ await this.query<Qbo.Department>("Department", "Active = true", 1, 1);+ targets.push({+ id: QBO_DIMENSION_TARGET_DEPARTMENT,+ label: "Department"+ });+ } catch (error) {+ console.warn(+ "QBO department tracking unavailable; omitting target:",+ error+ );+ }++ return targets;+ }++ // =================================================================+ // Change Data Capture+ // =================================================================++ /**+ * QBO Change Data Capture (GET /cdc): every entity of the requested+ * types changed since `changedSince` (ISO 8601; QBO reaches back at+ * most 30 days). The response nests one QueryResponse per entity type+ * under CDCResponse, mixing full objects with `status: "Deleted"`+ * tombstone stubs. Only identity fields are parsed — the pull syncers+ * refetch full objects by id — so each change normalizes to+ * `{ entityName, id, deleted, lastUpdatedTime }`. Records failing even+ * the minimal parse are logged and skipped.+ */+ async changeDataCapture(+ entities: string[],+ changedSince: string+ ): Promise<QboChangeDataCaptureEntry[]> {+ const response = await this.request<QboCdcResponse>(+ "GET",+ `/cdc?entities=${encodeURIComponent(+ entities.join(",")+ )}&changedSince=${encodeURIComponent(changedSince)}`+ );++ if (response.error) {+ throwQboApiError("change data capture", response);+ }++ const changes: QboChangeDataCaptureEntry[] = [];++ for (const cdcResponse of response.data?.CDCResponse ?? []) {+ for (const queryResponse of cdcResponse?.QueryResponse ?? []) {+ if (!queryResponse || typeof queryResponse !== "object") continue;++ for (const entityName of entities) {+ const records = (queryResponse as Record<string, unknown>)[+ entityName+ ];+ if (!Array.isArray(records)) continue;++ for (const record of records) {+ const parsed = CdcRecordSchema.safeParse(record);+ if (!parsed.success) {+ console.warn(+ `[QBO CDC] Skipping unparseable ${entityName} record:`,+ parsed.error.issues+ );+ continue;+ }++ changes.push({+ entityName,+ id: parsed.data.Id,+ deleted: parsed.data.status === "Deleted",+ lastUpdatedTime: parsed.data.MetaData?.LastUpdatedTime ?? null+ });+ }+ }+ }+ }++ return changes;+ }++ /**+ * QBO's CDC endpoint reaches back at most 30 days; clamped to 29 to+ * keep a margin for clock skew and call latency.+ */+ readonly pullLookbackDays = 29;++ /**+ * SupportsIncrementalPull: CDC changes for every entity whose RESOLVED+ * sync config direction includes pull, normalized for the generic+ * accounting-pull-sweep cron. Push-only entities (item and+ * purchaseOrder under the defaults) never flow QBO → Carbon and are not+ * fetched. Unknown entity names are logged and dropped.+ */+ async listChanges(args: { since: string }): Promise<ListChangesResult> {+ const entityNames = (+ Object.keys(QBO_CDC_ENTITY_TYPES) as QboCdcEntityName[]+ ).filter((entityName) => {+ const entityConfig = this.getSyncConfig(QBO_CDC_ENTITY_TYPES[entityName]);+ return (+ entityConfig.enabled &&+ (entityConfig.direction === "pull-from-accounting" ||+ entityConfig.direction === "two-way")+ );+ });++ if (entityNames.length === 0) {+ return { changes: [] };+ }++ const entries = await this.changeDataCapture(entityNames, args.since);++ const changes: ProviderChange[] = [];+ for (const entry of entries) {+ const entityType =+ (QBO_CDC_ENTITY_TYPES as Record<string, AccountingEntityType>)[+ entry.entityName+ ] ?? null;+ if (!entityType) {+ console.warn(+ `[QBO] ignoring CDC change for unmapped entity "${entry.entityName}"`+ );+ continue;+ }++ // Payments (Payment / BillPayment) need the settled document to build the+ // composite entity id + dependency; CDC only carries the payment id, so+ // refetch the object.+ if (entityType === "payment") {+ const change = await this.buildPaymentChange(entry);+ if (change) changes.push(change);+ continue;+ }++ changes.push({+ entityType,+ remoteId: entry.id,+ updatedAt: entry.lastUpdatedTime,+ deleted: entry.deleted+ });+ }++ return { changes };+ }++ /**+ * Turn a CDC Payment/BillPayment entry into a `payment` ProviderChange with+ * the canonical composite id (`<invoiceId>:<paymentId>` /+ * `bill:<billId>:<paymentId>`) + a `dependsOnMapping` on the primary settled+ * document. Refetches the payment (CDC carries only the id) — the SAME+ * composite the notification-only webhook builds, so webhook + CDC dedupe on+ * the one `payment` mapping. A hard-deleted stub (`entry.deleted`) is emitted+ * as a bare-id deleted-flagged change WITHOUT refetching (the sweep turns it+ * into a void); returns null (logged) only for a live payment that settles no+ * Bill/Invoice.+ */+ private async buildPaymentChange(+ entry: QboChangeDataCaptureEntry+ ): Promise<ProviderChange | null> {+ if (entry.deleted) {+ // A hard-deleted Payment/BillPayment CDC stub carries only its bare id+ // (no lines, and a refetch would 404), so the composite entity id can't+ // be rebuilt here. Emit a deleted-flagged change carrying the BARE+ // payment id; the pull sweep resolves the composite(s) from the existing+ // payment mapping (suffix match) and enqueues the reversing void pull.+ // No dependsOnMapping — the settled document is unknown from a tombstone.+ return {+ entityType: "payment",+ remoteId: entry.id,+ updatedAt: entry.lastUpdatedTime,+ deleted: true+ };+ }++ const family = entry.entityName === "BillPayment" ? "ap" : "ar";+ const remote =+ family === "ap"+ ? await this.getBillPayment(entry.id)+ : await this.getPayment(entry.id);+ if (!remote) {+ console.warn(+ `[QBO] ${entry.entityName} ${entry.id} not found on refetch — skipping`+ );+ return null;+ }++ const built = buildQboPaymentSyncChange(remote, family);+ if (!built) {+ console.warn(+ `[QBO] ${entry.entityName} ${entry.id} settles no ${+ family === "ap" ? "Bill" : "Invoice"+ } — skipping`+ );+ return null;+ }++ return {+ entityType: "payment",+ remoteId: built.entityId,+ updatedAt:+ parseQboDate(remote.MetaData?.LastUpdatedTime)?.toISOString() ??+ entry.lastUpdatedTime,+ dependsOnMapping: {+ entityType: family === "ap" ? "bill" : "invoice",+ remoteId: built.documentRemoteId+ }+ };+ }+}++/**+ * QBO CDC entity names → Carbon entity types. `Payment` (AR) and `BillPayment`+ * (AP) both map to the single `payment` entity type — the payment syncer+ * discriminates family from the composite id / object shape.+ *+ * VERIFY(sandbox): confirm QBO CDC actually returns `BillPayment` deltas (and+ * `Payment` deltas) within the 29-day window; research says yes, but Intuit's+ * CDC-supported-entity list has historically shifted.+ */+export const QBO_CDC_ENTITY_TYPES = {+ Customer: "customer",+ Vendor: "vendor",+ Item: "item",+ Invoice: "invoice",+ Bill: "bill",+ PurchaseOrder: "purchaseOrder",+ Payment: "payment",+ BillPayment: "payment"+} as const satisfies Record<string, AccountingEntityType>;++export type QboCdcEntityName = keyof typeof QBO_CDC_ENTITY_TYPES;++/**+ * Write payload for POST /payment (Phase G AR outbound write-back). QBO+ * requires CustomerRef (the payer) and a DepositToAccountRef (the bank the+ * receipt lands in); each `Line` applies its `Amount` to an Invoice via+ * LinkedTxn. Deliberately structural (not QboCreatePayload<Qbo.Payment>) — the+ * read schema omits these write-only refs.+ */+export type QboPaymentCreatePayload = {+ CustomerRef: Qbo.Ref;+ TotalAmt: number;+ TxnDate: string;+ DepositToAccountRef: Qbo.Ref;+ Line: Qbo.PaymentLine[];+};++/**+ * Write payload for POST /billpayment (Phase G AP outbound write-back). QBO+ * requires VendorRef (the payee) and a PayType with the matching detail; a+ * "Check" payment carries CheckPayment.BankAccountRef (the bank the+ * disbursement clears through). Each `Line` applies its `Amount` to a Bill via+ * LinkedTxn.+ */+export type QboBillPaymentCreatePayload = {+ VendorRef: Qbo.Ref;+ TotalAmt: number;+ TxnDate: string;+ PayType: "Check";+ CheckPayment: { BankAccountRef: Qbo.Ref };+ Line: Qbo.PaymentLine[];+};++/**+ * Envelope returned by GET /cdc. Each CDCResponse carries one+ * QueryResponse per changed entity type; entity rows live under the+ * entity name exactly like /query — full objects for live records,+ * `{ Id, status: "Deleted", MetaData }` tombstone stubs for deletes.+ */+type QboCdcResponse = {+ CDCResponse?: Array<{+ QueryResponse?: Array<Record<string, unknown> | null>;+ } | null>;+ time?: string;+};++/**+ * Minimal identity parse of one CDC record (the pull syncers refetch full+ * objects by id): `Id`, the Deleted-stub marker, and+ * `MetaData.LastUpdatedTime` for the CDC cron's cursor math.+ */+const CdcRecordSchema = z.object({+ Id: z.string(),+ status: z.string().optional(),+ MetaData: z.object({ LastUpdatedTime: z.string().optional() }).optional()+});++/** One normalized CDC change. */+export type QboChangeDataCaptureEntry = {+ /** QBO entity name as requested, e.g. "Customer". */+ entityName: string;+ /** QBO entity Id — the remote id Carbon maps against. */+ id: string;+ /** True for QBO's `status: "Deleted"` tombstone stubs. */+ deleted: boolean;+ /** MetaData.LastUpdatedTime (ISO 8601 with offset), when present. */+ lastUpdatedTime: string | null;+};diff --git a/packages/ee/src/accounting/providers/rillet/__tests__/fields.test.ts b/packages/ee/src/accounting/providers/rillet/__tests__/fields.test.tsnew file mode 100644index 0000000000..346f659709--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/__tests__/fields.test.ts@@ -0,0 +1,375 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_SYNC_CONFIG } from "../../../core/models";+import { AccountingApiError } from "../../../core/utils";+import {+ buildRilletFieldTarget,+ parseRilletFieldTarget,+ RILLET_API_VERSION,+ RilletProvider+} from "../provider";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+}++function makeProvider() {+ return new RilletProvider({+ companyId: "company-1",+ credentials: {+ type: "apiKey",+ apiKey: "rillet-key",+ environment: "production"+ },+ syncConfig: DEFAULT_SYNC_CONFIG+ });+}++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++// Verified v4 surface (spec changelog 2026-08-04): GET /fields returns+// { fields: [{ id, name, values: [{ id, name, deactivated }], settings,+// updated_at }] }; POST /fields/{id}/values { name } upserts by name and+// returns the FULL Field including the value's uuid.+const DEPARTMENT_FIELD = {+ id: "f1d10000-0000-0000-0000-000000000001",+ name: "Department",+ values: [+ {+ id: "fv100000-0000-0000-0000-000000000001",+ name: "Operations",+ deactivated: false+ }+ ],+ settings: { EXPENSES: { mandatory: false, display: "STANDALONE" } },+ updated_at: "2026-08-01T00:00:00.000Z"+};++describe("RilletProvider.listFields", () => {+ it("lists field definitions with their pick-list values", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ fields: [DEPARTMENT_FIELD] })+ );++ const fields = await makeProvider().listFields();++ expect(String(fetchMock.mock.calls[0]?.[0])).toBe(+ "https://api.rillet.com/fields"+ );+ const headers = fetchMock.mock.calls[0]?.[1]?.headers as Record<+ string,+ string+ >;+ expect(headers["X-Rillet-API-Version"]).toBe(RILLET_API_VERSION);+ expect(fields).toEqual([DEPARTMENT_FIELD]);+ });++ it("defensively follows a cursor if the endpoint ever paginates", async () => {+ const secondField = { ...DEPARTMENT_FIELD, id: "f2", name: "Region" };+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse({+ fields: [DEPARTMENT_FIELD],+ pagination: { next_cursor: "abc" }+ })+ )+ .mockResolvedValueOnce(jsonResponse({ fields: [secondField] }));++ const fields = await makeProvider().listFields();++ expect(fields.map((field) => field.id)).toEqual([+ DEPARTMENT_FIELD.id,+ "f2"+ ]);+ expect(String(fetchMock.mock.calls[1]?.[0])).toBe(+ "https://api.rillet.com/fields?cursor=abc"+ );+ });++ it("throws a structured error on API failure", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse(+ { type: "about:blank", title: "Server error", status: 500 },+ 500+ )+ );++ await expect(makeProvider().listFields()).rejects.toBeInstanceOf(+ AccountingApiError+ );+ });+});++describe("RilletProvider.upsertFieldValue", () => {+ it("upserts a value BY NAME and extracts its uuid from the returned full Field", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ field: {+ ...DEPARTMENT_FIELD,+ values: [+ ...DEPARTMENT_FIELD.values,+ {+ id: "fv100000-0000-0000-0000-000000000002",+ name: "Engineering",+ deactivated: false+ }+ ]+ }+ })+ );++ const value = await makeProvider().upsertFieldValue(+ DEPARTMENT_FIELD.id,+ "Engineering"+ );++ expect(value.id).toBe("fv100000-0000-0000-0000-000000000002");+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe(+ `https://api.rillet.com/fields/${DEPARTMENT_FIELD.id}/values`+ );+ expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({+ name: "Engineering"+ });+ });++ it("reuses the EXISTING value uuid when the name is already on the field (upsert semantics)", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ field: DEPARTMENT_FIELD }));++ const value = await makeProvider().upsertFieldValue(+ DEPARTMENT_FIELD.id,+ "Operations"+ );++ expect(value.id).toBe("fv100000-0000-0000-0000-000000000001");+ });++ it("accepts a bare (unwrapped) Field response body", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(DEPARTMENT_FIELD));++ const value = await makeProvider().upsertFieldValue(+ DEPARTMENT_FIELD.id,+ "Operations"+ );+ expect(value.id).toBe("fv100000-0000-0000-0000-000000000001");+ });++ it("fails loudly when the upserted name is missing from the returned field (contract drift)", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ field: DEPARTMENT_FIELD }));++ await expect(+ makeProvider().upsertFieldValue(DEPARTMENT_FIELD.id, "Not There")+ ).rejects.toThrowError(/not on the returned field/);+ });++ it("trims a trailing-space value and matches Rillet's trimmed store (production-event field failure)", async () => {+ // Carbon dimension labels can carry inconsistent whitespace ("Test " vs+ // "Test"); Rillet trims on write. POST must carry the trimmed name and the+ // match must be trim-tolerant, else the whole journal fails on a string miss+ // ("Test " is not on the returned field ...).+ const fieldWithTest = {+ ...DEPARTMENT_FIELD,+ values: [+ ...DEPARTMENT_FIELD.values,+ {+ id: "fv100000-0000-0000-0000-00000000000b",+ name: "Test",+ deactivated: false+ }+ ]+ };+ fetchMock.mockResolvedValueOnce(jsonResponse({ field: fieldWithTest }));++ const value = await makeProvider().upsertFieldValue(+ DEPARTMENT_FIELD.id,+ "Test "+ );++ expect(value.id).toBe("fv100000-0000-0000-0000-00000000000b");+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({+ name: "Test"+ });+ });++ it("recovers across whitespace when Rillet 400s 'already exists' but stored the value trimmed", async () => {+ // A prior line created "Test " → Rillet stored "Test". This line upserts+ // "Test" → 400 already-exists; recovery must match the stored value by+ // trimmed name, not exact string.+ const fieldWithTest = {+ ...DEPARTMENT_FIELD,+ values: [+ ...DEPARTMENT_FIELD.values,+ {+ id: "fv100000-0000-0000-0000-00000000000c",+ name: "Test ",+ deactivated: false+ }+ ]+ };+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse(+ {+ title: "Bad Request",+ status: 400,+ detail: 'Value "Test" already exists.'+ },+ 400+ )+ )+ .mockResolvedValueOnce(jsonResponse({ fields: [fieldWithTest] }));++ const value = await makeProvider().upsertFieldValue(+ DEPARTMENT_FIELD.id,+ "Test"+ );++ expect(value.id).toBe("fv100000-0000-0000-0000-00000000000c");+ });++ it("recovers the existing value's uuid when Rillet 400s 'already exists' (mapping lost / value seeded in Rillet)", async () => {+ // POST /fields/{id}/values rejects a name that already exists (Rillet is+ // NOT idempotent by name — the bill-sync failure in the field). The+ // recovery reads the value back by name via GET /fields.+ const fieldWithHeadquarters = {+ ...DEPARTMENT_FIELD,+ values: [+ ...DEPARTMENT_FIELD.values,+ {+ id: "fv100000-0000-0000-0000-00000000000a",+ name: "Headquarters",+ deactivated: false+ }+ ]+ };+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse(+ {+ title: "Bad Request",+ status: 400,+ detail: 'Value "Headquarters" already exists.'+ },+ 400+ )+ )+ .mockResolvedValueOnce(jsonResponse({ fields: [fieldWithHeadquarters] }));++ const value = await makeProvider().upsertFieldValue(+ DEPARTMENT_FIELD.id,+ "Headquarters"+ );++ expect(value.id).toBe("fv100000-0000-0000-0000-00000000000a");+ expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");+ expect(String(fetchMock.mock.calls[1]?.[0])).toBe(+ "https://api.rillet.com/fields"+ );+ });++ it("prefers a non-deactivated existing value when recovering by name", async () => {+ const fieldWithDupes = {+ ...DEPARTMENT_FIELD,+ values: [+ {+ id: "fv-deactivated",+ name: "Headquarters",+ deactivated: true+ },+ {+ id: "fv-active",+ name: "Headquarters",+ deactivated: false+ }+ ]+ };+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse(+ { detail: 'Value "Headquarters" already exists.', status: 400 },+ 400+ )+ )+ .mockResolvedValueOnce(jsonResponse({ fields: [fieldWithDupes] }));++ const value = await makeProvider().upsertFieldValue(+ DEPARTMENT_FIELD.id,+ "Headquarters"+ );++ expect(value.id).toBe("fv-active");+ });++ it("re-throws an 'already exists' 400 when the value cannot be recovered (contract drift)", async () => {+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse(+ { detail: 'Value "Headquarters" already exists.', status: 400 },+ 400+ )+ )+ // GET /fields returns the field but WITHOUT the value — should not+ // swallow the error into a broken ref.+ .mockResolvedValueOnce(jsonResponse({ fields: [DEPARTMENT_FIELD] }));++ await expect(+ makeProvider().upsertFieldValue(DEPARTMENT_FIELD.id, "Headquarters")+ ).rejects.toBeInstanceOf(AccountingApiError);+ });++ it("re-throws a non-'already exists' 400 without attempting recovery", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ detail: "Field not found.", status: 400 }, 400)+ );++ await expect(+ makeProvider().upsertFieldValue(DEPARTMENT_FIELD.id, "Headquarters")+ ).rejects.toBeInstanceOf(AccountingApiError);+ // Only the POST — no GET /fields recovery attempt.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe("RilletProvider.journalDimensionTargets", () => {+ it("declares one field:<fieldId> target per Rillet Field", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ fields: [DEPARTMENT_FIELD] })+ );++ const targets = await makeProvider().journalDimensionTargets();+ expect(targets).toEqual([+ {+ id: `field:${DEPARTMENT_FIELD.id}`,+ label: "Department",+ capacity: 1+ }+ ]);+ });++ it("returns [] on failure (forgiving settings-surface contract)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ title: "Server error" }, 500)+ );+ await expect(makeProvider().journalDimensionTargets()).resolves.toEqual([]);+ });+});++describe("Rillet field targets", () => {+ it("builds and parses field:<fieldId> targets", () => {+ expect(buildRilletFieldTarget("f1")).toBe("field:f1");+ expect(parseRilletFieldTarget("field:f1")).toBe("f1");+ expect(parseRilletFieldTarget("class")).toBeNull();+ expect(parseRilletFieldTarget("field:")).toBeNull();+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts b/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.tsnew file mode 100644index 0000000000..a631059ddb--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/__tests__/provider.test.ts@@ -0,0 +1,701 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_SYNC_CONFIG, ProviderID } from "../../../core/models";+import type {+ GlobalSyncConfig,+ ProviderCredentials+} from "../../../core/types";+import { AccountingApiError, RatelimitError } from "../../../core/utils";+import type { RilletJournalEntryCreate } from "../models";+import {+ buildRilletIdempotencyKey,+ buildRilletSyncConfig,+ extractRilletErrorDetails,+ RILLET_API_VERSION,+ RilletProvider+} from "../provider";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+}++function makeProvider(overrides?: {+ environment?: "production" | "sandbox";+ credentials?: ProviderCredentials | null;+}) {+ const credentials: ProviderCredentials | undefined =+ overrides?.credentials === null+ ? undefined+ : (overrides?.credentials ?? {+ type: "apiKey",+ apiKey: "rillet-key",+ environment: overrides?.environment ?? "production"+ });++ return new RilletProvider({+ companyId: "company-1",+ credentials,+ syncConfig: DEFAULT_SYNC_CONFIG+ });+}++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++function requestUrl(callIndex: number): string {+ return String(fetchMock.mock.calls[callIndex]?.[0]);+}++function requestInit(callIndex: number): RequestInit | undefined {+ return fetchMock.mock.calls[callIndex]?.[1];+}++function requestHeaders(callIndex: number): Record<string, string> {+ return (requestInit(callIndex)?.headers ?? {}) as Record<string, string>;+}++const JOURNAL_PAYLOAD: RilletJournalEntryCreate = {+ name: "Carbon JE000042 je_123",+ date: "2026-07-01",+ currency: "USD",+ items: [+ {+ account_code: "1400",+ amount: { amount: "150.00", currency: "USD" },+ side: "DEBIT"+ },+ {+ account_code: "2100",+ amount: { amount: "150.00", currency: "USD" },+ side: "CREDIT"+ }+ ]+};++describe("RilletProvider base URL + headers", () => {+ it("targets the production host by default with the bearer key and pinned API version", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [] }));++ const provider = makeProvider();+ await provider.listChartOfAccounts();++ expect(requestUrl(0)).toBe("https://api.rillet.com/accounts");+ const headers = requestHeaders(0);+ expect(headers.Authorization).toBe("Bearer rillet-key");+ expect(headers["X-Rillet-API-Version"]).toBe(RILLET_API_VERSION);+ expect(headers.Accept).toBe("application/json");+ expect(headers["Content-Type"]).toBe("application/json");+ });++ it("targets the sandbox host when the stored key is a sandbox key", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [] }));++ const provider = makeProvider({ environment: "sandbox" });+ await provider.listChartOfAccounts();++ expect(requestUrl(0)).toBe("https://sandbox.api.rillet.com/accounts");+ });++ it("identifies as the rillet provider", () => {+ const provider = makeProvider();+ expect(provider.id).toBe(ProviderID.RILLET);+ expect(provider.capabilities).toEqual({+ transport: "rest",+ supportsWebhooks: true,+ supportsJournalPush: true+ });+ });+});++describe("RilletProvider auth (API key, no OAuth)", () => {+ it("throws the no-OAuth message from authenticate and every OAuth surface", async () => {+ const provider = makeProvider();++ await expect(provider.authenticate()).rejects.toThrow(/no OAuth flow/);+ expect(() => provider.auth.getAuthUrl([], "")).toThrow(/no OAuth flow/);+ expect(() => provider.auth.exchangeCode("code", "uri")).toThrow(+ /no OAuth flow/+ );+ expect(() => provider.auth.refresh()).toThrow(/no OAuth flow/);+ });++ it("throws a descriptive error when no credentials are stored", async () => {+ const provider = makeProvider({ credentials: null });++ expect(() => provider.auth.getCredentials()).toThrow(+ /no stored credentials/+ );+ await expect(provider.createCustomer({ name: "Acme" })).rejects.toThrow(+ /no stored credentials/+ );+ });++ it("rejects a non-apiKey credentials variant", async () => {+ const provider = makeProvider({+ credentials: { type: "oauth2", accessToken: "token" }+ });++ await expect(provider.createCustomer({ name: "Acme" })).rejects.toThrow(+ /apiKey credentials/+ );+ });++ it("does not retry on 401 — a rejected key is terminal", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ title: "Unauthorized", status: 401 }, 401)+ );++ const provider = makeProvider();+ const response = await provider.request("GET", "/accounts");++ expect(response.error).toBe(true);+ expect(response.code).toBe(401);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe("RilletProvider idempotency", () => {+ it("sends the Idempotency-Key header on creates", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ id: "je-remote-1", ...JOURNAL_PAYLOAD })+ );++ const provider = makeProvider();+ const created = await provider.createJournalEntry(+ JOURNAL_PAYLOAD,+ "idem-key-123"+ );++ expect(created.id).toBe("je-remote-1");+ expect(requestUrl(0)).toBe("https://api.rillet.com/journal-entries");+ expect(requestInit(0)?.method).toBe("POST");+ expect(requestHeaders(0)["Idempotency-Key"]).toBe("idem-key-123");+ expect(JSON.parse(String(requestInit(0)?.body))).toEqual(JOURNAL_PAYLOAD);+ });++ it("buildRilletIdempotencyKey is stable and entity-scoped (payload drift must not mint a fresh key)", () => {+ // A crash between the remote create and the local mapping write+ // retries the push; the retry's payload may have drifted (dimension+ // resolution, an edit between attempts). The key must dedupe on the+ // logical create — company + operation + local entity — so the retry+ // replays Rillet's stored response instead of double-creating.+ const args = {+ companyId: "company-1",+ operation: "journal-entry",+ localId: "je_123"+ };++ const key = buildRilletIdempotencyKey(args);+ expect(key).toMatch(/^[0-9a-f]{64}$/);+ expect(buildRilletIdempotencyKey(args)).toBe(key);+ expect(buildRilletIdempotencyKey({ ...args, localId: "je_456" })).not.toBe(+ key+ );+ expect(buildRilletIdempotencyKey({ ...args, operation: "bill" })).not.toBe(+ key+ );+ });+});++describe("RilletProvider rate limiting + errors", () => {+ it("throws RatelimitError on 429", async () => {+ fetchMock.mockResolvedValueOnce(+ new Response("", { status: 429, headers: { "Retry-After": "30" } })+ );++ const provider = makeProvider();+ await expect(provider.createCustomer({ name: "Acme" })).rejects.toThrow(+ RatelimitError+ );+ });++ it("extracts RFC 9457 problem details including the errors[] extension", () => {+ const details = extractRilletErrorDetails(422, "Unprocessable Entity", {+ type: "https://api.rillet.com/errors/validation",+ title: "Validation failed",+ status: 422,+ detail: "items must contain at least 2 elements",+ errors: [+ { pointer: "/items", detail: "too few items" },+ "currency is required"+ ]+ });++ expect(details.providerErrorType).toBe(+ "https://api.rillet.com/errors/validation"+ );+ expect(details.providerErrorCode).toBe(422);+ expect(details.providerMessage).toBe(+ "items must contain at least 2 elements"+ );+ expect(details.validationErrors).toEqual([+ { field: "/items", message: "too few items" },+ { message: "currency is required" }+ ]);+ });++ it("falls back to title when detail is absent, and to the raw string body", () => {+ expect(+ extractRilletErrorDetails(500, "Internal Server Error", {+ type: "about:blank",+ title: "Internal error",+ status: 500+ }).providerMessage+ ).toBe("Internal error");++ expect(+ extractRilletErrorDetails(400, "Bad Request", "plain text error")+ .providerMessage+ ).toBe("plain text error");+ });++ it("throws a structured AccountingApiError on write failure", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse(+ {+ type: "https://api.rillet.com/errors/validation",+ title: "Validation failed",+ status: 422,+ detail: "name is required"+ },+ 422+ )+ );++ const provider = makeProvider();++ let thrown: unknown;+ try {+ await provider.createVendor({ name: "Acme" });+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(AccountingApiError);+ expect((thrown as AccountingApiError).provider).toBe("rillet");+ expect((thrown as AccountingApiError).details.providerMessage).toBe(+ "name is required"+ );+ });++ it("returns null from getCustomer when the read fails", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ title: "Not Found", status: 404 }, 404)+ );++ const provider = makeProvider();+ await expect(provider.getCustomer("missing")).resolves.toBeNull();+ });++ it("unwraps a wrapped single-object envelope defensively", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ customer: { id: "cus-1", name: "Acme" } })+ );++ const provider = makeProvider();+ const created = await provider.createCustomer({ name: "Acme" });+ expect(created.id).toBe("cus-1");+ });+});++describe("RilletProvider chart of accounts", () => {+ it("normalizes to { id, code, name }, dropping INACTIVE and code-less accounts", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ accounts: [+ {+ id: "a-1",+ code: "1400",+ name: "Inventory",+ type: "ASSET",+ status: "ACTIVE"+ },+ { id: "a-2", code: "9999", name: "Old", status: "INACTIVE" },+ { id: "a-3", code: null, name: "No code", status: "ACTIVE" },+ { id: "a-4", code: "4000", name: null, status: "ACTIVE" }+ ]+ })+ );++ const provider = makeProvider();+ await expect(provider.listChartOfAccounts()).resolves.toEqual([+ { id: "a-1", code: "1400", name: "Inventory" },+ { id: "a-4", code: "4000", name: "4000" }+ ]);+ });++ it("returns [] instead of throwing when the request fails (Xero-parity contract)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ title: "Unauthorized", status: 401 }, 401)+ );++ const provider = makeProvider();+ await expect(provider.listChartOfAccounts()).resolves.toEqual([]);+ });+});++describe("RilletProvider field values", () => {+ it("recovers the existing value when the create 400s with already-exists", async () => {+ // POST /fields/{id}/values is NOT idempotent server-side (sandbox-verified+ // 2026-08-14): a value provisioned by an earlier instance or seeded in the+ // Rillet UI 400s. The provider must fall back to GET /fields and return+ // the existing value instead of failing the whole document push.+ fetchMock.mockResolvedValueOnce(+ jsonResponse(+ {+ title: "Bad Request",+ status: 400,+ detail: 'Value "Headquarters" already exists'+ },+ 400+ )+ );+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ fields: [+ {+ id: "field-1",+ name: "Location",+ values: [{ id: "val-1", name: "Headquarters" }]+ }+ ]+ })+ );++ const provider = makeProvider();+ await expect(+ provider.upsertFieldValue("field-1", "Headquarters")+ ).resolves.toMatchObject({ id: "val-1", name: "Headquarters" });++ const urls = fetchMock.mock.calls.map((call) => call[0] as string);+ expect(urls[0]).toContain("/fields/field-1/values");+ expect(urls[1]).toContain("/fields");+ });++ it("rethrows a non-duplicate failure without listing fields", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ title: "Unauthorized", status: 401 }, 401)+ );++ const provider = makeProvider();+ await expect(provider.upsertFieldValue("field-1", "HQ")).rejects.toThrow();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe("RilletProvider cursor pagination", () => {+ it("follows pagination.next_cursor with limit=100 until absent", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ customers: [+ { id: "c-1", name: "A" },+ { id: "c-2", name: "B" }+ ],+ pagination: { next_cursor: "cur-2" }+ })+ );+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ customers: [{ id: "c-3", name: "C" }], pagination: {} })+ );++ const provider = makeProvider();+ const customers = await provider.listCustomers();++ expect(customers.map((customer) => customer.id)).toEqual([+ "c-1",+ "c-2",+ "c-3"+ ]);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(requestUrl(0)).toBe("https://api.rillet.com/customers?limit=100");+ expect(requestUrl(1)).toBe(+ "https://api.rillet.com/customers?limit=100&cursor=cur-2"+ );+ });+});++describe("RilletProvider validate", () => {+ it("is true when GET /accounts succeeds", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ accounts: [] }));+ await expect(makeProvider().validate()).resolves.toBe(true);+ });++ it("is false on an API failure or unusable credentials", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ title: "Unauthorized", status: 401 }, 401)+ );+ await expect(makeProvider().validate()).resolves.toBe(false);++ await expect(makeProvider({ credentials: null }).validate()).resolves.toBe(+ false+ );+ });+});++describe("buildRilletSyncConfig", () => {+ it("forces push-only, pull-only and disabled entities regardless of stored overrides", () => {+ const stored: GlobalSyncConfig = {+ entities: {+ ...DEFAULT_SYNC_CONFIG.entities,+ // Stored overrides that Rillet cannot honor+ customer: { enabled: false, direction: "two-way", owner: "accounting" },+ invoice: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ payment: { enabled: false, direction: "two-way", owner: "carbon" },+ purchaseOrder: {+ enabled: true,+ direction: "push-to-accounting",+ owner: "carbon"+ }+ }+ };++ const built = buildRilletSyncConfig(stored);++ // Push-only forced; per-company enabled survives+ expect(built.entities.customer).toEqual({+ enabled: false,+ direction: "push-to-accounting",+ owner: "carbon"+ });+ expect(built.entities.invoice).toEqual({+ enabled: true,+ direction: "push-to-accounting",+ owner: "carbon"+ });+ expect(built.entities.journalEntry.direction).toBe("push-to-accounting");+ expect(built.entities.journalEntry.owner).toBe("carbon");+ // Always-on: journalEntry is FORCED enabled — a stale stored+ // enabled:false override cannot turn automated postings off.+ expect(built.entities.journalEntry.enabled).toBe(true);+ expect(+ buildRilletSyncConfig({+ entities: {+ ...DEFAULT_SYNC_CONFIG.entities,+ journalEntry: {+ enabled: false,+ direction: "push-to-accounting",+ owner: "carbon"+ }+ }+ }).entities.journalEntry.enabled+ ).toBe(true);++ // Payment: two-way (pull inbound + push Carbon-born outbound, Phase G),+ // owner accounting, and FORCED enabled (no per-company toggle — the+ // documents-mode families gate governs whether it runs)+ expect(built.entities.payment).toEqual({+ enabled: true,+ direction: "two-way",+ owner: "accounting"+ });++ // Unsupported entities forced off+ expect(built.entities.purchaseOrder.enabled).toBe(false);+ expect(built.entities.salesOrder.enabled).toBe(false);+ expect(built.entities.inventoryAdjustment.enabled).toBe(false);+ expect(built.entities.employee.enabled).toBe(false);+ });+});++describe("listChanges (SupportsIncrementalPull)", () => {+ it("declares no lookback cap (updated.gt reaches arbitrarily far back)", () => {+ expect(makeProvider().pullLookbackDays).toBeUndefined();+ });++ it("lists changed invoice payments as composite-id changes with an invoice dependency", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ payments: [+ {+ id: "pay-1",+ status: "SUCCESSFUL",+ invoice_id: "inv-1",+ amount: { amount: "100.00", currency: "USD" },+ updated_at: "2026-07-31T12:00:00.000Z"+ },+ // No invoice_id → unaddressable, logged and dropped+ { id: "pay-2", status: "UNCLEARED" }+ ]+ })+ );+ // AP changed-bills feed — empty for this AR-focused case.+ fetchMock.mockResolvedValueOnce(jsonResponse({ bills: [] }));++ const result = await makeProvider().listChanges({+ since: "2026-07-30T00:00:00.000Z"+ });++ const url = fetchMock.mock.calls[0]?.[0] as string;+ expect(url).toContain("/invoice-payments?");+ expect(url).toContain(+ `updated.gt=${encodeURIComponent("2026-07-30T00:00:00.000Z")}`+ );+ expect(url).toContain("sort_by=updated");++ expect(result.changes).toEqual([+ {+ entityType: "payment",+ remoteId: "inv-1:pay-1",+ updatedAt: "2026-07-31T12:00:00.000Z",+ dependsOnMapping: { entityType: "invoice", remoteId: "inv-1" }+ }+ ]);+ });++ it("lists changed bill payments as `bill:`-prefixed changes with a bill dependency", async () => {+ // AR invoice-payments feed — empty for this AP-focused case.+ fetchMock.mockResolvedValueOnce(jsonResponse({ payments: [] }));+ // AP feed is COMPOSED (GET /bill-payments does not exist): changed bills…+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ bills: [{ id: "bill-1", updated_at: "2026-08-01T12:00:00.000Z" }]+ })+ );+ // …then that bill's payments.+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ payments: [+ {+ id: "bp-1",+ status: "SUCCESSFUL",+ bill_id: "bill-1",+ amount: { amount: "500.00", currency: "USD" },+ updated_at: "2026-08-01T12:00:00.000Z"+ },+ // No bill_id / updated_at of its own → stamped with the bill's+ { id: "bp-2", status: "UNCLEARED" }+ ]+ })+ );++ const result = await makeProvider().listChanges({+ since: "2026-07-30T00:00:00.000Z"+ });++ const billsUrl = fetchMock.mock.calls[1]?.[0] as string;+ expect(billsUrl).toContain("/bills?");+ expect(billsUrl).toContain(+ `updated.gt=${encodeURIComponent("2026-07-30T00:00:00.000Z")}`+ );+ expect(billsUrl).toContain("sort_by=updated");++ const billPaymentsUrl = fetchMock.mock.calls[2]?.[0] as string;+ expect(billPaymentsUrl).toContain("/bills/bill-1/payments");++ expect(result.changes).toEqual([+ {+ entityType: "payment",+ remoteId: "bill:bill-1:bp-1",+ updatedAt: "2026-08-01T12:00:00.000Z",+ dependsOnMapping: { entityType: "bill", remoteId: "bill-1" }+ },+ {+ entityType: "payment",+ remoteId: "bill:bill-1:bp-2",+ updatedAt: "2026-08-01T12:00:00.000Z",+ dependsOnMapping: { entityType: "bill", remoteId: "bill-1" }+ }+ ]);+ });++ it("emits AR and AP changes together from one sweep", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ payments: [+ {+ id: "pay-1",+ status: "SUCCESSFUL",+ invoice_id: "inv-1",+ updated_at: "2026-07-31T12:00:00.000Z"+ }+ ]+ })+ );+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ bills: [{ id: "bill-1", updated_at: "2026-08-01T12:00:00.000Z" }]+ })+ );+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ payments: [+ {+ id: "bp-1",+ status: "SUCCESSFUL",+ bill_id: "bill-1",+ updated_at: "2026-08-01T12:00:00.000Z"+ }+ ]+ })+ );++ const result = await makeProvider().listChanges({+ since: "2026-07-30T00:00:00.000Z"+ });++ expect(result.changes.map((change) => change.remoteId)).toEqual([+ "inv-1:pay-1",+ "bill:bill-1:bp-1"+ ]);+ expect(+ result.changes.map((change) => change.dependsOnMapping?.entityType)+ ).toEqual(["invoice", "bill"]);+ });++ it("follows pagination across pages (both feeds)", async () => {+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse({+ payments: [+ {+ id: "pay-1",+ status: "SUCCESSFUL",+ invoice_id: "inv-1",+ updated_at: "2026-07-31T12:00:00.000Z"+ }+ ],+ pagination: { next_cursor: "cursor-2" }+ })+ )+ .mockResolvedValueOnce(+ jsonResponse({+ payments: [+ {+ id: "pay-2",+ status: "CLEARED",+ invoice_id: "inv-2",+ updated_at: "2026-07-31T13:00:00.000Z"+ }+ ],+ pagination: { next_cursor: null }+ })+ )+ // AP changed-bills feed — single empty page, so no per-bill calls.+ .mockResolvedValueOnce(jsonResponse({ bills: [] }));++ const result = await makeProvider().listChanges({+ since: "2026-07-30T00:00:00.000Z"+ });++ // 2 invoice-payment pages + 1 changed-bills page+ expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(result.changes.map((change) => change.remoteId)).toEqual([+ "inv-1:pay-1",+ "inv-2:pay-2"+ ]);+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/__tests__/webhook.test.ts b/packages/ee/src/accounting/providers/rillet/__tests__/webhook.test.tsnew file mode 100644index 0000000000..b65caed21e--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/__tests__/webhook.test.ts@@ -0,0 +1,106 @@+import { createHmac } from "node:crypto";+import { describe, expect, it } from "vitest";+import {+ buildRilletSignedPayload,+ verifyRilletWebhookSignature+} from "../webhook";++const token = Buffer.from("super-secret-webhook-token").toString("base64");++const headers = {+ timestamp: "2026-07-31T12:00:00.000Z",+ id: "6f9619ff-8b86-d011-b42d-00c04fc964ff",+ entity: "invoice",+ event: "payment-updated"+};++const body = JSON.stringify({+ id: "11111111-1111-1111-1111-111111111111",+ invoice_id: "22222222-2222-2222-2222-222222222222"+});++function sign(signingToken: string): string {+ return createHmac("sha256", Buffer.from(signingToken, "base64"))+ .update(buildRilletSignedPayload(headers, body))+ .digest("base64");+}++describe("buildRilletSignedPayload", () => {+ it("dot-joins timestamp, id, entity, event, and the raw body", () => {+ expect(buildRilletSignedPayload(headers, body)).toBe(+ `${headers.timestamp}.${headers.id}.${headers.entity}.${headers.event}.${body}`+ );+ });+});++describe("verifyRilletWebhookSignature", () => {+ it("accepts a valid signature", () => {+ expect(+ verifyRilletWebhookSignature({+ headers: { ...headers, signature: sign(token) },+ body,+ token+ })+ ).toBe(true);+ });++ it("rejects a signature from a different token", () => {+ const otherToken = Buffer.from("rotated-away").toString("base64");+ expect(+ verifyRilletWebhookSignature({+ headers: { ...headers, signature: sign(otherToken) },+ body,+ token+ })+ ).toBe(false);+ });++ it("rejects when the body was tampered with", () => {+ expect(+ verifyRilletWebhookSignature({+ headers: { ...headers, signature: sign(token) },+ body: body.replace("2222", "3333"),+ token+ })+ ).toBe(false);+ });++ it("accepts when any of the comma-separated signatures matches", () => {+ const otherToken = Buffer.from("rotated-away").toString("base64");+ const signature = `${sign(otherToken)}, ${sign(token)}`;+ expect(+ verifyRilletWebhookSignature({+ headers: { ...headers, signature },+ body,+ token+ })+ ).toBe(true);+ });++ it("rejects an empty signature header or missing token", () => {+ expect(+ verifyRilletWebhookSignature({+ headers: { ...headers, signature: "" },+ body,+ token+ })+ ).toBe(false);+ expect(+ verifyRilletWebhookSignature({+ headers: { ...headers, signature: sign(token) },+ body,+ token: ""+ })+ ).toBe(false);+ });++ it("rejects garbage base64 without throwing", () => {+ expect(+ verifyRilletWebhookSignature({+ headers: { ...headers, signature: "!!!not-base64!!!" },+ body,+ token+ })+ ).toBe(false);+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/bill.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/bill.test.tsnew file mode 100644index 0000000000..0a18bb8382--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/bill.test.ts@@ -0,0 +1,354 @@+import { describe, expect, it } from "vitest";+import { JournalEntrySyncError } from "../../../../core/posting";+import type { Accounting } from "../../../../core/types";+import { type BillPostingJournalLine, mapBillToRilletBill } from "../bill";++// The bill's G/L costing comes from its posted Purchase Invoice journal+// (item-backed invoice lines carry no account of their own): journal lines+// minus the AP control line ARE the Rillet bill items.++const bill = (): Accounting.Bill =>+ ({+ id: "pi_1",+ companyId: "company-1",+ invoiceId: "AP000001",+ supplierId: "sup_1",+ supplierExternalId: null,+ status: "Pending",+ dateIssued: "2026-08-04",+ dateDue: null,+ datePaid: null,+ currencyCode: "USD",+ exchangeRate: 1,+ subtotal: 300,+ totalTax: 0,+ totalDiscount: 0,+ totalAmount: 300,+ balance: 300,+ supplierReference: null,+ lines: [],+ updatedAt: "2026-08-04T00:00:00.000Z"+ }) as unknown as Accounting.Bill;++const journalLines: BillPostingJournalLine[] = [+ // Debit-signed: GR/IR clearing debit +300, AP credit -300+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR Clearing"+ },+ {+ id: "jl-2",+ accountId: "acct_ap",+ amount: -300,+ description: "Accounts Payable"+ }+];++const codes = new Map([["acct_grir", "2125"]]);++describe("mapBillToRilletBill (journal-derived costing)", () => {+ it("builds items from the posting journal minus the AP control line", () => {+ const payload = mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: journalLines,+ payablesAccountId: "acct_ap"+ });++ expect(payload.vendor_id).toBe("vendor-remote-1");+ expect(payload.expense_number).toBe("AP000001");+ expect(payload.items).toEqual([+ {+ account_code: "2125",+ amount: { amount: "300.00", currency: "USD" },+ description: "GR/IR Clearing"+ }+ ]);+ });++ it("warns when the invoice has no posted journal", () => {+ expect(() =>+ mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: [],+ payablesAccountId: "acct_ap"+ })+ ).toThrowError(JournalEntrySyncError);+ try {+ mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: [],+ payablesAccountId: "acct_ap"+ });+ } catch (error) {+ expect((error as JournalEntrySyncError).failure.message).toContain(+ "no posted Purchase Invoice journal"+ );+ expect((error as JournalEntrySyncError).failure.warning).toBe(true);+ }+ });++ it("warns on unmapped costing accounts (AP line still excluded)", () => {+ try {+ mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: new Map(),+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: journalLines,+ payablesAccountId: "acct_ap"+ });+ expect.unreachable("should have thrown");+ } catch (error) {+ const failure = (error as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(failure.metadata?.unmappedAccountIds).toEqual(["acct_grir"]);+ }+ });++ it("keeps variance/tax lines as additional items", () => {+ const payload = mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: new Map([+ ["acct_grir", "2125"],+ ["acct_ppv", "5210"]+ ]),+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 280,+ description: "GR/IR Clearing"+ },+ {+ id: "jl-2",+ accountId: "acct_ppv",+ amount: 20,+ description: "Purchase Price Variance"+ },+ {+ id: "jl-3",+ accountId: "acct_ap",+ amount: -300,+ description: "Accounts Payable"+ }+ ],+ payablesAccountId: "acct_ap"+ });++ expect(payload.items.map((i) => [i.account_code, i.amount.amount])).toEqual(+ [+ ["2125", "280.00"],+ ["5210", "20.00"]+ ]+ );+ });+});++describe("mapBillToRilletBill — item labels + FX (representation model)", () => {+ it("prepends the item code/name label to PO-backed line descriptions", () => {+ const payload = mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR Clearing",+ sourceItem: { id: "item-1", code: "WIDGET-1", name: "Widget" }+ }+ ],+ payablesAccountId: "acct_ap"+ });++ expect(payload.items[0]?.description).toBe(+ "WIDGET-1 Widget — GR/IR Clearing"+ );+ // account + amount unchanged vs the no-label case (parity, base currency).+ expect(payload.items[0]?.account_code).toBe("2125");+ expect(payload.items[0]?.amount).toEqual({+ amount: "300.00",+ currency: "USD"+ });+ expect(payload.exchange_rate).toBeUndefined();+ });++ it("uses the item label alone when the line has no journal description", () => {+ const payload = mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: null,+ sourceItem: { id: "item-1", code: "WIDGET-1", name: null }+ }+ ],+ payablesAccountId: "acct_ap"+ });+ expect(payload.items[0]?.description).toBe("WIDGET-1");+ });++ it("replays an FX bill in transaction currency + pins exchange_rate", () => {+ const fxBill = {+ ...bill(),+ currencyCode: "EUR",+ exchangeRate: 2+ } as unknown as Accounting.Bill;++ const payload = mapBillToRilletBill({+ bill: fxBill,+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: new Map([+ ["acct_grir", "2125"],+ ["acct_ppv", "5210"]+ ]),+ subsidiaryId: null,+ companyId: "company-1",+ // base-currency debit-signed amounts (rate 2 → half in EUR)+ postingJournalLines: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR Clearing"+ },+ {+ id: "jl-2",+ accountId: "acct_ppv",+ amount: -20,+ description: "Purchase Price Variance"+ }+ ],+ payablesAccountId: "acct_ap"+ });++ expect(payload.exchange_rate).toBe(2);+ expect(payload.items.map((i) => [i.account_code, i.amount])).toEqual([+ ["2125", { amount: "150.00", currency: "EUR" }],+ ["5210", { amount: "-10.00", currency: "EUR" }]+ ]);+ });+});++describe("mapBillToRilletBill — dimensions (Fields)", () => {+ const LOCATION_DIM = "dim_loc";+ const LOCATION_FIELD_ID = "f1d10000-0000-0000-0000-000000000001";++ const dimensionedLines: BillPostingJournalLine[] = [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR Clearing",+ dimensions: [{ dimensionId: LOCATION_DIM, valueId: "loc_hq" }]+ },+ {+ id: "jl-2",+ accountId: "acct_ap",+ amount: -300,+ description: "Accounts Payable",+ // AP control line dimensions never push (the line itself is excluded)+ dimensions: [{ dimensionId: LOCATION_DIM, valueId: "loc_other" }]+ }+ ];++ const fieldIdByDimensionId = new Map([[LOCATION_DIM, LOCATION_FIELD_ID]]);++ it("attaches uuid field refs to items from their posting journal line dimensions", () => {+ const payload = mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: dimensionedLines,+ payablesAccountId: "acct_ap",+ dimensions: {+ fieldIdByDimensionId,+ fieldValueIdsByValue: new Map([["dim_loc:loc_hq", "fv-hq"]])+ }+ });++ expect(payload.items).toHaveLength(1);+ expect(payload.items[0]?.fields).toEqual([+ { field_id: LOCATION_FIELD_ID, field_value_id: "fv-hq" }+ ]);+ });++ it("omits fields for unmapped values (drop path) and when no dimension args are passed", () => {+ const dropped = mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: dimensionedLines,+ payablesAccountId: "acct_ap",+ dimensions: { fieldIdByDimensionId, fieldValueIdsByValue: new Map() }+ });+ expect(dropped.items[0]?.fields).toBeUndefined();++ const withoutArgs = mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: dimensionedLines,+ payablesAccountId: "acct_ap"+ });+ expect(withoutArgs.items[0]?.fields).toBeUndefined();+ });++ it("omits a dimension whose Field was not provisioned (no field mapping)", () => {+ const payload = mapBillToRilletBill({+ bill: bill(),+ vendorRemoteId: "vendor-remote-1",+ accountCodesById: codes,+ subsidiaryId: null,+ companyId: "company-1",+ postingJournalLines: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR Clearing",+ dimensions: [{ dimensionId: "dim_unprovisioned", valueId: "v1" }]+ }+ ],+ payablesAccountId: "acct_ap",+ dimensions: {+ fieldIdByDimensionId, // only LOCATION_DIM is mapped+ fieldValueIdsByValue: new Map([["dim_unprovisioned:v1", "fv-x"]])+ }+ });+ expect(payload.items[0]?.fields).toBeUndefined();+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/contact.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/contact.test.tsnew file mode 100644index 0000000000..4e014295e0--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/contact.test.ts@@ -0,0 +1,284 @@+import { describe, expect, it } from "vitest";+import type { Accounting } from "../../../../core/types";+import { AccountingApiError } from "../../../../core/utils";+import { mapContactToRilletCustomer } from "../customer";+import {+ mapPaymentTermsToRilletDays,+ writeDroppingUnregisteredReferences+} from "../shared";+import {+ mapContactToRilletVendor,+ RILLET_VENDOR_MAX_PAYMENT_TERMS_DAYS+} from "../vendor";++const makeContact = (+ overrides?: Partial<Accounting.Contact>+): Accounting.Contact => ({+ id: "cust-1",+ name: "Acme Manufacturing",+ firstName: "Jane",+ lastName: "Doe",+ companyId: "company-1",+ email: "[email protected]",+ website: null,+ taxId: null,+ currencyCode: "USD",+ balance: null,+ creditLimit: null,+ paymentTerms: null,+ updatedAt: "2026-07-01T12:00:00.000Z",+ workPhone: "555-0100",+ mobilePhone: "555-0101",+ fax: null,+ homePhone: null,+ isVendor: false,+ isCustomer: true,+ addresses: [+ {+ label: "HQ",+ type: null,+ line1: "1 Factory Way",+ line2: "Suite 2",+ city: "Cleveland",+ country: "US",+ region: "OH",+ postalCode: "44101"+ }+ ],+ raw: {},+ ...overrides+});++describe("mapContactToRilletCustomer", () => {+ it("maps name, MAIN_SENDER email, the complete address, payment terms and the carbon reference", () => {+ const payload = mapContactToRilletCustomer(+ makeContact({ paymentTerms: "30" })+ );++ expect(payload).toEqual({+ name: "Acme Manufacturing",+ emails: [{ email: "[email protected]", type: "MAIN_SENDER" }],+ address: {+ line1: "1 Factory Way",+ line2: "Suite 2",+ city: "Cleveland",+ state: "OH",+ zip_code: "44101",+ country: "US"+ },+ payment_terms: 30,+ external_references: [+ { type: "carbon", id: "cust-1" },+ { type: "carbon-company", id: "company-1" }+ ]+ });+ });++ it("produces the minimal payload when email/address/terms are absent", () => {+ const payload = mapContactToRilletCustomer(+ makeContact({ email: undefined, addresses: [], paymentTerms: null })+ );++ expect(payload).toEqual({+ name: "Acme Manufacturing",+ external_references: [+ { type: "carbon", id: "cust-1" },+ { type: "carbon-company", id: "company-1" }+ ]+ });+ });++ it("omits the address entirely when the all-or-nothing group is incomplete", () => {+ const payload = mapContactToRilletCustomer(+ makeContact({+ addresses: [+ {+ label: null,+ type: null,+ line1: "1 Factory Way",+ line2: null,+ city: "Cleveland",+ country: "US",+ region: null, // missing state breaks the group+ postalCode: "44101"+ }+ ]+ })+ );++ expect(payload.address).toBeUndefined();+ });++ it("keeps line2 optional within a complete address", () => {+ const payload = mapContactToRilletCustomer(+ makeContact({+ addresses: [+ {+ label: null,+ type: null,+ line1: "1 Factory Way",+ line2: null,+ city: "Cleveland",+ country: "US",+ region: "OH",+ postalCode: "44101"+ }+ ]+ })+ );++ expect(payload.address).toEqual({+ line1: "1 Factory Way",+ city: "Cleveland",+ state: "OH",+ zip_code: "44101",+ country: "US"+ });+ });++ it("maps only bare non-negative integer payment terms (customers have no cap)", () => {+ expect(+ mapContactToRilletCustomer(makeContact({ paymentTerms: "Net 30" }))+ .payment_terms+ ).toBeUndefined();+ expect(+ mapContactToRilletCustomer(makeContact({ paymentTerms: "0" }))+ .payment_terms+ ).toBe(0);+ expect(+ mapContactToRilletCustomer(makeContact({ paymentTerms: "240" }))+ .payment_terms+ ).toBe(240);+ });+});++describe("mapContactToRilletVendor", () => {+ it("maps the flat vendor email, tax_id, capped payment terms and the carbon reference", () => {+ const payload = mapContactToRilletVendor(+ makeContact({+ id: "supp-1",+ taxId: "12-3456789",+ paymentTerms: "45",+ isVendor: true,+ isCustomer: false+ })+ );++ expect(payload).toEqual({+ name: "Acme Manufacturing",+ email: "[email protected]",+ address: {+ line1: "1 Factory Way",+ line2: "Suite 2",+ city: "Cleveland",+ state: "OH",+ zip_code: "44101",+ country: "US"+ },+ payment_terms: 45,+ tax_id: "12-3456789",+ external_references: [+ { type: "carbon", id: "supp-1" },+ { type: "carbon-company", id: "company-1" }+ ]+ });+ });++ it("omits payment terms beyond Rillet's 180-day vendor cap instead of clamping", () => {+ const payload = mapContactToRilletVendor(+ makeContact({ paymentTerms: "240" })+ );+ expect(payload.payment_terms).toBeUndefined();++ const atCap = mapContactToRilletVendor(+ makeContact({+ paymentTerms: String(RILLET_VENDOR_MAX_PAYMENT_TERMS_DAYS)+ })+ );+ expect(atCap.payment_terms).toBe(RILLET_VENDOR_MAX_PAYMENT_TERMS_DAYS);+ });++ it("produces the minimal payload when optional fields are absent", () => {+ const payload = mapContactToRilletVendor(+ makeContact({+ email: undefined,+ addresses: [],+ paymentTerms: null,+ taxId: null+ })+ );++ expect(payload).toEqual({+ name: "Acme Manufacturing",+ external_references: [+ { type: "carbon", id: "cust-1" },+ { type: "carbon-company", id: "company-1" }+ ]+ });+ });+});++describe("mapPaymentTermsToRilletDays", () => {+ it("parses only bare non-negative integers, honoring the optional cap", () => {+ expect(mapPaymentTermsToRilletDays(null)).toBeUndefined();+ expect(mapPaymentTermsToRilletDays("")).toBeUndefined();+ expect(mapPaymentTermsToRilletDays("Net 30")).toBeUndefined();+ expect(mapPaymentTermsToRilletDays("-5")).toBeUndefined();+ expect(mapPaymentTermsToRilletDays("30.5")).toBeUndefined();+ expect(mapPaymentTermsToRilletDays(" 30 ")).toBe(30);+ expect(mapPaymentTermsToRilletDays("0")).toBe(0);+ expect(mapPaymentTermsToRilletDays("240", { max: 180 })).toBeUndefined();+ expect(mapPaymentTermsToRilletDays("180", { max: 180 })).toBe(180);+ });+});++describe("writeDroppingUnregisteredReferences", () => {+ const referenceError = new AccountingApiError("rillet", "create vendor", {+ statusCode: 400,+ statusText: "Bad Request",+ providerMessage:+ "External reference type does not exist: carbon. The existing external reference types are: . Please ensure that you are using an existing type or add a new type in the Rillet settings."+ });++ it("retries without external_references when the org has no registered types", async () => {+ const calls: unknown[] = [];+ const result = await writeDroppingUnregisteredReferences(+ { name: "MyVendor", external_references: [{ type: "carbon", id: "x" }] },+ async (payload) => {+ calls.push(payload);+ if ("external_references" in payload) throw referenceError;+ return { id: "vendor-1" };+ }+ );++ expect(result).toEqual({ id: "vendor-1" });+ expect(calls).toHaveLength(2);+ expect(calls[1]).toEqual({ name: "MyVendor" });+ });++ it("rethrows other errors untouched", async () => {+ const otherError = new AccountingApiError("rillet", "create vendor", {+ statusCode: 500,+ statusText: "Server Error"+ });+ await expect(+ writeDroppingUnregisteredReferences(+ { name: "MyVendor", external_references: [] },+ async () => {+ throw otherError;+ }+ )+ ).rejects.toBe(otherError);+ });++ it("rethrows when the payload carries no references to strip", async () => {+ const payload: { name: string; external_references?: unknown } = {+ name: "MyVendor"+ };+ await expect(+ writeDroppingUnregisteredReferences(payload, async () => {+ throw referenceError;+ })+ ).rejects.toBe(referenceError);+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/invoice.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/invoice.test.tsnew file mode 100644index 0000000000..606fd126ba--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/invoice.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from "vitest";+import type { Accounting } from "../../../../core/types";+import { mapSalesInvoiceToRilletInvoice } from "../invoice";+import { RILLET_CUSTOMER_CUSTOM_REFERENCE_TYPE } from "../shared";++function invoice(): Accounting.SalesInvoice {+ return {+ id: "si_1",+ invoiceId: "INV-0001",+ companyId: "company-1",+ customerId: "cust-1",+ customerExternalId: "rillet-cust-1",+ status: "Submitted",+ currencyCode: "USD",+ exchangeRate: 1,+ dateIssued: "2026-08-12",+ dateDue: "2026-09-11",+ datePaid: null,+ customerReference: null,+ subtotal: 100,+ totalTax: 0,+ totalDiscount: 0,+ totalAmount: 100,+ balance: 100,+ lines: [+ {+ id: "sil_1",+ invoiceLineType: "Part",+ itemId: "item-1",+ itemCode: "PART-001",+ description: "Widget",+ quantity: 2,+ unitPrice: 50,+ taxPercent: 0,+ lineAmount: 100+ }+ ],+ updatedAt: "2026-08-12T00:00:00.000Z"+ };+}++describe("mapSalesInvoiceToRilletInvoice — external references", () => {+ it("tags the invoice and every item with a CUSTOMER_CUSTOM reference (rev-rec accepted type)", () => {+ const payload = mapSalesInvoiceToRilletInvoice({+ invoice: invoice(),+ customerRemoteId: "rillet-cust-1",+ itemRemoteIds: new Map([["item-1", "rillet-prod-1"]]),+ subsidiaryId: null,+ companyId: "company-1",+ documentUrl: "https://erp.example.test/x/sales-invoice/si_1"+ });++ // Invoice-level: keeps the carbon audit refs AND adds the rev-rec-accepted+ // CUSTOMER_CUSTOM reference so a Revenue-Recognition org accepts the invoice.+ expect(+ payload.external_references?.some(+ (ref) =>+ ref.type === RILLET_CUSTOMER_CUSTOM_REFERENCE_TYPE &&+ ref.id === "si_1"+ )+ ).toBe(true);++ // Every item carries a CUSTOMER_CUSTOM ref keyed by the Carbon line id+ // (rev-rec requires an accepted reference on the invoice items too).+ expect(payload.items).toHaveLength(1);+ expect(+ payload.items[0]?.external_references.some(+ (ref) =>+ ref.type === RILLET_CUSTOMER_CUSTOM_REFERENCE_TYPE &&+ ref.id === "sil_1"+ )+ ).toBe(true);+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/journal-entry.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/journal-entry.test.tsnew file mode 100644index 0000000000..ee02028a71--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/journal-entry.test.ts@@ -0,0 +1,376 @@+import { describe, expect, it } from "vitest";+import {+ DEFAULT_POSTING_SYNC_SETTINGS,+ JournalEntrySyncError,+ type PostingSyncSettings+} from "../../../../core/posting";+import type { Accounting } from "../../../../core/types";+import {+ getRilletLockDate,+ mapJournalEntryToRilletJournalEntry+} from "../journal-entry";++// 3-line balanced fixture: Dr Inventory 150.00, Dr Freight 25.50,+// Cr GRNI accrual 175.50 (Carbon signed amounts: positive = debit)+const makeJournal = (+ overrides?: Partial<Accounting.JournalEntry>+): Accounting.JournalEntry => ({+ id: "je_123",+ companyId: "company-1",+ journalEntryId: "JE000042",+ description: "Receipt posting",+ postingDate: "2026-07-01",+ status: "Posted",+ sourceType: "Purchase Receipt",+ reversalOfId: null,+ reversedById: null,+ reversal: false,+ lines: [+ {+ id: "line-1",+ accountId: "acc-inventory",+ amount: 150,+ description: "Inventory"+ },+ { id: "line-2", accountId: "acc-freight", amount: 25.5, description: null },+ {+ id: "line-3",+ accountId: "acc-accrual",+ amount: -175.5,+ description: "GRNI accrual"+ }+ ],+ updatedAt: "2026-07-01T12:00:00.000Z",+ ...overrides+});++// Carbon account.id -> Rillet account code (mapping externalCode)+const ACCOUNT_CODES: ReadonlyMap<string, string> = new Map([+ ["acc-inventory", "1400"],+ ["acc-freight", "5100"],+ ["acc-accrual", "2100"]+]);++const makeSettings = (+ overrides?: Partial<PostingSyncSettings>+): PostingSyncSettings => ({+ ...DEFAULT_POSTING_SYNC_SETTINGS,+ enabled: true,+ ...overrides+});++describe("mapJournalEntryToRilletJournalEntry", () => {+ it("maps a 3-line journal to unsigned 2-dp string amounts with an explicit side (positive = DEBIT)", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: makeJournal(),+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01"+ });++ expect(payload.name).toBe("Receipt posting");+ expect(payload.date).toBe("2026-07-01");+ expect(payload.currency).toBe("USD");+ expect(payload.subsidiary_id).toBeUndefined();+ expect(payload.items).toEqual([+ {+ account_code: "1400",+ amount: { amount: "150.00", currency: "USD" },+ side: "DEBIT",+ description: "Inventory"+ },+ {+ // Line without a description falls back to the journal description+ account_code: "5100",+ amount: { amount: "25.50", currency: "USD" },+ side: "DEBIT",+ description: "Receipt posting"+ },+ {+ account_code: "2100",+ amount: { amount: "175.50", currency: "USD" },+ side: "CREDIT",+ description: "GRNI accrual"+ }+ ]);+ });++ it("produces a balanced payload with >= 2 items: DEBIT cents equal CREDIT cents", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: makeJournal(),+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01"+ });++ expect(payload.items.length).toBeGreaterThanOrEqual(2);++ const centsBySide = payload.items.reduce(+ (sides, item) => {+ sides[item.side] += Math.round(Number(item.amount.amount) * 100);+ return sides;+ },+ { DEBIT: 0, CREDIT: 0 }+ );++ expect(centsBySide.DEBIT).toBe(centsBySide.CREDIT);+ expect(centsBySide.DEBIT).toBe(17550);+ });++ it("rounds every amount to a 2-dp string", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: makeJournal({+ lines: [+ {+ id: "line-1",+ accountId: "acc-inventory",+ amount: 10.567,+ description: null+ },+ {+ id: "line-2",+ accountId: "acc-accrual",+ amount: -10.567,+ description: null+ }+ ]+ }),+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01"+ });++ expect(payload.items.map((item) => item.amount.amount)).toEqual([+ "10.57",+ "10.57"+ ]);+ });++ it("propagates the currency onto the payload and every item", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: makeJournal(),+ accountCodesById: ACCOUNT_CODES,+ currency: "EUR",+ subsidiaryId: null,+ pushDate: "2026-07-01"+ });++ expect(payload.currency).toBe("EUR");+ expect(payload.items.every((item) => item.amount.currency === "EUR")).toBe(+ true+ );+ });++ it("includes subsidiary_id only when configured", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: makeJournal(),+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: "sub-1",+ pushDate: "2026-07-01"+ });++ expect(payload.subsidiary_id).toBe("sub-1");+ });++ it("flips every side (amounts stay positive) and uses the reversal name for reversal pushes", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: makeJournal({ status: "Reversed", reversal: true }),+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01"+ });++ expect(payload.name).toBe("Reversal of Receipt posting");+ expect(payload.items.map((item) => item.side)).toEqual([+ "CREDIT",+ "CREDIT",+ "DEBIT"+ ]);+ expect(payload.items.map((item) => item.amount.amount)).toEqual([+ "150.00",+ "25.50",+ "175.50"+ ]);+ });++ it("falls back to the readable journal number when the description is empty", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: { ...makeJournal(), description: null },+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01"+ });++ expect(payload.name).toBe("Carbon JE000042");+ });++ it("appends the original date to the name when the push was re-dated", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: makeJournal(),+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-02",+ redatedFromDate: "2026-07-01"+ });++ expect(payload.name).toBe("Receipt posting | original date 2026-07-01");+ expect(payload.date).toBe("2026-07-02");+ });++ it("throws the structured UNMAPPED_ACCOUNTS error when a line's account has no mapping", () => {+ let thrown: unknown;+ try {+ mapJournalEntryToRilletJournalEntry({+ journal: makeJournal(),+ accountCodesById: new Map([["acc-inventory", "1400"]]),+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01"+ });+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(JournalEntrySyncError);+ const failure = (thrown as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(failure.warning).toBe(true);+ expect(failure.metadata?.unmappedAccountIds).toEqual(["acc-freight"]);+ });+});++// ── Dimension slots → item field refs (Phase 2, Rillet Fields) ───────────────++describe("mapJournalEntryToRilletJournalEntry — dimensions (Fields)", () => {+ const LOCATION_DIM = "dim_loc";+ const DEPARTMENT_FIELD_ID = "f1d10000-0000-0000-0000-000000000001";++ const dimensionedJournal = makeJournal({+ lines: [+ {+ id: "line-1",+ accountId: "acc-inventory",+ amount: 150,+ description: "Inventory",+ dimensions: [{ dimensionId: LOCATION_DIM, valueId: "loc_atl" }]+ },+ {+ id: "line-2",+ accountId: "acc-accrual",+ amount: -150,+ description: null,+ dimensions: [{ dimensionId: LOCATION_DIM, valueId: "loc_bos" }]+ }+ ]+ });++ const fieldIdByDimensionId = new Map([[LOCATION_DIM, DEPARTMENT_FIELD_ID]]);++ it("attaches uuid field refs (field_id + field_value_id — ids, never names) for every dimension on the line", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01",+ dimensions: {+ fieldIdByDimensionId,+ fieldValueIdsByValue: new Map([+ ["dim_loc:loc_atl", "fv-atl"],+ ["dim_loc:loc_bos", "fv-bos"]+ ])+ }+ });++ expect(payload.items[0]?.fields).toEqual([+ { field_id: DEPARTMENT_FIELD_ID, field_value_id: "fv-atl" }+ ]);+ expect(payload.items[1]?.fields).toEqual([+ { field_id: DEPARTMENT_FIELD_ID, field_value_id: "fv-bos" }+ ]);+ });++ it("omits fields for unmapped values (drop path) and when no dimension args are passed", () => {+ const dropped = mapJournalEntryToRilletJournalEntry({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01",+ dimensions: {+ fieldIdByDimensionId,+ fieldValueIdsByValue: new Map([["dim_loc:loc_atl", "fv-atl"]])+ }+ });+ expect(dropped.items[0]?.fields).toEqual([+ { field_id: DEPARTMENT_FIELD_ID, field_value_id: "fv-atl" }+ ]);+ expect(dropped.items[1]?.fields).toBeUndefined();++ const legacy = mapJournalEntryToRilletJournalEntry({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01"+ });+ expect(legacy.items[0]?.fields).toBeUndefined();+ });++ it("reuses upserted value ids on later pushes: an updated lookup resolves without re-creating", () => {+ // Simulates the autoCreate flow: the ensure step upserted Boston and+ // added it to the shared lookup — the mapper then resolves both values+ const lookup = new Map([["dim_loc:loc_atl", "fv-atl"]]);+ lookup.set("dim_loc:loc_bos", "fv-bos-upserted");++ const payload = mapJournalEntryToRilletJournalEntry({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01",+ dimensions: { fieldIdByDimensionId, fieldValueIdsByValue: lookup }+ });++ expect(payload.items[1]?.fields).toEqual([+ { field_id: DEPARTMENT_FIELD_ID, field_value_id: "fv-bos-upserted" }+ ]);+ });++ it("omits a dimension whose Field was not provisioned (no field mapping)", () => {+ const payload = mapJournalEntryToRilletJournalEntry({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ currency: "USD",+ subsidiaryId: null,+ pushDate: "2026-07-01",+ dimensions: {+ fieldIdByDimensionId: new Map(), // LOCATION_DIM Field not provisioned+ fieldValueIdsByValue: new Map([["dim_loc:loc_atl", "fv-atl"]])+ }+ });+ expect(payload.items[0]?.fields).toBeUndefined();+ });+});++describe("getRilletLockDate (closed-books source)", () => {+ it("returns ONLY the manual settings.lockDate, normalized to YYYY-MM-DD", () => {+ expect(getRilletLockDate(makeSettings({ lockDate: "2026-06-30" }))).toBe(+ "2026-06-30"+ );+ expect(+ getRilletLockDate(makeSettings({ lockDate: "2026-06-30T00:00:00.000Z" }))+ ).toBe("2026-06-30");+ });++ it("returns null when no manual lock date is stored (the Rillet API cannot read a close date)", () => {+ expect(getRilletLockDate(makeSettings())).toBeNull();+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment-push.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment-push.test.tsnew file mode 100644index 0000000000..e67d98a68e--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment-push.test.ts@@ -0,0 +1,471 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { RilletPaymentSyncer } from "../payment";++// Phase G — outbound payment write-back. A Carbon-born Posted payment pushes to+// Rillet as a payment document; a provider-recorded (pulled) payment is skipped+// by the mapping-exists guard. The pull path is covered in payment.test.ts.++vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: () => ({ functions: { invoke: vi.fn() } })+}));++// The mapping link runs inside withTriggersDisabled (a real Kysely transaction+// with a `SET LOCAL` statement). Stub it to invoke the callback with a capturing+// tx so the link's insert is observable without a live DB — `txLinkSink` records+// the values passed to `insertInto("externalIntegrationMapping").values(...)`.+const { txLinkSink } = vi.hoisted(() => ({+ txLinkSink: [] as Array<Record<string, unknown>>+}));+vi.mock("../../../../core/utils", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("../../../../core/utils")>();+ return {+ ...actual,+ withTriggersDisabled: async (+ _db: unknown,+ cb: (tx: unknown) => Promise<unknown>+ ) => {+ const insertBuilder: Record<string, unknown> = {};+ insertBuilder.values = (v: Record<string, unknown>) => {+ txLinkSink.push(v);+ return insertBuilder;+ };+ insertBuilder.onConflict = () => insertBuilder;+ insertBuilder.execute = async () => [];+ return cb({ insertInto: () => insertBuilder });+ }+ };+});++beforeEach(() => {+ txLinkSink.length = 0;+});++type PaymentRow = {+ status: "Draft" | "Posted" | "Voided";+ paymentType: "Receipt" | "Disbursement";+ bankAccount: string;+ currencyCode: string;+ exchangeRate: number;+ paymentDate: string;+ postingDate: string | null;+ reference: string | null;+};++type SettlementRow = {+ targetSalesInvoiceId: string | null;+ targetPurchaseInvoiceId: string | null;+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+};++function makePushDb(opts: {+ metadata?: unknown;+ payment?: PaymentRow;+ settlements?: SettlementRow[];+ linkSink: Array<Record<string, unknown>>;+}) {+ const selectChain = (rows: unknown[]) => {+ const b: Record<string, unknown> = {};+ b.select = () => b;+ b.where = () => b;+ b.execute = async () => rows;+ b.executeTakeFirst = async () => rows[0];+ return b;+ };+ return {+ selectFrom: (t: string) => {+ if (t === "companyIntegration") {+ return selectChain(+ opts.metadata === undefined ? [] : [{ metadata: opts.metadata }]+ );+ }+ if (t === "payment") {+ return selectChain(opts.payment ? [opts.payment] : []);+ }+ if (t === "invoiceSettlement") return selectChain(opts.settlements ?? []);+ return selectChain([]);+ },+ transaction: () => ({+ execute: async (cb: (tx: unknown) => Promise<unknown>) => {+ const insertBuilder: Record<string, unknown> = {};+ insertBuilder.values = (v: Record<string, unknown>) => {+ opts.linkSink.push(v);+ return insertBuilder;+ };+ insertBuilder.onConflict = () => insertBuilder;+ insertBuilder.execute = async () => [];+ const tx = {+ executeQuery: async () => ({ rows: [] }),+ insertInto: () => insertBuilder+ };+ return cb(tx);+ }+ })+ } as never;+}++function makeSyncer(opts: {+ db: ReturnType<typeof makePushDb>;+ mapping?: { metadata: Record<string, unknown> | null } | null;+ documentRemoteId?: string | null;+ accountCodes?: Map<string, string>;+ enabled?: boolean;+ createInvoicePayment?: ReturnType<typeof vi.fn>;+ createBillPayment?: ReturnType<typeof vi.fn>;+}) {+ const createInvoicePayment =+ opts.createInvoicePayment ??+ vi.fn(async () => ({ id: "rillet-pay-1", status: "SUCCESSFUL" }));+ const createBillPayment =+ opts.createBillPayment ??+ vi.fn(async () => ({ id: "rillet-pay-1", status: "SUCCESSFUL" }));++ const syncer = new RilletPaymentSyncer({+ database: opts.db,+ companyId: "company-1",+ provider: {+ id: "rillet",+ createInvoicePayment,+ createBillPayment+ } as never,+ config: {+ enabled: opts.enabled ?? true,+ direction: "two-way",+ owner: "accounting"+ },+ entityType: "payment"+ });++ const s = syncer as unknown as Record<string, unknown>;+ s.mappingService = {+ getByEntity: async () => opts.mapping ?? null,+ getExternalId: async () => opts.documentRemoteId ?? null+ };+ // Pre-seed the account-code cache so the adapter never hits the DB.+ s.accountCodesByIdPromise = Promise.resolve(+ opts.accountCodes ?? new Map([["bank-1", "1000"]])+ );++ return { syncer, createInvoicePayment, createBillPayment };+}++const apPayment: PaymentRow = {+ status: "Posted",+ paymentType: "Disbursement",+ bankAccount: "bank-1",+ currencyCode: "USD",+ exchangeRate: 1,+ paymentDate: "2026-08-07",+ postingDate: "2026-08-07",+ reference: "PAY-1"+};++const apSettlement: SettlementRow = {+ targetSalesInvoiceId: null,+ targetPurchaseInvoiceId: "pinv-1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0+};++describe("RilletPaymentSyncer push — happy path", () => {+ it("pushes a Carbon-born AP payment as a Rillet bill payment and links the mapping", async () => {+ const linkSink: Array<Record<string, unknown>> = [];+ const { syncer, createBillPayment } = makeSyncer({+ db: makePushDb({+ payment: apPayment,+ settlements: [apSettlement],+ linkSink+ }),+ mapping: null, // Carbon-born: no existing payment mapping+ documentRemoteId: "bill-remote-1"+ });++ const result = await syncer.pushToAccounting("pay_1");++ expect(result.status).toBe("success");+ expect(result.remoteId).toBe("rillet-pay-1");++ // Created against the mapped bill remote id, in the payment currency,+ // clearing through the mapped bank account, tagged with the Carbon id.+ expect(createBillPayment).toHaveBeenCalledTimes(1);+ const [billId, payload, idempotencyKey] = createBillPayment.mock.calls[0]!;+ expect(billId).toBe("bill-remote-1");+ expect(payload).toMatchObject({+ amount: { amount: "100.00", currency: "USD" },+ date: "2026-08-07",+ account_code: "1000",+ external_references: [{ type: "carbon", id: "pay_1" }]+ });+ expect(typeof idempotencyKey).toBe("string");++ // Mapping linked under the AP composite id, stamped Carbon-origin.+ expect(txLinkSink).toHaveLength(1);+ expect(txLinkSink[0]).toMatchObject({+ entityType: "payment",+ entityId: "pay_1",+ externalId: "bill:bill-remote-1:rillet-pay-1",+ metadata: { origin: "carbon" }+ });+ });++ it("pushes a Carbon-born AR payment as a Rillet invoice payment (prefix-less composite)", async () => {+ const { syncer, createInvoicePayment } = makeSyncer({+ db: makePushDb({+ payment: { ...apPayment, paymentType: "Receipt" },+ settlements: [+ {+ ...apSettlement,+ targetPurchaseInvoiceId: null,+ targetSalesInvoiceId: "sinv-1"+ }+ ],+ linkSink: []+ }),+ mapping: null,+ documentRemoteId: "inv-remote-1"+ });++ const result = await syncer.pushToAccounting("pay_1");++ expect(result.status).toBe("success");+ expect(createInvoicePayment).toHaveBeenCalledTimes(1);+ expect(txLinkSink[0]).toMatchObject({+ externalId: "inv-remote-1:rillet-pay-1"+ });+ });+});++describe("RilletPaymentSyncer push — origin routing (loop guard)", () => {+ it("skips a provider-known payment (mapping already exists) — idempotent", async () => {+ const { syncer, createBillPayment } = makeSyncer({+ db: makePushDb({+ payment: apPayment,+ settlements: [apSettlement],+ linkSink: []+ }),+ mapping: { metadata: null } as never // a pulled payment carries a mapping+ });+ // getByEntity returns a mapping WITH an externalId → idempotent skip.+ (syncer as unknown as Record<string, unknown>).mappingService = {+ getByEntity: async () => ({+ externalId: "bill:bill-remote-1:rillet-pay-1",+ metadata: null+ })+ };++ const result = await syncer.pushToAccounting("pay_1");++ expect(result.status).toBe("skipped");+ expect(result.error).toContain("already linked");+ expect(createBillPayment).not.toHaveBeenCalled();+ });+});++describe("RilletPaymentSyncer push — gates (parked as Skipped)", () => {+ it("skips when the AP family is not in documents mode", async () => {+ const { syncer, createBillPayment } = makeSyncer({+ db: makePushDb({+ metadata: {+ settings: { postingSync: { families: { ap: "journals" } } }+ },+ payment: apPayment,+ settlements: [apSettlement],+ linkSink: []+ }),+ mapping: null+ });++ const result = await syncer.pushToAccounting("pay_1");+ expect(result.status).toBe("skipped");+ expect(result.error).toContain("documents mode");+ expect(createBillPayment).not.toHaveBeenCalled();+ });++ it("fans a multi-settlement payment out to one provider payment per document, each linked under a suffixed key", async () => {+ let call = 0;+ const createBillPayment = vi.fn(async (..._args: unknown[]) => ({+ id: `rillet-pay-${++call}`,+ status: "SUCCESSFUL"+ }));+ const { syncer } = makeSyncer({+ db: makePushDb({+ payment: apPayment,+ settlements: [+ {+ ...apSettlement,+ targetPurchaseInvoiceId: "pinv-2",+ appliedAmount: 40+ },+ apSettlement+ ],+ linkSink: []+ }),+ mapping: null,+ documentRemoteId: "bill-remote-1",+ createBillPayment+ });++ const result = await syncer.pushToAccounting("pay_1");+ expect(result.status).toBe("success");++ // One provider payment per settlement, in deterministic target order+ // (pinv-1 before pinv-2), each for ITS applied amount.+ expect(createBillPayment).toHaveBeenCalledTimes(2);+ expect(createBillPayment.mock.calls[0]?.[1]).toMatchObject({+ amount: { amount: "100.00", currency: "USD" }+ });+ expect(createBillPayment.mock.calls[1]?.[1]).toMatchObject({+ amount: { amount: "40.00", currency: "USD" }+ });++ // Each fan-out leg links under `<paymentId>:<targetDocId>` so a partial+ // failure resumes instead of double-creating.+ expect(txLinkSink).toHaveLength(2);+ expect(txLinkSink[0]).toMatchObject({+ entityType: "payment",+ entityId: "pay_1:pinv-1",+ externalId: "bill:bill-remote-1:rillet-pay-1",+ metadata: { origin: "carbon" }+ });+ expect(txLinkSink[1]).toMatchObject({+ entityId: "pay_1:pinv-2",+ externalId: "bill:bill-remote-1:rillet-pay-2"+ });+ });++ it("skips a foreign-currency payment", async () => {+ const { syncer } = makeSyncer({+ db: makePushDb({+ payment: { ...apPayment, exchangeRate: 2 },+ settlements: [apSettlement],+ linkSink: []+ }),+ mapping: null+ });++ const result = await syncer.pushToAccounting("pay_1");+ expect(result.status).toBe("skipped");+ expect(result.error).toContain("FX");+ });++ it("skips a payment carrying a discount", async () => {+ const { syncer } = makeSyncer({+ db: makePushDb({+ payment: apPayment,+ settlements: [{ ...apSettlement, discountAmount: 5 }],+ linkSink: []+ }),+ mapping: null+ });++ const result = await syncer.pushToAccounting("pay_1");+ expect(result.status).toBe("skipped");+ expect(result.error).toContain("discount");+ });++ it("skips when the syncer config is disabled", async () => {+ const { syncer } = makeSyncer({+ db: makePushDb({+ payment: apPayment,+ settlements: [apSettlement],+ linkSink: []+ }),+ mapping: null,+ enabled: false+ });++ const result = await syncer.pushToAccounting("pay_1");+ expect(result.status).toBe("skipped");+ expect(result.error).toContain("disabled");+ });+});++describe("RilletPaymentSyncer push — void routing", () => {+ it("skips (not supported) a voided Carbon-originated payment", async () => {+ const { syncer } = makeSyncer({+ db: makePushDb({+ payment: { ...apPayment, status: "Voided" },+ settlements: [apSettlement],+ linkSink: []+ }),+ mapping: { metadata: { origin: "carbon" } }+ });++ const result = await syncer.pushToAccounting("pay_1");+ expect(result.status).toBe("skipped");+ expect(result.error).toContain("not supported");+ });++ it("skips a voided pulled payment (no Carbon-originated provider payment to reverse)", async () => {+ const { syncer } = makeSyncer({+ db: makePushDb({+ payment: { ...apPayment, status: "Voided" },+ settlements: [apSettlement],+ linkSink: []+ }),+ mapping: { metadata: null } // pulled: no origin stamp+ });++ const result = await syncer.pushToAccounting("pay_1");+ expect(result.status).toBe("skipped");+ expect(result.error).toContain("no Carbon-originated");+ });+});++describe("RilletPaymentSyncer.pushRemotePayment — mapping Warnings", () => {+ function adapter(opts: {+ documentRemoteId?: string | null;+ accountCodes?: Map<string, string>;+ }) {+ const { syncer } = makeSyncer({+ db: makePushDb({ linkSink: [] }),+ documentRemoteId: opts.documentRemoteId,+ accountCodes: opts.accountCodes+ });+ return syncer as unknown as {+ pushRemotePayment(ctx: {+ carbonPaymentId: string;+ family: "ar" | "ap";+ targetDocumentId: string;+ bankAccountId: string;+ amount: number;+ currencyCode: string;+ paidDate: string;+ reference: string | null;+ }): Promise<{ remoteId: string; compositeEntityId: string }>;+ };+ }++ const ctx = {+ carbonPaymentId: "pay_1",+ family: "ap" as const,+ targetDocumentId: "pinv-1",+ bankAccountId: "bank-1",+ amount: 100,+ currencyCode: "USD",+ paidDate: "2026-08-07",+ reference: "PAY-1"+ };++ it("warns (UNSYNCED_DOCUMENT) when the settled document has not synced", async () => {+ await expect(+ adapter({ documentRemoteId: null }).pushRemotePayment(ctx)+ ).rejects.toMatchObject({+ failure: { errorCode: "UNSYNCED_DOCUMENT", warning: true }+ });+ });++ it("warns (UNMAPPED_ACCOUNTS) when the bank account is not mapped", async () => {+ await expect(+ adapter({+ documentRemoteId: "bill-remote-1",+ accountCodes: new Map() // bank-1 absent+ }).pushRemotePayment(ctx)+ ).rejects.toMatchObject({+ failure: { errorCode: "UNMAPPED_ACCOUNTS", warning: true }+ });+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.tsnew file mode 100644index 0000000000..f8ee1dea43--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/payment.test.ts@@ -0,0 +1,1057 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ type NormalizedPayment,+ upsertLocalPaymentDraft+} from "../../../../core/payment-application";+import { Rillet } from "../../models";+import {+ getRilletBillPaymentSyncEntityId,+ getRilletPaymentAmount,+ getRilletPaymentCurrency,+ getRilletPaymentSyncEntityId,+ getSettledInvoiceStatus,+ mapRilletPaymentToLocal,+ parseRilletPaymentSyncEntityId,+ RilletPaymentSyncer+} from "../payment";++const { invokeMock } = vi.hoisted(() => ({ invokeMock: vi.fn() }));+vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: () => ({ functions: { invoke: invokeMock } })+}));++describe("composite payment sync entity id", () => {+ it("round-trips invoice + payment ids as a prefix-less AR id", () => {+ const entityId = getRilletPaymentSyncEntityId(+ "0b9f9c1e-9f10-4c8e-8f2c-1a2b3c4d5e6f",+ "7c8d9e0f-1a2b-3c4d-5e6f-7a8b9c0d1e2f"+ );++ expect(entityId).toBe(+ "0b9f9c1e-9f10-4c8e-8f2c-1a2b3c4d5e6f:7c8d9e0f-1a2b-3c4d-5e6f-7a8b9c0d1e2f"+ );+ expect(parseRilletPaymentSyncEntityId(entityId)).toEqual({+ family: "ar",+ documentRemoteId: "0b9f9c1e-9f10-4c8e-8f2c-1a2b3c4d5e6f",+ paymentRemoteId: "7c8d9e0f-1a2b-3c4d-5e6f-7a8b9c0d1e2f"+ });+ });++ it("round-trips bill + payment ids as a `bill:`-prefixed AP id", () => {+ const entityId = getRilletBillPaymentSyncEntityId(+ "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d",+ "9f8e7d6c-5b4a-3210-fedc-ba9876543210"+ );++ expect(entityId).toBe(+ "bill:1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d:9f8e7d6c-5b4a-3210-fedc-ba9876543210"+ );+ expect(parseRilletPaymentSyncEntityId(entityId)).toEqual({+ family: "ap",+ documentRemoteId: "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d",+ paymentRemoteId: "9f8e7d6c-5b4a-3210-fedc-ba9876543210"+ });+ });++ it("does not confuse a plain AR id with the `bill:` prefix", () => {+ // An AR invoice id never starts with "bill:" (Rillet ids are uuids), but+ // guard the discriminator anyway.+ expect(parseRilletPaymentSyncEntityId("inv-1:pay-1").family).toBe("ar");+ });++ it("throws on malformed ids (both families)", () => {+ expect(() => parseRilletPaymentSyncEntityId("no-separator")).toThrow(+ /Invalid Rillet payment sync entity id/+ );+ expect(() => parseRilletPaymentSyncEntityId(":pay-1")).toThrow(+ /Invalid Rillet payment sync entity id/+ );+ expect(() => parseRilletPaymentSyncEntityId("inv-1:")).toThrow(+ /Invalid Rillet payment sync entity id/+ );+ // "bill:" prefix with no separator in the remainder+ expect(() => parseRilletPaymentSyncEntityId("bill:no-separator")).toThrow(+ /Invalid Rillet payment sync entity id/+ );+ expect(() => parseRilletPaymentSyncEntityId("bill:b-1:")).toThrow(+ /Invalid Rillet payment sync entity id/+ );+ });+});++describe("getSettledInvoiceStatus", () => {+ it("covers the zero / partial / exact / over boundaries", () => {+ expect(+ getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 0 })+ ).toBeNull();+ expect(+ getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 40 })+ ).toBe("Partially Paid");+ expect(+ getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 100 })+ ).toBe("Paid");+ expect(+ getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 150 })+ ).toBe("Paid");+ });++ it("is cents-accurate and never restates degenerate invoices", () => {+ // 99.999 rounds to 10000 cents — exact at 2dp+ expect(+ getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 99.999 })+ ).toBe("Paid");+ expect(+ getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: 99.99 })+ ).toBe("Partially Paid");++ expect(+ getSettledInvoiceStatus({ invoiceTotal: 0, settledTotal: 50 })+ ).toBeNull();+ expect(+ getSettledInvoiceStatus({ invoiceTotal: 100, settledTotal: -5 })+ ).toBeNull();+ });+});++describe("mapRilletPaymentToLocal", () => {+ it("normalizes the list-endpoint shape (nested amount, date)", () => {+ const remote = Rillet.InvoicePaymentSchema.parse({+ id: "pay-1",+ status: "SUCCESSFUL",+ invoice_id: "inv-1",+ amount: { amount: "125.00", currency: "USD" },+ date: "2026-07-15",+ account_code: "1000",+ updated_at: "2026-07-15T10:00:00Z"+ });++ expect(mapRilletPaymentToLocal(remote)).toEqual({+ paymentRemoteId: "pay-1",+ invoiceRemoteId: "inv-1",+ amount: 125,+ currencyCode: "USD",+ date: "2026-07-15",+ status: "SUCCESSFUL",+ updatedAt: "2026-07-15T10:00:00Z"+ });+ });++ it("normalizes the webhook shape (flat amount + currency, payment_date, webhook-only statuses)", () => {+ const remote = Rillet.InvoicePaymentSchema.parse({+ id: "pay-2",+ status: "CLEARED",+ invoice_id: "inv-1",+ amount: 99.5,+ currency: "EUR",+ payment_date: "2026-07-16",+ cash_account_code: "1000",+ created_at: "2026-07-16T08:00:00Z",+ updated_at: "2026-07-16T09:00:00Z"+ });++ expect(mapRilletPaymentToLocal(remote)).toEqual({+ paymentRemoteId: "pay-2",+ invoiceRemoteId: "inv-1",+ amount: 99.5,+ currencyCode: "EUR",+ date: "2026-07-16",+ status: "CLEARED",+ updatedAt: "2026-07-16T09:00:00Z"+ });+ });++ it("passes FAILED through and defaults amount/currency when absent", () => {+ const local = mapRilletPaymentToLocal({+ id: "pay-3",+ status: "FAILED",+ updated_at: "2026-07-17T00:00:00Z"+ });++ expect(local.status).toBe("FAILED");+ expect(local.amount).toBe(0);+ expect(local.currencyCode).toBeNull();+ // No date fields → falls back to updated_at's date part+ expect(local.date).toBe("2026-07-17");+ // invoice_id absent → invoiceRemoteId omitted (completed from the+ // composite entity id in upsertLocal)+ expect(local.invoiceRemoteId).toBeUndefined();+ });++ it("accepts every status of both wire shapes (union schema)", () => {+ for (const status of [+ "SUCCESSFUL",+ "FAILED",+ "UNCLEARED",+ "CLEARED",+ "RECONCILED"+ ]) {+ expect(+ Rillet.InvoicePaymentSchema.parse({ id: "pay-x", status }).status+ ).toBe(status);+ }+ expect(() =>+ Rillet.InvoicePaymentSchema.parse({ id: "pay-x", status: "PENDING" })+ ).toThrow();+ });+});++describe("amount/currency normalization helpers", () => {+ it("reads nested, string and numeric amounts", () => {+ expect(+ getRilletPaymentAmount({+ id: "p",+ status: "SUCCESSFUL",+ amount: { amount: "10.50", currency: "USD" }+ })+ ).toBe(10.5);+ expect(+ getRilletPaymentAmount({ id: "p", status: "SUCCESSFUL", amount: "7.25" })+ ).toBe(7.25);+ expect(+ getRilletPaymentAmount({ id: "p", status: "SUCCESSFUL", amount: 3 })+ ).toBe(3);+ expect(getRilletPaymentAmount({ id: "p", status: "SUCCESSFUL" })).toBe(0);+ });++ it("prefers the nested currency, then the flat field", () => {+ expect(+ getRilletPaymentCurrency({+ id: "p",+ status: "SUCCESSFUL",+ amount: { amount: "10.50", currency: "USD" },+ currency: "EUR"+ })+ ).toBe("USD");+ expect(+ getRilletPaymentCurrency({+ id: "p",+ status: "SUCCESSFUL",+ amount: 10.5,+ currency: "EUR"+ })+ ).toBe("EUR");+ expect(+ getRilletPaymentCurrency({ id: "p", status: "SUCCESSFUL" })+ ).toBeNull();+ });+});++// A fake Kysely database that answers only the+// `selectFrom("companyIntegration").select("metadata")...executeTakeFirst()`+// chain the documents-mode gate reads. `metadata` undefined = no integration+// row (the gate then resolves to defaults = documents = enabled).+function makeMetadataDb(metadata: unknown) {+ const chain: any = {+ select: () => chain,+ where: () => chain,+ executeTakeFirst: async () =>+ metadata === undefined ? undefined : { metadata }+ };+ return { selectFrom: () => chain } as never;+}++/** metadata that puts a family into a given posting-sync mode. */+function familyModeMetadata(family: "ar" | "ap", mode: string) {+ return { settings: { postingSync: { families: { [family]: mode } } } };+}++describe("RilletPaymentSyncer.shouldSync ownership gate", () => {+ function makeSyncer(mappedInvoiceId: string | null, metadata?: unknown) {+ const syncer = new RilletPaymentSyncer({+ database: makeMetadataDb(metadata),+ companyId: "company-1",+ provider: { id: "rillet" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ // Stub the mapping lookup — the gate's only dependency+ (syncer as unknown as Record<string, unknown>).mappingService = {+ getEntityId: async () => mappedInvoiceId+ };+ return syncer as unknown as {+ shouldSync(context: {+ direction: "push" | "pull";+ remoteEntity?: Rillet.InvoicePayment;+ isFirstSync: boolean;+ entityId: string;+ }): Promise<boolean | string>;+ };+ }++ it("skips (does not fail) when the AR family is not in documents mode", async () => {+ const result = await makeSyncer(+ "sales-invoice-1",+ familyModeMetadata("ar", "journals")+ ).shouldSync({+ direction: "pull",+ entityId: "inv-ours:pay-1",+ remoteEntity: { id: "pay-1", status: "SUCCESSFUL" },+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("payment sync-back is disabled");+ expect(result).toContain("ar");+ });++ it("skips (does not fail) payments on invoices with no local mapping", async () => {+ const result = await makeSyncer(null).shouldSync({+ direction: "pull",+ entityId: "inv-other-subsidiary:pay-1",+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("no Carbon mapping");+ });++ it("proceeds for payments on locally-mapped invoices", async () => {+ const result = await makeSyncer("sales-invoice-1").shouldSync({+ direction: "pull",+ entityId: "inv-ours:pay-1",+ remoteEntity: { id: "pay-1", status: "SUCCESSFUL" },+ isFirstSync: true+ });+ expect(result).toBe(true);+ });++ it("still skips first-seen FAILED payments on mapped invoices", async () => {+ const result = await makeSyncer("sales-invoice-1").shouldSync({+ direction: "pull",+ entityId: "inv-ours:pay-1",+ remoteEntity: { id: "pay-1", status: "FAILED" },+ isFirstSync: true+ });+ expect(result).toContain("never recorded");+ });+});++// Fake Kysely db answering both the documents-mode gate's+// `companyIntegration.metadata` read AND the FX gate's `company.baseCurrencyCode`+// read (distinct by table).+function makeFxDb(metadata: unknown, baseCurrencyCode: string) {+ const chain = (result: unknown) => {+ const c: any = {+ select: () => c,+ where: () => c,+ executeTakeFirst: async () => result+ };+ return c;+ };+ return {+ selectFrom: (table: string) =>+ table === "company"+ ? chain({ baseCurrencyCode })+ : chain(metadata === undefined ? undefined : { metadata })+ } as never;+}++describe("RilletPaymentSyncer.shouldSync FX gate", () => {+ function makeFxSyncer(baseCurrency: string) {+ const syncer = new RilletPaymentSyncer({+ database: makeFxDb(undefined, baseCurrency),+ companyId: "company-1",+ provider: { id: "rillet" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ (syncer as unknown as Record<string, unknown>).mappingService = {+ getEntityId: async () => "sales-invoice-1"+ };+ return syncer as unknown as {+ shouldSync(context: {+ direction: "push" | "pull";+ remoteEntity?: Rillet.InvoicePayment;+ isFirstSync: boolean;+ entityId: string;+ }): Promise<boolean | string>;+ };+ }++ it("parks an FX payment whose currency differs from the base currency", async () => {+ const result = await makeFxSyncer("USD").shouldSync({+ direction: "pull",+ entityId: "inv-ours:pay-1",+ remoteEntity: {+ id: "pay-1",+ status: "SUCCESSFUL",+ amount: { amount: "125.00", currency: "EUR" }+ },+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("FX payment");+ expect(result).toContain("EUR");+ expect(result).toContain("USD");+ expect(result).toContain("not supported v1");+ });++ it("proceeds for a base-currency payment", async () => {+ const result = await makeFxSyncer("USD").shouldSync({+ direction: "pull",+ entityId: "inv-ours:pay-1",+ remoteEntity: {+ id: "pay-1",+ status: "SUCCESSFUL",+ amount: { amount: "125.00", currency: "USD" }+ },+ isFirstSync: true+ });+ expect(result).toBe(true);+ });++ it("proceeds when the payment carries no currency", async () => {+ const result = await makeFxSyncer("USD").shouldSync({+ direction: "pull",+ entityId: "inv-ours:pay-1",+ remoteEntity: { id: "pay-1", status: "SUCCESSFUL" },+ isFirstSync: true+ });+ expect(result).toBe(true);+ });+});++function makeMapperSyncer() {+ const syncer = new RilletPaymentSyncer({+ database: {} as never,+ companyId: "company-1",+ provider: { id: "rillet" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ return syncer as unknown as {+ mapToNormalized(+ remote: Rillet.InvoicePayment | Rillet.BillPayment,+ entityId: string+ ): NormalizedPayment;+ };+}++describe("RilletPaymentSyncer.mapToNormalized", () => {+ it("normalizes a SUCCESSFUL invoice payment to a settled AR NormalizedPayment", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ id: "pay-1",+ status: "SUCCESSFUL",+ amount: { amount: "125.00", currency: "USD" },+ date: "2026-07-15",+ updated_at: "2026-07-15T10:00:00Z"+ },+ "inv-1:pay-1"+ );++ expect(normalized).toEqual({+ family: "ar",+ documentRemoteId: "inv-1",+ paymentRemoteId: "pay-1",+ amount: 125,+ currencyCode: "USD",+ exchangeRate: 1,+ paidDate: "2026-07-15",+ reference: "pay-1",+ status: "settled"+ });+ });++ it("marks a FAILED payment as failed (the void path)", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ { id: "pay-2", status: "FAILED", updated_at: "2026-07-17T00:00:00Z" },+ "inv-1:pay-2"+ );+ expect(normalized.status).toBe("failed");+ expect(normalized.family).toBe("ar");+ expect(normalized.documentRemoteId).toBe("inv-1");+ });++ it("normalizes a bill payment (bill: id) to a settled AP NormalizedPayment", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ id: "bp-1",+ status: "SUCCESSFUL",+ bill_id: "bill-remote-1",+ amount: { amount: "500.00", currency: "USD" },+ date: "2026-08-01",+ updated_at: "2026-08-01T10:00:00Z"+ },+ "bill:bill-remote-1:bp-1"+ );++ expect(normalized).toEqual({+ family: "ap",+ documentRemoteId: "bill-remote-1",+ paymentRemoteId: "bp-1",+ amount: 500,+ currencyCode: "USD",+ exchangeRate: 1,+ paidDate: "2026-08-01",+ reference: "bp-1",+ status: "settled"+ });+ });++ it("marks a FAILED bill payment as failed (AP void path)", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ id: "bp-2",+ status: "FAILED",+ bill_id: "bill-remote-1",+ payment_date: "2026-08-02",+ updated_at: "2026-08-02T00:00:00Z"+ },+ "bill:bill-remote-1:bp-2"+ );+ expect(normalized.family).toBe("ap");+ expect(normalized.status).toBe("failed");+ expect(normalized.documentRemoteId).toBe("bill-remote-1");+ expect(normalized.paidDate).toBe("2026-08-02");+ });+});++// A minimal fake Kysely transaction that records writes and returns canned+// reads. Only the chains upsertLocalPaymentDraft (+ createMappingService) use+// are supported.+function makeFakeTx(store: {+ docMappings: Record<string, string>;+ salesInvoice?: { id: string; customerId: string; currencyCode: string };+ purchaseInvoice?: { id: string; supplierId: string; currencyCode: string };+ paymentMapping?: { entityId: string };+ existingPayment?: { id: string; status: string };+ newPaymentId: string;+ records: Array<{ op: string; table: string; values: unknown }>;+}) {+ const resolveOne = (b: any) => {+ const where = (col: string) =>+ b.wheres.find((w: any) => w.col === col)?.val;+ if (b.table === "externalIntegrationMapping") {+ if (b.selectedAll) return store.paymentMapping ?? undefined; // getByExternalId+ const entityId = store.docMappings[where("externalId") as string];+ return entityId ? { entityId } : undefined; // getEntityId+ }+ if (b.table === "salesInvoice") return store.salesInvoice;+ if (b.table === "purchaseInvoice") return store.purchaseInvoice;+ if (b.table === "payment") {+ if (b.op === "insert") return { id: store.newPaymentId };+ // Resolve by the queried id, like the real table — the settlement-keyed+ // mapping regression below depends on a wrong id NOT matching.+ return store.existingPayment && where("id") === store.existingPayment.id+ ? store.existingPayment+ : undefined;+ }+ return undefined;+ };+ const makeBuilder = (table: string, op: string) => {+ const b: any = {+ table,+ op,+ wheres: [] as Array<{ col: string; val: unknown }>,+ selectedAll: false,+ valuesArg: undefined as unknown,+ select() {+ return b;+ },+ selectAll() {+ b.selectedAll = true;+ return b;+ },+ innerJoin() {+ return b;+ },+ where(col: string, _o: string, val: unknown) {+ b.wheres.push({ col, val });+ return b;+ },+ set(v: unknown) {+ b.valuesArg = v;+ return b;+ },+ values(v: unknown) {+ b.valuesArg = v;+ return b;+ },+ returning() {+ return b;+ },+ onConflict() {+ return b;+ },+ orderBy() {+ return b;+ },+ limit() {+ return b;+ },+ async execute() {+ store.records.push({ op, table, values: b.valuesArg });+ return [];+ },+ async executeTakeFirst() {+ return resolveOne(b);+ },+ async executeTakeFirstOrThrow() {+ const row = resolveOne(b);+ if (!row) throw new Error("no row");+ store.records.push({ op, table, values: b.valuesArg });+ return row;+ }+ };+ return b;+ };+ return {+ selectFrom: (t: string) => makeBuilder(t, "select"),+ insertInto: (t: string) => makeBuilder(t, "insert"),+ updateTable: (t: string) => makeBuilder(t, "update"),+ deleteFrom: (t: string) => makeBuilder(t, "delete")+ } as never;+}++describe("upsertLocalPaymentDraft (AR)", () => {+ const settled: NormalizedPayment = {+ family: "ar",+ documentRemoteId: "inv-1",+ paymentRemoteId: "pay-1",+ amount: 125,+ currencyCode: "USD",+ exchangeRate: 1,+ paidDate: "2026-07-15",+ reference: "pay-1",+ status: "settled"+ };++ it("writes a Draft payment + invoiceSettlement and returns postAction 'post'", async () => {+ const store = {+ docMappings: { "inv-1": "sales-invoice-1" },+ salesInvoice: {+ id: "sales-invoice-1",+ customerId: "cust-1",+ currencyCode: "USD"+ },+ paymentMapping: undefined,+ existingPayment: undefined,+ newPaymentId: "payment-row-1",+ records: [] as Array<{ op: string; table: string; values: unknown }>+ };++ const result = await upsertLocalPaymentDraft(makeFakeTx(store), {+ providerId: "rillet",+ companyId: "company-1",+ actorId: "user-1",+ bankAccount: "bank-1",+ paymentMappingId: "inv-1:pay-1",+ getNextReadableId: async () => "PAY000001",+ normalized: settled+ });++ expect(result).toEqual({+ paymentRowId: "payment-row-1",+ family: "ar",+ postAction: "post"+ });++ const paymentInsert = store.records.find(+ (r) => r.op === "insert" && r.table === "payment"+ );+ expect(paymentInsert?.values).toMatchObject({+ status: "Draft",+ paymentType: "Receipt",+ customerId: "cust-1",+ supplierId: null,+ totalAmount: 125,+ bankAccount: "bank-1",+ reference: "pay-1",+ paymentId: "PAY000001"+ });+ // No journalId written by the draft path (post-payment owns the GL journal).+ expect(paymentInsert?.values).not.toHaveProperty("journalId");++ const settlementInsert = store.records.find(+ (r) => r.op === "insert" && r.table === "invoiceSettlement"+ );+ expect(settlementInsert?.values).toMatchObject([+ { targetSalesInvoiceId: "sales-invoice-1", appliedAmount: 125 }+ ]);++ // The payment mapping is linked under the composite id.+ expect(+ store.records.some(+ (r) => r.op === "insert" && r.table === "externalIntegrationMapping"+ )+ ).toBe(true);+ });++ it("returns postAction 'void' for a FAILED payment whose Carbon payment is Posted, without rewriting it", async () => {+ const store = {+ docMappings: { "inv-1": "sales-invoice-1" },+ salesInvoice: {+ id: "sales-invoice-1",+ customerId: "cust-1",+ currencyCode: "USD"+ },+ paymentMapping: { entityId: "payment-row-1" },+ existingPayment: { id: "payment-row-1", status: "Posted" },+ newPaymentId: "unused",+ records: [] as Array<{ op: string; table: string; values: unknown }>+ };++ const result = await upsertLocalPaymentDraft(makeFakeTx(store), {+ providerId: "rillet",+ companyId: "company-1",+ actorId: "user-1",+ bankAccount: "bank-1",+ paymentMappingId: "inv-1:pay-1",+ getNextReadableId: async () => "PAY000002",+ normalized: { ...settled, status: "failed" }+ });++ expect(result).toEqual({+ paymentRowId: "payment-row-1",+ family: "ar",+ postAction: "void"+ });+ // The Posted payment is left untouched — post-payment's void needs it Posted.+ expect(+ store.records.some(+ (r) => r.table === "payment" && (r.op === "insert" || r.op === "update")+ )+ ).toBe(false);+ });+});++describe("upsertLocalPaymentDraft (AP bill payment)", () => {+ const settledAp: NormalizedPayment = {+ family: "ap",+ documentRemoteId: "bill-remote-1",+ paymentRemoteId: "bp-1",+ amount: 500,+ currencyCode: "USD",+ exchangeRate: 1,+ paidDate: "2026-08-01",+ reference: "bp-1",+ status: "settled"+ };++ it("writes a Draft Disbursement payment + targetPurchaseInvoiceId settlement and returns postAction 'post'", async () => {+ const store = {+ docMappings: { "bill-remote-1": "purchase-invoice-1" },+ purchaseInvoice: {+ id: "purchase-invoice-1",+ supplierId: "supplier-1",+ currencyCode: "USD"+ },+ paymentMapping: undefined,+ existingPayment: undefined,+ newPaymentId: "payment-row-ap-1",+ records: [] as Array<{ op: string; table: string; values: unknown }>+ };++ const result = await upsertLocalPaymentDraft(makeFakeTx(store), {+ providerId: "rillet",+ companyId: "company-1",+ actorId: "user-1",+ bankAccount: "bank-1",+ paymentMappingId: "bill:bill-remote-1:bp-1",+ getNextReadableId: async () => "PAY000010",+ normalized: settledAp+ });++ expect(result).toEqual({+ paymentRowId: "payment-row-ap-1",+ family: "ap",+ postAction: "post"+ });++ const paymentInsert = store.records.find(+ (r) => r.op === "insert" && r.table === "payment"+ );+ expect(paymentInsert?.values).toMatchObject({+ status: "Draft",+ paymentType: "Disbursement",+ supplierId: "supplier-1",+ customerId: null,+ totalAmount: 500,+ bankAccount: "bank-1",+ reference: "bp-1",+ paymentId: "PAY000010"+ });++ const settlementInsert = store.records.find(+ (r) => r.op === "insert" && r.table === "invoiceSettlement"+ );+ expect(settlementInsert?.values).toMatchObject([+ { targetPurchaseInvoiceId: "purchase-invoice-1", appliedAmount: 500 }+ ]);++ // The AP payment mapping is linked under the `bill:` composite id.+ expect(+ store.records.some(+ (r) => r.op === "insert" && r.table === "externalIntegrationMapping"+ )+ ).toBe(true);+ });++ it("throws when the bill has no local mapping (all documents unmapped)", async () => {+ const store = {+ docMappings: {}, // bill-remote-1 is unmapped+ purchaseInvoice: undefined,+ paymentMapping: undefined,+ existingPayment: undefined,+ newPaymentId: "unused",+ records: [] as Array<{ op: string; table: string; values: unknown }>+ };++ await expect(+ upsertLocalPaymentDraft(makeFakeTx(store), {+ providerId: "rillet",+ companyId: "company-1",+ actorId: "user-1",+ bankAccount: "bank-1",+ paymentMappingId: "bill:bill-remote-1:bp-1",+ getNextReadableId: async () => "PAY000011",+ normalized: settledAp+ })+ ).rejects.toThrow(/No mapped bill/);++ // Nothing written — shouldSync should have skipped an unmapped bill first.+ expect(+ store.records.some(+ (r) => r.table === "payment" && (r.op === "insert" || r.op === "update")+ )+ ).toBe(false);+ });++ it("no-ops on a payment Carbon pushed with a settlement-keyed mapping (echo guard)", async () => {+ // The outbound multi-settlement push links the mapping under+ // `<paymentId>:<targetDocumentId>`, not the bare payment row id. Pulling+ // that payment back must resolve the row through the key's prefix and+ // leave the Posted payment untouched — before the fix it missed the row,+ // re-inserted the payment, and died on the mapping's unique-externalId+ // constraint.+ const store = {+ docMappings: { "bill-remote-1": "purchase-invoice-1" },+ purchaseInvoice: {+ id: "purchase-invoice-1",+ supplierId: "supplier-1",+ currencyCode: "USD"+ },+ paymentMapping: { entityId: "pmt-1:purchase-invoice-1" },+ existingPayment: { id: "pmt-1", status: "Posted" },+ newPaymentId: "unused",+ records: [] as Array<{ op: string; table: string; values: unknown }>+ };++ const result = await upsertLocalPaymentDraft(makeFakeTx(store), {+ providerId: "rillet",+ companyId: "company-1",+ actorId: "user-1",+ bankAccount: "bank-1",+ paymentMappingId: "bill:bill-remote-1:bp-1",+ getNextReadableId: async () => "PAY000012",+ normalized: settledAp+ });++ expect(result).toEqual({+ paymentRowId: "pmt-1",+ family: "ap",+ postAction: "none"+ });++ // No new payment row, no settlement rewrite, no duplicate mapping link.+ expect(+ store.records.some(+ (r) => r.table === "payment" && (r.op === "insert" || r.op === "update")+ )+ ).toBe(false);+ expect(+ store.records.some((r) => r.table === "externalIntegrationMapping")+ ).toBe(false);+ });+});++describe("RilletPaymentSyncer.shouldSync AP ownership gate", () => {+ function makeApSyncer(mappedBillId: string | null, metadata?: unknown) {+ const syncer = new RilletPaymentSyncer({+ database: makeMetadataDb(metadata),+ companyId: "company-1",+ provider: { id: "rillet" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ (syncer as unknown as Record<string, unknown>).mappingService = {+ getEntityId: async () => mappedBillId+ };+ return syncer as unknown as {+ shouldSync(context: {+ direction: "push" | "pull";+ remoteEntity?: Rillet.BillPayment;+ isFirstSync: boolean;+ entityId: string;+ }): Promise<boolean | string>;+ };+ }++ it("skips (does not fail) when the AP family is set to none", async () => {+ const result = await makeApSyncer(+ "purchase-invoice-1",+ familyModeMetadata("ap", "none")+ ).shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:bp-1",+ remoteEntity: { id: "bp-1", status: "SUCCESSFUL", bill_id: "bill-ours" },+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("payment sync-back is disabled");+ expect(result).toContain("ap");+ });++ it("skips (does not fail) bill payments on bills with no local mapping", async () => {+ const result = await makeApSyncer(null).shouldSync({+ direction: "pull",+ entityId: "bill:bill-other-subsidiary:bp-1",+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("no Carbon mapping");+ expect(result).toContain("bill");+ });++ it("proceeds for bill payments on locally-mapped bills", async () => {+ const result = await makeApSyncer("purchase-invoice-1").shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:bp-1",+ remoteEntity: { id: "bp-1", status: "SUCCESSFUL", bill_id: "bill-ours" },+ isFirstSync: true+ });+ expect(result).toBe(true);+ });++ it("still skips first-seen FAILED bill payments on mapped bills", async () => {+ const result = await makeApSyncer("purchase-invoice-1").shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:bp-1",+ remoteEntity: { id: "bp-1", status: "FAILED", bill_id: "bill-ours" },+ isFirstSync: true+ });+ expect(result).toContain("never recorded");+ });+});++describe("PaymentSyncerBase post-payment dispatch", () => {+ function makeDispatchSyncer(pending: {+ paymentRowId: string;+ postAction: "post" | "void" | "none";+ actorId: string;+ }) {+ const syncer = new RilletPaymentSyncer({+ database: {} as never,+ companyId: "company-1",+ provider: { id: "rillet" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ }) as unknown as {+ pendingPosts: Map<string, typeof pending>;+ applyPostPayment(remoteId: string, result: unknown): Promise<unknown>;+ };+ syncer.pendingPosts.set("inv-1:pay-1", pending);+ return syncer;+ }++ const successResult = {+ status: "success",+ action: "updated",+ localId: "payment-row-1",+ remoteId: "inv-1:pay-1"+ };++ beforeEach(() => {+ invokeMock.mockReset();+ invokeMock.mockResolvedValue({ data: null, error: null });+ });++ it("invokes post-payment {type:'post'} for a settled payment", async () => {+ const syncer = makeDispatchSyncer({+ paymentRowId: "payment-row-1",+ postAction: "post",+ actorId: "user-1"+ });++ const result = await syncer.applyPostPayment("inv-1:pay-1", successResult);++ expect(invokeMock).toHaveBeenCalledWith("post-payment", {+ body: {+ type: "post",+ paymentId: "payment-row-1",+ userId: "user-1",+ companyId: "company-1"+ }+ });+ expect(result).toEqual(successResult);+ });++ it("invokes post-payment {type:'void'} for a failed payment", async () => {+ const syncer = makeDispatchSyncer({+ paymentRowId: "payment-row-1",+ postAction: "void",+ actorId: "user-1"+ });++ await syncer.applyPostPayment("inv-1:pay-1", successResult);++ expect(invokeMock).toHaveBeenCalledWith("post-payment", {+ body: {+ type: "void",+ paymentId: "payment-row-1",+ userId: "user-1",+ companyId: "company-1"+ }+ });+ });++ it("does not invoke post-payment when postAction is 'none'", async () => {+ const syncer = makeDispatchSyncer({+ paymentRowId: "payment-row-1",+ postAction: "none",+ actorId: "user-1"+ });++ await syncer.applyPostPayment("inv-1:pay-1", successResult);+ expect(invokeMock).not.toHaveBeenCalled();+ });++ it("surfaces a post-payment error as a Failed result (not swallowed)", async () => {+ invokeMock.mockResolvedValue({+ data: { message: "Accounting period is locked" },+ error: { message: "Edge Function returned 500" }+ });+ const syncer = makeDispatchSyncer({+ paymentRowId: "payment-row-1",+ postAction: "post",+ actorId: "user-1"+ });++ const result = (await syncer.applyPostPayment(+ "inv-1:pay-1",+ successResult+ )) as { status: string; error: string };++ expect(result.status).toBe("error");+ expect(result.error).toContain("Accounting period is locked");+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/entities/bill.ts b/packages/ee/src/accounting/providers/rillet/entities/bill.tsnew file mode 100644index 0000000000..1064f3d4b3--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/bill.ts@@ -0,0 +1,551 @@+import { buildDimensionValueMappingEntityId } from "../../../core/dimension-mapping";+import {+ type CostingLine,+ costingLineItemLabel,+ loadBillCostingLines,+ toTransactionCurrencyLines+} from "../../../core/document-costing";+import { createMappingService } from "../../../core/external-mapping";+import {+ JournalEntrySyncError,+ toPostingDateString+} from "../../../core/posting";+import type { Accounting, ShouldSyncContext } from "../../../core/types";+import type {+ Rillet,+ RilletBillCreate,+ RilletTransactionWriteOmit+} from "../models";+import { buildRilletIdempotencyKey } from "../provider";+import type { RilletJournalDimensionArgs } from "./journal-entry";+import {+ carbonCompanyExternalReference,+ carbonExternalReference,+ loadRilletAccountCodesById,+ RilletTransactionSyncer,+ toRilletMoney,+ writeDroppingUnregisteredReferences+} from "./shared";++/**+ * RilletBillSyncer — Carbon purchase invoices → Rillet bills (push-only,+ * create-only; entityType "bill"). `expense_number` is Carbon's readable+ * purchase-invoice id.+ *+ * Rillet bill items are ACCOUNT-COSTED only (`account_code` + amount —+ * there is no item/product reference on bills), so the bill reproduces the+ * bill's posted "Purchase Invoice" journal: its lines minus the AP control+ * line ARE the bill items (shared `loadBillCostingLines`). The item behind+ * each PO-backed line is a description LABEL only, never an account.+ *+ * Lines without an account, or with an unmapped account, fail as the+ * structured UNMAPPED_ACCOUNTS Warning — the user assigns/maps the account+ * and retries. There is deliberately NO silent fallback account: misclassed+ * AP expense in the ledger of record is worse than a parked operation.+ *+ * FX bills replay in the invoice's transaction currency (base ÷+ * `exchangeRate`, residue balanced) with `exchange_rate` pinned on the+ * payload. Base-currency bills are byte-identical to the pre-refactor output+ * (only descriptions gain an item label).+ *+ * `due_date` is REQUIRED by Rillet; when Carbon has none it falls back to+ * the bill date (Rillet's own default for invoices).+ */++// Only posted bills are pushed (Draft has no journal to replay) — mirrors the+// Rillet invoice syncer's posted-status gate.+const SYNCABLE_STATUSES: Accounting.Bill["status"][] = [+ "Pending",+ "Open",+ "Return",+ "Debit Note Issued",+ "Partially Paid",+ "Paid",+ "Overdue"+];++// Row shapes (mirror the QBO bill syncer's)+type BillRow = {+ id: string;+ companyId: string;+ invoiceId: string;+ supplierId: string | null;+ status: Accounting.Bill["status"];+ dateIssued: string | null;+ dateDue: string | null;+ datePaid: string | null;+ currencyCode: string;+ exchangeRate: number;+ subtotal: number;+ totalTax: number;+ totalDiscount: number;+ totalAmount: number;+ balance: number;+ supplierReference: string | null;+ updatedAt: string | null;+};++type BillLineRow = {+ id: string;+ invoiceId: string;+ description: string | null;+ quantity: number;+ unitPrice: number | null;+ itemId: string | null;+ accountId: string | null;+ accountNumber: string | null;+ taxPercent: number | null;+ taxAmount: number | null;+ totalAmount: number | null;+ itemCode: string | null;+ purchaseOrderLineId: string | null;+};++/**+ * The costing lines that become bill items are the shared `CostingLine`+ * shape (base-currency, debit-signed, AP control line already excluded, with+ * item labels + dimensions attached). Kept as a local alias so the pure+ * mapper's tests read against a stable name.+ */+export type BillPostingJournalLine = CostingLine;++/** Prepend the item code/name label to a costing line's description so the+ * account-costed bill line still shows what was purchased. */+function describeCostingLine(line: CostingLine): string | undefined {+ const label = costingLineItemLabel(line);+ if (!label) return line.description ?? undefined;+ return line.description ? `${label} — ${line.description}` : label;+}++/**+ * Map a Carbon bill to the Rillet bill create payload. Pure — exported for+ * tests. `postingJournalLines` are the bill's costing lines (AP control line+ * already excluded by `loadBillCostingLines`); the mapper re-runs the AP+ * filter defensively so direct callers may pass raw journal lines too.+ *+ * The costing lines carry base-currency debit-signed amounts;+ * `bill.exchangeRate` converts them to the invoice's transaction currency+ * (pass-through at rate 1). Throws structured Warnings when the journal is+ * missing (invoice not posted / accounting off) or an account is unmapped.+ */+export function mapBillToRilletBill(args: {+ bill: Accounting.Bill;+ vendorRemoteId: string;+ accountCodesById: ReadonlyMap<string, string>;+ subsidiaryId: string | null;+ companyId: string;+ /** Costing lines of the bill's posted Purchase Invoice journal, debit-signed. */+ postingJournalLines: BillPostingJournalLine[];+ /** accountDefault.payablesAccount — the AP control line(s) to exclude. */+ payablesAccountId: string | null;+ /**+ * Slot config + resolved Field-value ids (same contract as the journal+ * mapper's RilletJournalDimensionArgs). Slotted line dimensions with no+ * resolvable value are OMITTED — the warn policy parks in the syncer+ * before mapping, so an unresolved value here is the recorded drop path.+ */+ dimensions?: RilletJournalDimensionArgs;+}): RilletBillCreate {+ const { bill } = args;+ const currency = bill.currencyCode;++ if (args.postingJournalLines.length === 0) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync bill ${bill.invoiceId}: no posted Purchase Invoice journal found — the bill's G/L costing comes from its posting journal. Post the invoice (with accounting enabled), then retry.`,+ warning: true,+ metadata: { billId: bill.id }+ });+ }++ // Defensive re-filter: loadBillCostingLines already dropped the AP control+ // line, but keep the filter so raw journal lines (tests) also work.+ const costingLines = args.postingJournalLines.filter(+ (line) =>+ line.accountId === null || line.accountId !== args.payablesAccountId+ );++ const unmapped = new Set<string>();+ const lineIdsWithoutAccount: string[] = [];+ for (const line of costingLines) {+ if (!line.accountId) {+ lineIdsWithoutAccount.push(line.id);+ continue;+ }+ if (!args.accountCodesById.get(line.accountId)) {+ unmapped.add(line.accountId);+ }+ }++ if (unmapped.size > 0 || lineIdsWithoutAccount.length > 0) {+ const parts: string[] = [];+ if (unmapped.size > 0) {+ parts.push(`${unmapped.size} account(s) have no Rillet account mapping`);+ }+ if (lineIdsWithoutAccount.length > 0) {+ parts.push(+ `${lineIdsWithoutAccount.length} posting journal line(s) have no account`+ );+ }+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync bill ${bill.invoiceId}: ${parts.join(+ "; "+ )}. Map the account(s) on the integration settings page, then retry.`,+ warning: true,+ metadata: {+ billId: bill.id,+ unmappedAccountIds: [...unmapped],+ ...(lineIdsWithoutAccount.length > 0 ? { lineIdsWithoutAccount } : {})+ }+ });+ }++ // FX: convert base-currency amounts to the invoice's transaction currency+ // (pass-through at rate 1) and pin exchange_rate on the payload below.+ const transactionLines = toTransactionCurrencyLines(+ costingLines,+ bill.exchangeRate+ );++ const items: Rillet.BillItem[] = transactionLines.map((line) => {+ const fieldRefs: Rillet.ItemFieldRef[] = [];+ if (args.dimensions) {+ for (const dimension of line.dimensions ?? []) {+ const fieldId = args.dimensions.fieldIdByDimensionId.get(+ dimension.dimensionId+ );+ if (!fieldId) continue;+ const fieldValueId = args.dimensions.fieldValueIdsByValue.get(+ buildDimensionValueMappingEntityId(+ dimension.dimensionId,+ dimension.valueId+ )+ );+ if (!fieldValueId) continue; // Field/value not provisioned — drop this ref+ fieldRefs.push({ field_id: fieldId, field_value_id: fieldValueId });+ }+ }++ const description = describeCostingLine(line);++ return {+ account_code: args.accountCodesById.get(line.accountId!)!,+ amount: toRilletMoney(line.amount, currency),+ ...(description ? { description } : {}),+ ...(fieldRefs.length > 0 ? { fields: fieldRefs } : {})+ };+ });++ const billDate = toPostingDateString(+ bill.dateIssued ?? new Date().toISOString()+ );++ return {+ vendor_id: args.vendorRemoteId,+ expense_number: bill.invoiceId,+ bill_date: billDate,+ // due_date is REQUIRED by Rillet — fall back to the bill date+ due_date: toPostingDateString(bill.dateDue ?? billDate),+ items,+ ...(args.subsidiaryId ? { subsidiary_id: args.subsidiaryId } : {}),+ // Pin the provider exchange rate for FX bills (omit at parity rate 1).+ ...(bill.exchangeRate !== 1 ? { exchange_rate: bill.exchangeRate } : {}),+ external_references: [+ carbonExternalReference(bill.id),+ carbonCompanyExternalReference(args.companyId)+ ]+ };+}++export class RilletBillSyncer extends RilletTransactionSyncer<+ Accounting.Bill,+ Rillet.Bill,+ RilletTransactionWriteOmit+> {+ private accountCodesByIdPromise?: Promise<Map<string, string>>;++ protected get pushOnlyEntityLabel(): string {+ return "Bills";+ }++ private getAccountCodesById(): Promise<Map<string, string>> {+ if (!this.accountCodesByIdPromise) {+ this.accountCodesByIdPromise = loadRilletAccountCodesById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountCodesByIdPromise;+ }++ // =================================================================+ // 1. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.Bill | null> {+ const bills = await this.fetchBillsByIds([id]);+ return bills.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.Bill>> {+ return this.fetchBillsByIds(ids);+ }++ private async fetchBillsByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.Bill>> {+ if (ids.length === 0) return new Map();++ const billRows = await this.database+ .selectFrom("purchaseInvoice")+ // `balance` is derived and lives only on the `purchaseInvoices` view+ .leftJoin("purchaseInvoices", "purchaseInvoices.id", "purchaseInvoice.id")+ .select([+ "purchaseInvoice.id",+ "purchaseInvoice.companyId",+ "purchaseInvoice.invoiceId",+ "purchaseInvoice.supplierId",+ "purchaseInvoice.status",+ "purchaseInvoice.dateIssued",+ "purchaseInvoice.dateDue",+ "purchaseInvoice.datePaid",+ "purchaseInvoice.currencyCode",+ "purchaseInvoice.exchangeRate",+ "purchaseInvoice.subtotal",+ "purchaseInvoice.totalTax",+ "purchaseInvoice.totalDiscount",+ "purchaseInvoice.totalAmount",+ "purchaseInvoices.balance",+ "purchaseInvoice.supplierReference",+ "purchaseInvoice.updatedAt"+ ])+ .where("purchaseInvoice.id", "in", ids)+ .where("purchaseInvoice.companyId", "=", this.companyId)+ .execute();++ if (billRows.length === 0) return new Map();++ const lineRows = await this.database+ .selectFrom("purchaseInvoiceLine")+ .leftJoin("item", "item.id", "purchaseInvoiceLine.itemId")+ .leftJoin("account", "account.id", "purchaseInvoiceLine.accountId")+ .select([+ "purchaseInvoiceLine.id",+ "purchaseInvoiceLine.invoiceId",+ "purchaseInvoiceLine.description",+ "purchaseInvoiceLine.quantity",+ "purchaseInvoiceLine.unitPrice",+ "purchaseInvoiceLine.itemId",+ "purchaseInvoiceLine.accountId",+ "purchaseInvoiceLine.taxPercent",+ "purchaseInvoiceLine.taxAmount",+ "purchaseInvoiceLine.totalAmount",+ "purchaseInvoiceLine.purchaseOrderLineId",+ "item.readableId as itemCode",+ "account.number as accountNumber"+ ])+ .where(+ "purchaseInvoiceLine.invoiceId",+ "in",+ billRows.map((b) => b.id)+ )+ .execute();++ // Supplier external IDs (entityType "vendor" — what the vendor syncer+ // stores)+ const supplierIds = billRows+ .map((b) => b.supplierId)+ .filter((id): id is string => id !== null);++ const supplierExternalIds = new Map<string, string | null>();+ if (supplierIds.length > 0) {+ const mappingService = createMappingService(+ this.database,+ this.companyId+ );+ for (const supplierId of supplierIds) {+ supplierExternalIds.set(+ supplierId,+ await mappingService.getExternalId(+ "vendor",+ supplierId,+ this.provider.id+ )+ );+ }+ }++ const linesByInvoice = new Map<string, BillLineRow[]>();+ for (const line of lineRows as BillLineRow[]) {+ const existing = linesByInvoice.get(line.invoiceId) ?? [];+ existing.push(line);+ linesByInvoice.set(line.invoiceId, existing);+ }++ const result = new Map<string, Accounting.Bill>();+ for (const row of billRows as BillRow[]) {+ const lines = linesByInvoice.get(row.id) ?? [];+ result.set(row.id, {+ id: row.id,+ companyId: row.companyId,+ invoiceId: row.invoiceId,+ supplierId: row.supplierId,+ supplierExternalId: row.supplierId+ ? (supplierExternalIds.get(row.supplierId) ?? null)+ : null,+ status: row.status,+ dateIssued: row.dateIssued,+ dateDue: row.dateDue,+ datePaid: row.datePaid,+ currencyCode: row.currencyCode,+ exchangeRate: Number(row.exchangeRate) || 1,+ subtotal: Number(row.subtotal) || 0,+ totalTax: Number(row.totalTax) || 0,+ totalDiscount: Number(row.totalDiscount) || 0,+ totalAmount: Number(row.totalAmount) || 0,+ balance: Number(row.balance) || 0,+ supplierReference: row.supplierReference,+ lines: lines.map((line) => ({+ id: line.id,+ description: line.description,+ quantity: Number(line.quantity) || 0,+ unitPrice: Number(line.unitPrice) || 0,+ itemId: line.itemId,+ itemCode: line.itemCode,+ accountId: line.accountId,+ accountNumber: line.accountNumber,+ taxPercent: line.taxPercent != null ? Number(line.taxPercent) : null,+ taxAmount: line.taxAmount != null ? Number(line.taxAmount) : null,+ totalAmount: Number(line.totalAmount) || 0,+ purchaseOrderLineId: line.purchaseOrderLineId+ })),+ updatedAt: row.updatedAt ?? new Date().toISOString(),+ raw: row+ });+ }++ return result;+ }++ // =================================================================+ // 2. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Rillet.Bill | null> {+ return this.rilletProvider.getBill(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Rillet.Bill>> {+ const result = new Map<string, Rillet.Bill>();+ for (const id of ids) {+ const bill = await this.rilletProvider.getBill(id);+ if (bill) result.set(bill.id, bill);+ }+ return result;+ }++ // =================================================================+ // 3. SHOULD SYNC (posted-bill gate)+ // =================================================================++ protected shouldSync(+ context: ShouldSyncContext<Accounting.Bill, Rillet.Bill>+ ): boolean | string {+ if (context.direction === "pull") {+ return "Bills are push-only; pulling bills from Rillet is not supported";+ }++ if (context.localEntity) {+ if (!SYNCABLE_STATUSES.includes(context.localEntity.status)) {+ return `Bill must be posted before syncing (current status: ${context.localEntity.status})`;+ }+ }++ return true;+ }++ // =================================================================+ // 4. TRANSFORMATION (Carbon -> Rillet)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.Bill+ ): Promise<RilletBillCreate> {+ // JIT dependency: vendor before the document+ let vendorRemoteId = local.supplierExternalId;+ if (!vendorRemoteId && local.supplierId) {+ vendorRemoteId = await this.ensureDependencySynced(+ "vendor",+ local.supplierId+ );+ }++ if (!vendorRemoteId) {+ throw new Error(+ `Cannot sync bill ${local.id}: No supplier linked or supplier not synced to Rillet`+ );+ }++ const payablesAccountId = await this.getPayablesAccountId();+ const { lines: costingLines } = await loadBillCostingLines(this.database, {+ companyId: this.companyId,+ billId: local.id,+ payablesAccountId+ });++ // Send ALL dimensions on the bill: auto-provision every Rillet Field ++ // value the COSTING lines reference (the AP control line never pushes, so+ // its dimensions never reach Rillet). Rillet has no field cap, so nothing+ // is dropped for lack of a slot.+ const { fieldIdByDimensionId, fieldValueIdsByValue } =+ await this.resolveLineDimensions(costingLines);++ return mapBillToRilletBill({+ bill: local,+ vendorRemoteId,+ accountCodesById: await this.getAccountCodesById(),+ subsidiaryId: this.rilletProvider.subsidiaryId,+ companyId: this.companyId,+ postingJournalLines: costingLines,+ payablesAccountId,+ dimensions: { fieldIdByDimensionId, fieldValueIdsByValue }+ });+ }++ /** accountDefault.payablesAccount — the AP control line to exclude. */+ private async getPayablesAccountId(): Promise<string | null> {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select("payablesAccount")+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();+ return defaults?.payablesAccount ?? null;+ }++ // =================================================================+ // 5. UPSERT REMOTE (create-only; RilletTransactionSyncer hard-skips+ // already-mapped ids)+ // =================================================================++ protected async upsertRemote(+ data: RilletBillCreate,+ localId: string+ ): Promise<string> {+ const created = await writeDroppingUnregisteredReferences(data, (payload) =>+ this.rilletProvider.createBill(+ payload,+ buildRilletIdempotencyKey({+ companyId: this.companyId,+ operation: "bill",+ localId+ })+ )+ );+ return created.id;+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/entities/customer.ts b/packages/ee/src/accounting/providers/rillet/entities/customer.tsnew file mode 100644index 0000000000..b6044ccd11--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/customer.ts@@ -0,0 +1,272 @@+import type { Accounting } from "../../../core/types";+import type { Rillet, RilletCustomerWrite, RilletWriteOmit } from "../models";+import { buildRilletIdempotencyKey } from "../provider";+import {+ carbonCompanyExternalReference,+ carbonExternalReference,+ mapContactAddressToRilletAddress,+ mapPaymentTermsToRilletDays,+ RilletEntitySyncer,+ writeDroppingUnregisteredReferences+} from "./shared";++/**+ * RilletCustomerSyncer — Carbon customers → Rillet Customer objects.+ * PUSH-ONLY in v1 (buildRilletSyncConfig forces direction/owner): pull+ * methods come from RilletEntitySyncer's push-only rejections.+ *+ * Rillet keeps customers and vendors as separate objects (like QBO, not+ * Xero's dual-flag Contact), so this syncer reads the customer tables+ * only and mapping rows live under entityType "customer". No+ * name-matching lookup before create (unlike QBO's smart match) — the+ * carbon external_reference plus the create Idempotency-Key are the+ * duplicate guards in v1.+ */++// Row shape for customer queries with address and contact joins (mirrors+// the QBO/Xero syncers' row so the Contact build stays identical)+type CustomerRow = {+ id: string;+ name: string;+ companyId: string;+ taxId: string | null;+ phone: string | null;+ fax: string | null;+ website: string | null;+ currencyCode: string | null;+ updatedAt: string | null;+ locationName: string | null;+ addressLine1: string | null;+ addressLine2: string | null;+ city: string | null;+ stateProvince: string | null;+ postalCode: string | null;+ countryCode: string | null;+ contactFirstName: string | null;+ contactLastName: string | null;+ contactEmail: string | null;+ contactMobilePhone: string | null;+ contactHomePhone: string | null;+ contactWorkPhone: string | null;+};++/**+ * Map a Carbon customer to the Rillet Customer write payload. Pure —+ * exported for tests.+ *+ * - The contact email becomes the MAIN_SENDER invoice recipient.+ * - The address maps only when Rillet's all-or-nothing group is complete+ * (line1/city/state/zip/country).+ * - payment_terms maps only from a bare non-negative integer day count.+ * - external_references carry the carbon (entity id) and+ * carbon-company (owning Carbon instance) tags.+ */+export function mapContactToRilletCustomer(+ local: Accounting.Contact+): RilletCustomerWrite {+ const address = mapContactAddressToRilletAddress(local);+ const paymentTerms = mapPaymentTermsToRilletDays(local.paymentTerms);++ return {+ name: local.name,+ ...(local.email+ ? { emails: [{ email: local.email, type: "MAIN_SENDER" as const }] }+ : {}),+ ...(address ? { address } : {}),+ ...(paymentTerms !== undefined ? { payment_terms: paymentTerms } : {}),+ external_references: [+ carbonExternalReference(local.id),+ carbonCompanyExternalReference(local.companyId)+ ]+ };+}++export class RilletCustomerSyncer extends RilletEntitySyncer<+ Accounting.Contact,+ Rillet.Customer,+ RilletWriteOmit+> {+ protected get pushOnlyEntityLabel(): string {+ return "Customers";+ }++ // =================================================================+ // 1. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.Contact | null> {+ const customers = await this.fetchCustomersByIds([id]);+ return customers.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.Contact>> {+ return this.fetchCustomersByIds(ids);+ }++ private async fetchCustomersByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.Contact>> {+ if (ids.length === 0) return new Map();++ const rows = await (this.database as any)+ .selectFrom("customer")+ .leftJoin("customerTax", "customerTax.customerId", "customer.id")+ .leftJoin(+ "customerLocation",+ "customerLocation.customerId",+ "customer.id"+ )+ .leftJoin("address", "address.id", "customerLocation.addressId")+ .leftJoin("customerContact", "customerContact.customerId", "customer.id")+ .leftJoin("contact", "contact.id", "customerContact.contactId")+ .select([+ "customer.id",+ "customer.name",+ "customer.companyId",+ "customerTax.taxId as taxId",+ "customer.phone",+ "customer.fax",+ "customer.website",+ "customer.currencyCode",+ "customer.updatedAt",+ "customerLocation.name as locationName",+ "address.addressLine1",+ "address.addressLine2",+ "address.city",+ // stateProvince + countryCode (alpha-2) feed Rillet's+ // all-or-nothing address group (state/country are required there)+ "address.stateProvince",+ "address.postalCode",+ "address.countryCode",+ "contact.firstName as contactFirstName",+ "contact.lastName as contactLastName",+ "contact.email as contactEmail",+ "contact.mobilePhone as contactMobilePhone",+ "contact.homePhone as contactHomePhone",+ "contact.workPhone as contactWorkPhone"+ ])+ .where("customer.id", "in", ids)+ .where("customer.companyId", "=", this.companyId)+ .execute();++ return this.groupAndTransformRows(rows as CustomerRow[]);+ }++ private groupAndTransformRows(+ rows: CustomerRow[]+ ): Map<string, Accounting.Contact> {+ const result = new Map<string, Accounting.Contact>();++ const groups = new Map<string, CustomerRow[]>();+ for (const row of rows) {+ const existing = groups.get(row.id) ?? [];+ existing.push(row);+ groups.set(row.id, existing);+ }++ for (const [id, groupRows] of groups) {+ const first = groupRows[0]!;+ const addresses = groupRows+ .filter((r) => r.addressLine1 || r.city)+ .map((r) => ({+ label: r.locationName ?? null,+ type: null,+ line1: r.addressLine1 ?? null,+ line2: r.addressLine2 ?? null,+ city: r.city ?? null,+ country: r.countryCode ?? null,+ region: r.stateProvince ?? null,+ postalCode: r.postalCode ?? null+ }));++ result.set(id, {+ id: first.id,+ name: first.name,+ firstName: first.contactFirstName ?? "",+ lastName: first.contactLastName ?? "",+ companyId: first.companyId,+ email: first.contactEmail ?? undefined,+ website: first.website ?? null,+ taxId: first.taxId ?? null,+ currencyCode: first.currencyCode ?? "USD",+ balance: null,+ creditLimit: null,+ paymentTerms: null,+ updatedAt: first.updatedAt ?? new Date().toISOString(),+ workPhone: first.contactWorkPhone ?? first.phone ?? null,+ mobilePhone: first.contactMobilePhone ?? null,+ fax: first.fax ?? null,+ homePhone: first.contactHomePhone ?? null,+ isVendor: false,+ isCustomer: true,+ addresses,+ raw: first+ });+ }++ return result;+ }++ // =================================================================+ // 2. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Rillet.Customer | null> {+ return this.rilletProvider.getCustomer(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Rillet.Customer>> {+ const result = new Map<string, Rillet.Customer>();+ for (const id of ids) {+ const customer = await this.rilletProvider.getCustomer(id);+ if (customer) result.set(customer.id, customer);+ }+ return result;+ }++ // =================================================================+ // 3. TRANSFORMATION (Carbon -> Rillet)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.Contact+ ): Promise<RilletCustomerWrite> {+ return mapContactToRilletCustomer(local);+ }++ // =================================================================+ // 4. UPSERT REMOTE (create with idempotency key, or PUT update)+ // =================================================================++ protected async upsertRemote(+ data: RilletCustomerWrite,+ localId: string+ ): Promise<string> {+ const existingRemoteId = await this.getRemoteId(localId);++ if (existingRemoteId) {+ const updated = await writeDroppingUnregisteredReferences(+ data,+ (payload) =>+ this.rilletProvider.updateCustomer(existingRemoteId, payload)+ );+ return updated.id ?? existingRemoteId;+ }++ const created = await writeDroppingUnregisteredReferences(data, (payload) =>+ this.rilletProvider.createCustomer(+ payload,+ buildRilletIdempotencyKey({+ companyId: this.companyId,+ operation: "customer",+ localId+ })+ )+ );+ return created.id;+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/entities/invoice.ts b/packages/ee/src/accounting/providers/rillet/entities/invoice.tsnew file mode 100644index 0000000000..cf9631f8f9--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/invoice.ts@@ -0,0 +1,420 @@+import {+ JournalEntrySyncError,+ toPostingDateString+} from "../../../core/posting";+import type { Accounting, ShouldSyncContext } from "../../../core/types";+import type {+ Rillet,+ RilletInvoiceCreate,+ RilletTransactionWriteOmit+} from "../models";+import {+ buildRilletIdempotencyKey,+ isRilletUnknownExternalReferenceTypeError+} from "../provider";+import {+ carbonCompanyExternalReference,+ carbonExternalReference,+ customerCustomExternalReference,+ RILLET_CARBON_COMPANY_REFERENCE_TYPE,+ RILLET_CARBON_REFERENCE_TYPE,+ RilletTransactionSyncer,+ toRilletMoney+} from "./shared";++/**+ * RilletSalesInvoiceSyncer — Carbon sales invoices → Rillet AR_ONLY+ * invoices (push-only, create-only; entityType "invoice").+ *+ * AR_ONLY is Rillet's external-ERP scope: Carbon keeps generating and+ * sending the invoice; Rillet carries the receivable (and reports+ * payments back through the invoice-payment-updated webhook → the payment+ * syncer). `invoice_number` is Carbon's readable invoice id.+ *+ * Customer and line items are JIT-synced via ensureDependencySynced+ * before the document. Rillet AR_ONLY items REQUIRE a product_id, so a+ * line without a Carbon item cannot be represented — it fails with a+ * structured Warning listing the lines (UNMAPPED_ACCOUNTS envelope: the+ * closest user-fixable code available; the core error-code list has no+ * missing-item code yet).+ *+ * Create-only: pushed invoices are never updated from Carbon in v1 —+ * RilletTransactionSyncer hard-skips already-mapped ids (updates are a+ * follow-up).+ */++// Only posted invoices are pushed (same status gate as the Xero/QBO+// sales-invoice syncers)+const SYNCABLE_STATUSES: Accounting.SalesInvoice["status"][] = [+ "Pending",+ "Submitted",+ "Partially Paid",+ "Paid",+ "Overdue"+];++// Row shapes for sales invoice queries (mirror the QBO syncer's)+type InvoiceRow = {+ id: string;+ invoiceId: string;+ companyId: string;+ customerId: string;+ status: Accounting.SalesInvoice["status"];+ currencyCode: string;+ exchangeRate: number;+ dateIssued: string | null;+ dateDue: string | null;+ datePaid: string | null;+ customerReference: string | null;+ subtotal: number;+ totalTax: number;+ totalDiscount: number;+ totalAmount: number;+ balance: number;+ updatedAt: string | null;+};++type InvoiceLineRow = {+ id: string;+ invoiceId: string;+ invoiceLineType: string;+ itemId: string | null;+ description: string | null;+ quantity: number;+ unitPrice: number;+ taxPercent: number;+ itemReadableIdWithRevision: string | null;+};++/**+ * Map a Carbon sales invoice to the Rillet AR_ONLY create payload. Pure —+ * exported for tests. `itemRemoteIds` maps Carbon itemId → Rillet product+ * id (resolved by ensureDependencySynced before mapping).+ *+ * Throws the structured UNMAPPED_ACCOUNTS Warning when any line has no+ * item (AR_ONLY items require product_id), and a plain Error when a+ * line's item was not resolved to a product (a dependency-sync bug, not+ * user-fixable).+ */+export function mapSalesInvoiceToRilletInvoice(args: {+ invoice: Accounting.SalesInvoice;+ customerRemoteId: string;+ itemRemoteIds: ReadonlyMap<string, string>;+ subsidiaryId: string | null;+ companyId: string;+ /** Link back to the Carbon invoice — REQUIRED by Rillet on+ * CUSTOMER_CUSTOM references. */+ documentUrl: string;+}): RilletInvoiceCreate {+ const { invoice } = args;+ const currency = invoice.currencyCode;++ const lineIdsWithoutItem = invoice.lines+ .filter((line) => !line.itemId)+ .map((line) => line.id);+ if (lineIdsWithoutItem.length > 0) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync invoice ${invoice.invoiceId}: ${lineIdsWithoutItem.length} line(s) have no item — Rillet AR_ONLY invoice lines require a product. Assign an item to the line(s), then retry.`,+ warning: true,+ metadata: { invoiceId: invoice.id, lineIdsWithoutItem }+ });+ }++ const items: Rillet.InvoiceItem[] = invoice.lines.map((line) => {+ const productId = args.itemRemoteIds.get(line.itemId!);+ if (!productId) {+ throw new Error(+ `Cannot sync invoice ${invoice.invoiceId}: item ${line.itemId} has not been synced to Rillet`+ );+ }++ return {+ product_id: productId,+ description: line.description ?? line.itemCode ?? "Invoice line",+ quantity: line.quantity,+ total_amount: toRilletMoney(line.quantity * line.unitPrice, currency),+ // CUSTOMER_CUSTOM satisfies rev-rec validation and carries the line id+ // for audit. NO `carbon` ref here: Rillet counts header + item+ // references together for RESTRICTED types, and organizations that+ // register `carbon` as restricted reject a document carrying it on+ // both the header and a line ("multiple references of a restricted+ // type" — verified on the sandbox 2026-08-12). The header's carbon+ // ref is the document's single origin link.+ external_references: [+ customerCustomExternalReference(line.id, args.documentUrl)+ ]+ };+ });++ const invoiceDate = toPostingDateString(+ invoice.dateIssued ?? new Date().toISOString()+ );++ return {+ scope: "AR_ONLY",+ customer_id: args.customerRemoteId,+ invoice_number: invoice.invoiceId,+ invoice_date: invoiceDate,+ // Rillet defaults due_date to invoice_date when omitted+ ...(invoice.dateDue+ ? { due_date: toPostingDateString(invoice.dateDue) }+ : {}),+ ...(invoice.totalTax > 0+ ? { tax_amount: toRilletMoney(invoice.totalTax, currency) }+ : {}),+ ...(args.subsidiaryId ? { subsidiary_id: args.subsidiaryId } : {}),+ items,+ // CUSTOMER_CUSTOM satisfies Rillet rev-rec validation (accepted integration+ // type); the carbon / carbon-company refs stay for origin auditing.+ external_references: [+ carbonExternalReference(invoice.id),+ carbonCompanyExternalReference(args.companyId),+ customerCustomExternalReference(invoice.id, args.documentUrl)+ ]+ };+}++export class RilletSalesInvoiceSyncer extends RilletTransactionSyncer<+ Accounting.SalesInvoice,+ Rillet.Invoice,+ RilletTransactionWriteOmit+> {+ protected get pushOnlyEntityLabel(): string {+ return "Sales invoices";+ }++ // =================================================================+ // 1. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.SalesInvoice | null> {+ const invoices = await this.fetchInvoicesByIds([id]);+ return invoices.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.SalesInvoice>> {+ return this.fetchInvoicesByIds(ids);+ }++ private async fetchInvoicesByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.SalesInvoice>> {+ if (ids.length === 0) return new Map();++ const invoiceRows = await this.database+ .selectFrom("salesInvoice")+ // `balance` is derived and lives only on the `salesInvoices` view+ .leftJoin("salesInvoices", "salesInvoices.id", "salesInvoice.id")+ .select([+ "salesInvoice.id",+ "salesInvoice.invoiceId",+ "salesInvoice.companyId",+ "salesInvoice.customerId",+ "salesInvoice.status",+ "salesInvoice.currencyCode",+ "salesInvoice.exchangeRate",+ "salesInvoice.dateIssued",+ "salesInvoice.dateDue",+ "salesInvoice.datePaid",+ "salesInvoice.customerReference",+ "salesInvoice.subtotal",+ "salesInvoice.totalTax",+ "salesInvoice.totalDiscount",+ "salesInvoice.totalAmount",+ "salesInvoices.balance",+ "salesInvoice.updatedAt"+ ])+ .where("salesInvoice.id", "in", ids)+ .where("salesInvoice.companyId", "=", this.companyId)+ .execute();++ if (invoiceRows.length === 0) return new Map();++ const lineRows = await this.database+ .selectFrom("salesInvoiceLine")+ .leftJoin("item", "item.id", "salesInvoiceLine.itemId")+ .select([+ "salesInvoiceLine.id",+ "salesInvoiceLine.invoiceId",+ "salesInvoiceLine.invoiceLineType",+ "salesInvoiceLine.itemId",+ "salesInvoiceLine.description",+ "salesInvoiceLine.quantity",+ "salesInvoiceLine.unitPrice",+ "salesInvoiceLine.taxPercent",+ "item.readableIdWithRevision as itemReadableIdWithRevision"+ ])+ .where(+ "salesInvoiceLine.invoiceId",+ "in",+ invoiceRows.map((r) => r.id)+ )+ .execute();++ const linesByInvoiceId = new Map<string, InvoiceLineRow[]>();+ for (const line of lineRows as InvoiceLineRow[]) {+ const existing = linesByInvoiceId.get(line.invoiceId) ?? [];+ existing.push(line);+ linesByInvoiceId.set(line.invoiceId, existing);+ }++ const result = new Map<string, Accounting.SalesInvoice>();+ for (const row of invoiceRows as InvoiceRow[]) {+ const lines = linesByInvoiceId.get(row.id) ?? [];++ result.set(row.id, {+ id: row.id,+ invoiceId: row.invoiceId,+ companyId: row.companyId,+ customerId: row.customerId,+ customerExternalId: null, // Resolved during mapToRemote+ status: row.status,+ currencyCode: row.currencyCode,+ exchangeRate: Number(row.exchangeRate) || 1,+ dateIssued: row.dateIssued,+ dateDue: row.dateDue,+ datePaid: row.datePaid,+ customerReference: row.customerReference,+ subtotal: Number(row.subtotal) || 0,+ totalTax: Number(row.totalTax) || 0,+ totalDiscount: Number(row.totalDiscount) || 0,+ totalAmount: Number(row.totalAmount) || 0,+ balance: Number(row.balance) || 0,+ lines: lines.map((line) => {+ const quantity = Number(line.quantity) || 0;+ const unitPrice = Number(line.unitPrice) || 0;+ return {+ id: line.id,+ invoiceLineType: line.invoiceLineType,+ itemId: line.itemId,+ itemCode: line.itemReadableIdWithRevision,+ description: line.description,+ quantity,+ unitPrice,+ taxPercent: Number(line.taxPercent) || 0,+ lineAmount: quantity * unitPrice+ };+ }),+ updatedAt: row.updatedAt ?? new Date().toISOString(),+ raw: row+ });+ }++ return result;+ }++ // =================================================================+ // 2. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Rillet.Invoice | null> {+ return this.rilletProvider.getInvoice(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Rillet.Invoice>> {+ const result = new Map<string, Rillet.Invoice>();+ for (const id of ids) {+ const invoice = await this.rilletProvider.getInvoice(id);+ if (invoice) result.set(invoice.id, invoice);+ }+ return result;+ }++ // =================================================================+ // 3. SHOULD SYNC (posted-invoice gate)+ // =================================================================++ protected shouldSync(+ context: ShouldSyncContext<Accounting.SalesInvoice, Rillet.Invoice>+ ): boolean | string {+ if (context.direction === "pull") {+ return "Sales invoices are push-only; pulling invoices from Rillet is not supported";+ }++ if (context.localEntity) {+ if (!SYNCABLE_STATUSES.includes(context.localEntity.status)) {+ return `Invoice must be posted before syncing (current status: ${context.localEntity.status})`;+ }+ }++ return true;+ }++ // =================================================================+ // 4. TRANSFORMATION (Carbon -> Rillet)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.SalesInvoice+ ): Promise<RilletInvoiceCreate> {+ // JIT dependencies: customer, then every line item, before the document+ const customerRemoteId = await this.ensureDependencySynced(+ "customer",+ local.customerId+ );++ const itemRemoteIds = new Map<string, string>();+ for (const line of local.lines) {+ if (line.itemId && !itemRemoteIds.has(line.itemId)) {+ itemRemoteIds.set(+ line.itemId,+ await this.ensureDependencySynced("item", line.itemId)+ );+ }+ }++ // Dynamic import: keeps @carbon/env (module-load env validation) out of+ // the module graph for consumers and tests that never push an invoice+ // (same pattern as the payment syncer's auth import).+ const { getAppUrl } = await import("@carbon/env");++ return mapSalesInvoiceToRilletInvoice({+ invoice: local,+ customerRemoteId,+ itemRemoteIds,+ subsidiaryId: this.rilletProvider.subsidiaryId,+ companyId: this.companyId,+ documentUrl: `${getAppUrl()}/x/sales-invoice/${local.id}`+ });+ }++ // =================================================================+ // 5. UPSERT REMOTE (create-only; RilletTransactionSyncer hard-skips+ // already-mapped ids — updates are a follow-up)+ // =================================================================++ protected async upsertRemote(+ data: RilletInvoiceCreate,+ localId: string+ ): Promise<string> {+ try {+ const created = await this.rilletProvider.createInvoice(+ data,+ buildRilletIdempotencyKey({+ companyId: this.companyId,+ operation: "invoice",+ localId+ })+ );+ return created.id;+ } catch (error) {+ // AR_ONLY invoices REQUIRE external_references, so the optional-+ // reference strip fallback the master-data syncers use cannot apply —+ // registering the slugs in the Rillet dashboard is the only fix.+ if (isRilletUnknownExternalReferenceTypeError(error)) {+ throw new JournalEntrySyncError({+ errorCode: "EXTERNAL_REFERENCE_TYPE_MISSING",+ message: `Cannot sync invoice: Rillet requires external references on AR_ONLY invoices, and this organization has no "${RILLET_CARBON_REFERENCE_TYPE}" / "${RILLET_CARBON_COMPANY_REFERENCE_TYPE}" reference types registered. Add them under Rillet Settings → External References, then retry.`,+ warning: true,+ metadata: { invoiceId: localId }+ });+ }+ throw error;+ }+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/entities/item.ts b/packages/ee/src/accounting/providers/rillet/entities/item.tsnew file mode 100644index 0000000000..5bbe03c594--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/item.ts@@ -0,0 +1,330 @@+import { JournalEntrySyncError } from "../../../core/posting";+import type { Accounting } from "../../../core/types";+import type { Rillet, RilletProductWrite, RilletWriteOmit } from "../models";+import { buildRilletIdempotencyKey } from "../provider";+import {+ carbonCompanyExternalReference,+ carbonExternalReference,+ loadCompanyBaseCurrency,+ loadRilletAccountCodesById,+ RilletEntitySyncer,+ toRilletMoney,+ writeDroppingUnregisteredReferences+} from "./shared";++/**+ * RilletItemSyncer — push-only: Carbon items become Rillet Products.+ * This syncer exists chiefly as the invoice-line dependency: Rillet+ * AR_ONLY invoice items REQUIRE a product_id, so the invoice syncer calls+ * ensureDependencySynced("item", ...) before mapping.+ *+ * Rillet products are revenue objects, not inventory: the required+ * `account_code` is the REVENUE account, resolved from the company's+ * accountDefault.salesAccount through the account-mapping externalCode+ * map (items carry no per-item posting accounts). An unmapped/missing+ * sales account → structured UNMAPPED_ACCOUNTS Warning, same errorCode+ * contract as the journal pre-flight.+ *+ * Rillet Product name is the unique-ish item key and maps from Carbon's+ * unique item code (readableIdWithRevision) — the same role QBO's+ * Item.Name plays. The 250-char cap → structured NAME_TOO_LONG Warning+ * (no silent truncation).+ */++/** Rillet caps product names at 250 characters. */+export const RILLET_PRODUCT_NAME_MAX_LENGTH = 250;++/**+ * Map a Carbon item to the Rillet Product write payload. Pure — exported+ * for tests.+ *+ * ASSUMPTIONS (the create-product docs give no ERP-integration guidance;+ * chosen as the safest minimal valid payload):+ * - `price` is ONE_TIME at the item's unit sale price in the company base+ * currency — nominal only, since AR_ONLY invoice items carry their own+ * `total_amount` (the price never books revenue by itself).+ * - `include_in_arr_mrr: false` — Carbon-invoiced products must not skew+ * Rillet's recurring-revenue metrics.+ * - `revenue_pattern: "EVEN_PERIOD"` — immediate/even recognition for the+ * invoice period; Carbon does not model service periods in v1.+ */+export function mapItemToRilletProduct(args: {+ item: Accounting.Item;+ accountCodesById: ReadonlyMap<string, string>;+ revenueAccountId: string | null;+ currency: string;+}): RilletProductWrite {+ const { item } = args;++ if (item.code.length > RILLET_PRODUCT_NAME_MAX_LENGTH) {+ throw new JournalEntrySyncError({+ errorCode: "NAME_TOO_LONG",+ message: `The item code is ${item.code.length} characters; Rillet caps product names at ${RILLET_PRODUCT_NAME_MAX_LENGTH}. Shorten the item code in Carbon, then retry.`,+ warning: true,+ metadata: {+ entityLabel: "item",+ name: item.code,+ maxLength: RILLET_PRODUCT_NAME_MAX_LENGTH+ }+ });+ }++ const accountCode = args.revenueAccountId+ ? args.accountCodesById.get(args.revenueAccountId)+ : undefined;++ if (!accountCode) {+ const missingDefault = !args.revenueAccountId;+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync item ${item.code}: ${+ missingDefault+ ? "the company account defaults are missing salesAccount"+ : "the default sales account has no Rillet account mapping"+ } — Rillet products require a revenue account code. Map the account on the integration settings page, then retry.`,+ warning: true,+ metadata: {+ itemId: item.id,+ unmappedAccountIds: args.revenueAccountId+ ? [args.revenueAccountId]+ : [],+ ...(missingDefault ? { missingDefaults: ["salesAccount"] } : {})+ }+ });+ }++ return {+ name: item.code,+ description: item.description ?? item.name,+ price: {+ type: "ONE_TIME",+ amount: toRilletMoney(item.unitSalePrice, args.currency)+ },+ include_in_arr_mrr: false,+ revenue_pattern: "EVEN_PERIOD",+ account_code: accountCode,+ status: "ACTIVE",+ external_references: [+ carbonExternalReference(item.id),+ carbonCompanyExternalReference(item.companyId)+ ]+ };+}++// Row shape for item queries with cost/price joins (mirrors the QBO/Xero+// item syncers')+type ItemRow = {+ id: string;+ readableId: string;+ readableIdWithRevision: string | null;+ name: string;+ description: string | null;+ companyId: string | null;+ type: "Part" | "Material" | "Tool" | "Service" | "Consumable" | "Fixture";+ unitOfMeasureCode: string | null;+ replenishmentSystem: "Buy" | "Make" | "Buy and Make";+ itemTrackingType: string;+ updatedAt: string | null;+ unitCost: number | null;+ unitSalePrice: number | null;+};++export class RilletItemSyncer extends RilletEntitySyncer<+ Accounting.Item,+ Rillet.Product,+ RilletWriteOmit+> {+ // Cached per instance — a drain reuses one syncer across its claimed+ // operations, so mappings, the sales-account default and the base+ // currency are each fetched at most once+ private accountCodesByIdPromise?: Promise<Map<string, string>>;+ private revenueAccountIdPromise?: Promise<string | null>;+ private baseCurrencyPromise?: Promise<string>;++ protected get pushOnlyEntityLabel(): string {+ return "Items";+ }++ // =================================================================+ // 1. ACCOUNT + CURRENCY RESOLUTION (cached per instance)+ // =================================================================++ private getAccountCodesById(): Promise<Map<string, string>> {+ if (!this.accountCodesByIdPromise) {+ this.accountCodesByIdPromise = loadRilletAccountCodesById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountCodesByIdPromise;+ }++ /**+ * The revenue account products post to: accountDefault.salesAccount+ * (items carry no per-item posting accounts).+ */+ private getRevenueAccountId(): Promise<string | null> {+ if (!this.revenueAccountIdPromise) {+ this.revenueAccountIdPromise = (async () => {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select("salesAccount")+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return defaults?.salesAccount ?? null;+ })();+ }+ return this.revenueAccountIdPromise;+ }++ private getBaseCurrency(): Promise<string> {+ if (!this.baseCurrencyPromise) {+ this.baseCurrencyPromise = loadCompanyBaseCurrency(+ this.database,+ this.companyId+ );+ }+ return this.baseCurrencyPromise;+ }++ // =================================================================+ // 2. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.Item | null> {+ const items = await this.fetchItemsByIds([id]);+ return items.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.Item>> {+ return this.fetchItemsByIds(ids);+ }++ private async fetchItemsByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.Item>> {+ if (ids.length === 0) return new Map();++ const rows = await this.database+ .selectFrom("item")+ .leftJoin("itemCost", "itemCost.itemId", "item.id")+ .leftJoin("itemUnitSalePrice", "itemUnitSalePrice.itemId", "item.id")+ .select([+ "item.id",+ "item.readableId",+ "item.readableIdWithRevision",+ "item.name",+ "item.description",+ "item.companyId",+ "item.type",+ "item.unitOfMeasureCode",+ "item.replenishmentSystem",+ "item.itemTrackingType",+ "item.updatedAt",+ "itemCost.unitCost",+ "itemUnitSalePrice.unitSalePrice"+ ])+ .where("item.id", "in", ids)+ .where("item.companyId", "=", this.companyId)+ .execute();++ const result = new Map<string, Accounting.Item>();+ for (const row of rows as ItemRow[]) {+ const isPurchased =+ row.replenishmentSystem === "Buy" ||+ row.replenishmentSystem === "Buy and Make";++ result.set(row.id, {+ id: row.id,+ code: row.readableIdWithRevision ?? row.readableId,+ name: row.name,+ description: row.description,+ companyId: row.companyId!,+ type: row.type,+ unitOfMeasureCode: row.unitOfMeasureCode,+ unitCost: Number(row.unitCost) || 0,+ unitSalePrice: Number(row.unitSalePrice) || 0,+ isPurchased,+ isSold: true, // Assume all items can be sold (Xero/QBO parity)+ isTrackedAsInventory: row.itemTrackingType !== "None",+ updatedAt: row.updatedAt ?? new Date().toISOString(),+ raw: row+ });+ }++ return result;+ }++ // =================================================================+ // 3. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Rillet.Product | null> {+ return this.rilletProvider.getProduct(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Rillet.Product>> {+ const result = new Map<string, Rillet.Product>();+ for (const id of ids) {+ const product = await this.rilletProvider.getProduct(id);+ if (product) result.set(product.id, product);+ }+ return result;+ }++ // =================================================================+ // 4. TRANSFORMATION (Carbon -> Rillet) with account resolution+ // =================================================================++ protected async mapToRemote(+ local: Accounting.Item+ ): Promise<RilletProductWrite> {+ const accountCodesById = await this.getAccountCodesById();+ const revenueAccountId = await this.getRevenueAccountId();+ const currency = await this.getBaseCurrency();++ return mapItemToRilletProduct({+ item: local,+ accountCodesById,+ revenueAccountId,+ currency+ });+ }++ // =================================================================+ // 5. UPSERT REMOTE (create with idempotency key, or PUT update)+ // =================================================================++ protected async upsertRemote(+ data: RilletProductWrite,+ localId: string+ ): Promise<string> {+ const existingRemoteId = await this.getRemoteId(localId);++ if (existingRemoteId) {+ const updated = await writeDroppingUnregisteredReferences(+ data,+ (payload) =>+ this.rilletProvider.updateProduct(existingRemoteId, payload)+ );+ return updated.id ?? existingRemoteId;+ }++ const created = await writeDroppingUnregisteredReferences(data, (payload) =>+ this.rilletProvider.createProduct(+ payload,+ buildRilletIdempotencyKey({+ companyId: this.companyId,+ operation: "product",+ localId+ })+ )+ );+ return created.id;+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/entities/journal-entry.ts b/packages/ee/src/accounting/providers/rillet/entities/journal-entry.tsnew file mode 100644index 0000000000..578db3cefa--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/journal-entry.ts@@ -0,0 +1,489 @@+import {+ buildDimensionValueMappingEntityId,+ loadJournalLineDimensions+} from "../../../core/dimension-mapping";+import {+ getPostingSyncSourceTypeSkipReason,+ JournalEntrySyncError,+ type PostingSyncSettings,+ parseJournalEntrySyncEntityId,+ roundCurrency,+ runJournalEntryPreflight,+ toDebitSignedAmount,+ toPostingDateString+} from "../../../core/posting";+import type { Accounting, ShouldSyncContext } from "../../../core/types";+import type {+ Rillet,+ RilletJournalEntryCreate,+ RilletWriteOmit+} from "../models";+import { buildRilletIdempotencyKey } from "../provider";+import {+ loadCompanyBaseCurrency,+ loadRilletAccountCodesById,+ RilletTransactionSyncer+} from "./shared";++/**+ * RilletJournalEntrySyncer — pushes Posted Carbon journals (`journal` ++ * `journalLine`) to Rillet as journal entries. PUSH-ONLY: pull methods+ * come from RilletTransactionSyncer's push-only rejections. Mirrors the+ * QBO JournalEntrySyncer's structure; what differs is the item shape+ * (unsigned 2-dp STRING amounts with an explicit DEBIT/CREDIT side), the+ * required currency (Carbon journals carry none — the company base+ * currency is resolved once per instance), and the optional subsidiary+ * scope (Rillet is multi-entity).+ *+ * Sign convention: Carbon `journalLine.amount` is signed (positive =+ * debit, negative = credit); Rillet items are UNSIGNED — `amount` =+ * abs(signed) as a 2-dp string and the side lives in `side` ("DEBIT" for+ * positive Carbon amounts, "CREDIT" otherwise). Reversals negate first,+ * flipping every side.+ *+ * Reversal contract (same as Xero/QBO): when a sync operation carries+ * `metadata.reversal: true`, the drain pushes entity id+ * `"<journal.id>:reversal"` (see getJournalEntrySyncEntityId). The syncer+ * loads the ORIGINAL journal, requires status `Reversed` plus an existing+ * original mapping, negates every signed amount, uses the name+ * `"Carbon reversal of <journalEntryId>"`, and stores the reversal's+ * mapping under the suffixed entity id — the original mapping is never+ * touched.+ *+ * Failure channel: pre-flight failures (UNMAPPED_ACCOUNTS,+ * CONTROL_ACCOUNT_LINE, PERIOD_LOCKED park, UNBALANCED_JOURNAL) throw+ * JournalEntrySyncError inside the mapping step; the+ * RilletTransactionSyncer push override converts them to+ * `SyncResult.error` carrying the structured JournalEntrySyncFailure+ * object for the drain (isJournalEntrySyncFailure → failOperation).+ *+ * Closed books: the pre-flight lock date comes ONLY from the manually+ * captured `settings.lockDate` (the Rillet API has no+ * org-lock-date/closed-period read) — the same manual-only source as QBO.+ * A stale date surfaces as Rillet's own rejection at push time.+ */++/**+ * The effective lock date (YYYY-MM-DD) for Rillet: the manual+ * `settings.lockDate` ONLY — Rillet's API cannot report a close date, so+ * the settings field is the sole pre-flight source (same approach as+ * getQboLockDate). Null when no date is stored.+ */+export function getRilletLockDate(+ settings: PostingSyncSettings+): string | null {+ return settings.lockDate ? settings.lockDate.slice(0, 10) : null;+}++/**+ * Map one Carbon journal to a Rillet journal-entry payload. Pure —+ * exported for tests (and for a future Rillet daily-consolidation path,+ * mirroring the Xero/QBO mapper contract).+ *+ * - Items: one Rillet item per journalLine — `amount` = abs(signed Carbon+ * amount) rounded to 2dp and rendered as a decimal STRING, `side` =+ * "DEBIT" when the signed amount is positive else "CREDIT" (reversals+ * negate first, flipping every side), `account_code` from the account+ * mapping (externalCode = Rillet account code), description = line+ * description falling back to the journal description.+ * - name: "Carbon <journalEntryId> <journal.id>" (or+ * "Carbon reversal of <journalEntryId>"), with+ * " | original date <postingDate>" appended when the period-lock redate+ * policy moved the push date.+ * - `currency` is the company base currency (Carbon journals are+ * base-currency); `subsidiary_id` only when configured.+ */+/**+ * Slot config + resolved Field-value ids for the Rillet journal mapper:+ * `slots` carry `field:<fieldId>` targets; `fieldValueIdsByValue`+ * resolves `<dimensionId>:<valueId>` → Rillet field_value uuid, and+ * `fieldIdByDimensionId` resolves the Carbon dimension → Rillet Field uuid.+ * Item refs are uuid pairs (`fields: [{ field_id, field_value_id }]`) — ids,+ * never names. EVERY dimension on a line is emitted; one whose Field or value+ * couldn't be provisioned (see resolveLineDimensions) is dropped from that+ * line's refs.+ */+export type RilletJournalDimensionArgs = {+ fieldIdByDimensionId: ReadonlyMap<string, string>;+ fieldValueIdsByValue: ReadonlyMap<string, string>;+};++export function mapJournalEntryToRilletJournalEntry(args: {+ journal: Accounting.JournalEntry;+ accountCodesById: ReadonlyMap<string, string>;+ currency: string;+ subsidiaryId: string | null;+ pushDate: string;+ redatedFromDate?: string;+ dimensions?: RilletJournalDimensionArgs;+}): RilletJournalEntryCreate {+ const { journal } = args;+ const sign = journal.reversal ? -1 : 1;++ const items: Rillet.JournalEntryItem[] = journal.lines.map((line) => {+ const accountCode = line.accountId+ ? args.accountCodesById.get(line.accountId)+ : undefined;++ if (!accountCode) {+ // runJournalEntryPreflight fails before mapping; this guards direct+ // callers (consolidation, tests) against unmapped input+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `No Rillet account code mapped for account ${+ line.accountId ?? "(none)"+ } on journal ${journal.journalEntryId}`,+ warning: true,+ metadata: {+ unmappedAccountIds: line.accountId ? [line.accountId] : []+ }+ });+ }++ const signedAmount = sign * line.amount;++ const fieldRefs: Rillet.ItemFieldRef[] = [];+ if (args.dimensions) {+ for (const dimension of line.dimensions ?? []) {+ const fieldId = args.dimensions.fieldIdByDimensionId.get(+ dimension.dimensionId+ );+ if (!fieldId) continue;+ const fieldValueId = args.dimensions.fieldValueIdsByValue.get(+ buildDimensionValueMappingEntityId(+ dimension.dimensionId,+ dimension.valueId+ )+ );+ if (!fieldValueId) continue; // Field/value not provisioned — drop this ref+ fieldRefs.push({ field_id: fieldId, field_value_id: fieldValueId });+ }+ }++ return {+ account_code: accountCode,+ amount: {+ amount: roundCurrency(Math.abs(signedAmount)).toFixed(2),+ currency: args.currency+ },+ side: signedAmount > 0 ? ("DEBIT" as const) : ("CREDIT" as const),+ description: line.description ?? journal.description ?? undefined,+ ...(fieldRefs.length > 0 ? { fields: fieldRefs } : {})+ };+ });++ // Human-first naming: the Carbon journal description (e.g. "Purchase+ // Receipt RE000001") when present, else the readable journal number.+ // Traceability lives in the mapping table (Sync Activity shows the+ // Rillet id) — Rillet journal entries accept no external_references, so+ // nothing is lost by keeping the name clean.+ const baseName =+ journal.description?.trim() || `Carbon ${journal.journalEntryId}`;+ let name = journal.reversal ? `Reversal of ${baseName}` : baseName;+ if (args.redatedFromDate) {+ name += ` | original date ${args.redatedFromDate}`;+ }++ return {+ name,+ date: args.pushDate,+ currency: args.currency,+ items,+ ...(args.subsidiaryId ? { subsidiary_id: args.subsidiaryId } : {})+ };+}++export class RilletJournalEntrySyncer extends RilletTransactionSyncer<+ Accounting.JournalEntry,+ Rillet.JournalEntry,+ RilletWriteOmit+> {+ // Per-instance caches — a drain reuses one syncer across its claimed+ // operations, so account codes, control accounts and the base currency+ // are each fetched at most once per drain (settings + dimension-value+ // lookup are cached by RilletTransactionSyncer)+ private accountCodesByIdPromise?: Promise<Map<string, string>>;+ private controlAccountIdsPromise?: Promise<Set<string>>;+ private baseCurrencyPromise?: Promise<string>;++ protected get pushOnlyEntityLabel(): string {+ return "Journal entries";+ }++ // =================================================================+ // 1. SETTINGS + PRE-FLIGHT INPUTS (cached per instance)+ // =================================================================++ /**+ * Carbon account.id → Rillet account code, from the account-mapping+ * rows (entityType "account"; mapping externalCode = Rillet account+ * code). Public (like getPostingSyncSettings) so a future Rillet+ * daily-consolidation path can run the same pre-flights on its+ * aggregate.+ */+ public getAccountCodesById(): Promise<Map<string, string>> {+ if (!this.accountCodesByIdPromise) {+ this.accountCodesByIdPromise = loadRilletAccountCodesById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountCodesByIdPromise;+ }++ /**+ * AR/AP control accounts (accountDefault.receivablesAccount /+ * payablesAccount) — journal lines on these never push. Public for+ * consolidation parity (same pre-flight inputs as individual pushes).+ */+ public getControlAccountIds(): Promise<Set<string>> {+ if (!this.controlAccountIdsPromise) {+ this.controlAccountIdsPromise = (async () => {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select(["receivablesAccount", "payablesAccount"])+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return new Set(+ [defaults?.receivablesAccount, defaults?.payablesAccount].filter(+ (id): id is string => typeof id === "string" && id.length > 0+ )+ );+ })();+ }+ return this.controlAccountIdsPromise;+ }++ /**+ * Company base currency — Carbon journals carry no currency of their+ * own, and Rillet journal payloads require one.+ */+ public getBaseCurrency(): Promise<string> {+ if (!this.baseCurrencyPromise) {+ this.baseCurrencyPromise = loadCompanyBaseCurrency(+ this.database,+ this.companyId+ );+ }+ return this.baseCurrencyPromise;+ }++ // =================================================================+ // 2. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(entityId: string): Promise<Accounting.JournalEntry | null> {+ const { journalId, reversal } = parseJournalEntrySyncEntityId(entityId);++ const journal = await this.database+ .selectFrom("journal")+ .select([+ "id",+ "companyId",+ "journalEntryId",+ "description",+ "postingDate",+ "status",+ "sourceType",+ "reversalOfId",+ "reversedById",+ "postedAt",+ "createdAt",+ "updatedAt"+ ])+ .where("id", "=", journalId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (!journal) return null;++ const lines = await this.database+ .selectFrom("journalLine")+ .leftJoin("account", "account.id", "journalLine.accountId")+ .select([+ "journalLine.id",+ "journalLine.accountId",+ "journalLine.amount",+ "journalLine.description",+ "account.class as accountClass"+ ])+ .where("journalId", "=", journalId)+ .where("companyId", "=", this.companyId)+ .orderBy("journalLineReference", "asc")+ .execute();++ const dimensionsByLine = await loadJournalLineDimensions(this.database, {+ companyId: this.companyId,+ journalLineIds: lines.map((line) => line.id)+ });++ return {+ id: journal.id,+ companyId: journal.companyId,+ journalEntryId: journal.journalEntryId,+ description: journal.description ?? null,+ postingDate: toPostingDateString(journal.postingDate),+ status: journal.status,+ sourceType: journal.sourceType ?? null,+ reversalOfId: journal.reversalOfId ?? null,+ reversedById: journal.reversedById ?? null,+ reversal,+ lines: lines.map((line) => {+ const dimensions = dimensionsByLine.get(line.id);+ return {+ id: line.id,+ accountId: line.accountId ?? null,+ // Carbon stores natural-balance-signed amounts; the engine expects+ // debit-signed (see toDebitSignedAmount)+ amount: toDebitSignedAmount(+ line.accountClass,+ Number(line.amount) || 0+ ),+ description: line.description ?? null,+ ...(dimensions ? { dimensions } : {})+ };+ }),+ updatedAt: journal.updatedAt ?? journal.postedAt ?? journal.createdAt+ };+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.JournalEntry>> {+ const result = new Map<string, Accounting.JournalEntry>();+ for (const id of ids) {+ const journal = await this.fetchLocal(id);+ if (journal) result.set(id, journal);+ }+ return result;+ }++ // =================================================================+ // 3. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Rillet.JournalEntry | null> {+ return this.rilletProvider.getJournalEntry(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Rillet.JournalEntry>> {+ const result = new Map<string, Rillet.JournalEntry>();+ for (const id of ids) {+ const journalEntry = await this.rilletProvider.getJournalEntry(id);+ if (journalEntry) result.set(journalEntry.id, journalEntry);+ }+ return result;+ }++ // =================================================================+ // 4. SHOULD SYNC (skip-reason gate)+ // =================================================================++ protected async shouldSync(+ context: ShouldSyncContext<Accounting.JournalEntry, Rillet.JournalEntry>+ ): Promise<boolean | string> {+ if (context.direction === "pull") {+ return "Journal entries are push-only; pulling journal entries from Rillet is not supported";+ }++ const local = context.localEntity;+ if (!local) return "Journal could not be loaded";++ // Idempotency: a mapped journal push is never repeated+ if (!context.isFirstSync) {+ return "Journal already pushed to Rillet (mapping exists)";+ }++ if (local.reversal) {+ if (local.status !== "Reversed") {+ return `Reversal push requires a Reversed journal (current status: ${local.status})`;+ }+ // Reversal-by-reference: only reverse what was actually pushed+ const originalRemoteId = await this.getRemoteId(local.id);+ if (!originalRemoteId) {+ return `Original journal ${local.journalEntryId} was never pushed to Rillet; nothing to reverse`;+ }+ } else if (local.status !== "Posted") {+ return `Journal must be Posted before syncing (current status: ${local.status})`;+ }++ const settings = await this.getPostingSyncSettings();+ const sourceTypeSkipReason = getPostingSyncSourceTypeSkipReason(+ local.sourceType,+ settings,+ {+ inventoryAdjustmentEntitySyncEnabled:+ this.provider.getSyncConfig("inventoryAdjustment")?.enabled ?? false+ }+ );+ if (sourceTypeSkipReason) return sourceTypeSkipReason;++ return true;+ }++ // =================================================================+ // 5. TRANSFORMATION (Carbon -> Rillet) with pre-flight+ // =================================================================++ protected async mapToRemote(+ local: Accounting.JournalEntry+ ): Promise<RilletJournalEntryCreate> {+ const settings = await this.getPostingSyncSettings();+ const accountCodesById = await this.getAccountCodesById();+ const controlAccountIds = await this.getControlAccountIds();+ const lockDate = getRilletLockDate(settings);++ // Send ALL dimensions on the journal: auto-provision every Rillet Field ++ // value the lines reference (Rillet has no field cap) and get back the two+ // lookups the mapper needs. Runs BEFORE pre-flight so freshly provisioned+ // values never park as unmapped.+ const { fieldIdByDimensionId, fieldValueIdsByValue } =+ await this.resolveLineDimensions(local.lines);++ const preflight = runJournalEntryPreflight({+ journal: local,+ accountCodesById,+ controlAccountIds,+ lockDate,+ settings,+ dimensionValueMappings: fieldValueIdsByValue+ });++ if (preflight.failure) {+ throw new JournalEntrySyncError(preflight.failure);+ }++ return mapJournalEntryToRilletJournalEntry({+ journal: local,+ accountCodesById,+ currency: await this.getBaseCurrency(),+ subsidiaryId: this.rilletProvider.subsidiaryId,+ pushDate: preflight.pushDate,+ redatedFromDate: preflight.redatedFromDate,+ dimensions: { fieldIdByDimensionId, fieldValueIdsByValue }+ });+ }++ // =================================================================+ // 6. UPSERT REMOTE (create-only; RilletTransactionSyncer hard-skips+ // already-mapped ids, so no update path exists)+ // =================================================================++ protected async upsertRemote(+ data: RilletJournalEntryCreate,+ localId: string+ ): Promise<string> {+ const created = await this.rilletProvider.createJournalEntry(+ data,+ buildRilletIdempotencyKey({+ companyId: this.companyId,+ operation: "journal-entry",+ localId+ })+ );+ return created.id;+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/entities/payment.ts b/packages/ee/src/accounting/providers/rillet/entities/payment.tsnew file mode 100644index 0000000000..2fbc3c4eaf--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/payment.ts@@ -0,0 +1,444 @@+import type { NormalizedPayment } from "../../../core/payment-application";+import {+ type PaymentPushContext,+ PaymentSyncerBase+} from "../../../core/payment-syncer";+import { JournalEntrySyncError } from "../../../core/posting";+import type { ShouldSyncContext } from "../../../core/types";+import type { Rillet, RilletLocalPayment } from "../models";+import { buildRilletIdempotencyKey, type RilletProvider } from "../provider";+import {+ loadCompanyBaseCurrency,+ loadRilletAccountCodesById,+ RILLET_CARBON_REFERENCE_TYPE,+ toRilletMoney+} from "./shared";++// Re-exported for the payment tests (moved to the family-agnostic core, where+// the runtime document-status boundary now lives — post-payment owns status).+export { getSettledInvoiceStatus } from "../../../core/payment-application";++/**+ * RilletPaymentSyncer — the AR payment syncer for Rillet, on the shared+ * `PaymentSyncerBase`. Rillet invoice payments (recorded against pushed AR_ONLY+ * invoices) settle Carbon sales invoices; the base writes a Draft `payment` ++ * `invoiceSettlement` and then invokes the native `post-payment` edge function+ * (GL journal + Posted/Voided status). Pushing is a rejection stub.+ *+ * Entity-id contract: the sync operation's entityId is a COMPOSITE. AR keeps+ * the prefix-less `"<invoiceRemoteId>:<paymentRemoteId>"` form (back-compat with+ * stored AR mappings); AP uses a `"bill:<billRemoteId>:<billPaymentRemoteId>"`+ * form. Rillet payments are only addressable through their document+ * (GET /invoices/{id}/payments, GET /bills/{id}/payments), and the drain hands+ * syncers nothing but entity ids, so the composite makes the syncer+ * self-sufficient. Mappings under entityType "payment" are stored against the+ * composite id. The `bill:` prefix is also the family discriminator the syncer+ * branches on (and the shape later QBO/Xero payment syncers mirror).+ *+ * v1 simplification (documented): exchange rates are recorded as 1 (Rillet+ * payments settle same-currency AR_ONLY invoices / AP bills).+ */++const SYNC_ID_SEPARATOR = ":";+/** AP composite-id family discriminator prefix. AR is prefix-less. */+const BILL_PREFIX = "bill:";++/** Composite sync entity id for one Rillet invoice payment (AR, prefix-less). */+export function getRilletPaymentSyncEntityId(+ invoiceRemoteId: string,+ paymentRemoteId: string+): string {+ return `${invoiceRemoteId}${SYNC_ID_SEPARATOR}${paymentRemoteId}`;+}++/** Composite sync entity id for one Rillet bill payment (AP, `bill:` prefix). */+export function getRilletBillPaymentSyncEntityId(+ billRemoteId: string,+ billPaymentRemoteId: string+): string {+ return `${BILL_PREFIX}${billRemoteId}${SYNC_ID_SEPARATOR}${billPaymentRemoteId}`;+}++/**+ * Split a composite payment entity id into its family, document remote id, and+ * payment remote id. A `bill:` prefix marks the AP form; anything else is the+ * back-compat AR form. Throws on a malformed id.+ */+export function parseRilletPaymentSyncEntityId(entityId: string): {+ family: "ar" | "ap";+ documentRemoteId: string;+ paymentRemoteId: string;+} {+ const isBill = entityId.startsWith(BILL_PREFIX);+ const remainder = isBill ? entityId.slice(BILL_PREFIX.length) : entityId;++ const separatorIndex = remainder.indexOf(SYNC_ID_SEPARATOR);+ if (separatorIndex <= 0 || separatorIndex === remainder.length - 1) {+ throw new Error(+ `Invalid Rillet payment sync entity id "${entityId}" — expected "<invoiceRemoteId>:<paymentRemoteId>" or "bill:<billRemoteId>:<billPaymentRemoteId>"`+ );+ }+ return {+ family: isBill ? "ap" : "ar",+ documentRemoteId: remainder.slice(0, separatorIndex),+ paymentRemoteId: remainder.slice(separatorIndex + 1)+ };+}++/** A payment object carrying the shared amount/currency wire shape. */+type RilletPaymentAmountLike = Rillet.InvoicePayment | Rillet.BillPayment;++/**+ * Numeric amount from either wire shape: the list endpoint's+ * `{ amount: { amount: "100.00", currency } }` or the webhook's flat+ * `amount` + `currency`. Shared by AR invoice payments and AP bill payments.+ */+export function getRilletPaymentAmount(+ remote: RilletPaymentAmountLike+): number {+ const raw = remote.amount;+ if (raw && typeof raw === "object") return Number(raw.amount) || 0;+ if (typeof raw === "string" || typeof raw === "number") {+ return Number(raw) || 0;+ }+ return 0;+}++/** Currency from either wire shape (see getRilletPaymentAmount). */+export function getRilletPaymentCurrency(+ remote: RilletPaymentAmountLike+): string | null {+ if (remote.amount && typeof remote.amount === "object") {+ return remote.amount.currency ?? null;+ }+ return remote.currency ?? null;+}++/**+ * Normalize a Rillet invoice payment onto the local shape. Pure — exported for+ * tests. The invoice id / composite id are completed from the operation's+ * entity id (the list-endpoint invoice_id is carried through when present).+ */+export function mapRilletPaymentToLocal(+ remote: Rillet.InvoicePayment+): Partial<RilletLocalPayment> {+ const date = (+ remote.date ??+ remote.payment_date ??+ remote.updated_at ??+ remote.created_at ??+ new Date().toISOString()+ ).slice(0, 10);++ return {+ paymentRemoteId: remote.id,+ ...(remote.invoice_id ? { invoiceRemoteId: remote.invoice_id } : {}),+ amount: getRilletPaymentAmount(remote),+ currencyCode: getRilletPaymentCurrency(remote),+ date,+ status: remote.status,+ updatedAt: remote.updated_at ?? new Date().toISOString()+ };+}++/** Either Rillet payment wire shape the syncer handles (AR invoice / AP bill). */+type RilletPayment = Rillet.InvoicePayment | Rillet.BillPayment;++export class RilletPaymentSyncer extends PaymentSyncerBase<RilletPayment> {+ private get rilletProvider(): RilletProvider {+ return this.provider as RilletProvider;+ }++ /** Rillet accepts Carbon-born payments back out (Phase G). */+ protected supportsPaymentPush = true;++ /** company.baseCurrencyCode, read once per syncer instance (FX gate). */+ private baseCurrencyPromise?: Promise<string>;++ private getBaseCurrency(): Promise<string> {+ if (!this.baseCurrencyPromise) {+ this.baseCurrencyPromise = loadCompanyBaseCurrency(+ this.database,+ this.companyId+ );+ }+ return this.baseCurrencyPromise;+ }++ /** Carbon account.id → Rillet account code, read once per syncer instance. */+ private accountCodesByIdPromise?: Promise<Map<string, string>>;++ private getAccountCodesById(): Promise<Map<string, string>> {+ if (!this.accountCodesByIdPromise) {+ this.accountCodesByIdPromise = loadRilletAccountCodesById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountCodesByIdPromise;+ }++ // =================================================================+ // 1. REMOTE FETCH — composite id → list the document's payments+ // =================================================================++ async fetchRemote(entityId: string): Promise<RilletPayment | null> {+ const { family, documentRemoteId, paymentRemoteId } =+ parseRilletPaymentSyncEntityId(entityId);++ const payments =+ family === "ap"+ ? await this.rilletProvider.listBillPayments(documentRemoteId)+ : await this.rilletProvider.listInvoicePayments(documentRemoteId);+ return payments.find((payment) => payment.id === paymentRemoteId) ?? null;+ }++ /**+ * Keyed by the COMPOSITE entity id (the base pull workflow uses the map keys+ * as remote ids, and the drain matches results back to operations by+ * entityId). One listing per distinct document per batch (AR invoices and AP+ * bills share the cache key space via the composite prefix).+ */+ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, RilletPayment>> {+ const result = new Map<string, RilletPayment>();+ const paymentsByDocument = new Map<string, RilletPayment[]>();++ for (const entityId of ids) {+ const { family, documentRemoteId, paymentRemoteId } =+ parseRilletPaymentSyncEntityId(entityId);++ // The family-qualified document id is the cache key, so an AR invoice and+ // an AP bill that happen to share a remote id never collide.+ const cacheKey =+ (family === "ap" ? "bill:" : "invoice:") + documentRemoteId;+ let payments = paymentsByDocument.get(cacheKey);+ if (!payments) {+ payments =+ family === "ap"+ ? await this.rilletProvider.listBillPayments(documentRemoteId)+ : await this.rilletProvider.listInvoicePayments(documentRemoteId);+ paymentsByDocument.set(cacheKey, payments);+ }++ const payment = payments.find((p) => p.id === paymentRemoteId);+ if (payment) result.set(entityId, payment);+ }++ return result;+ }++ // =================================================================+ // 2. TIMESTAMP + SHOULD SYNC+ // =================================================================++ protected getRemoteUpdatedAt(remote: RilletPayment): Date | null {+ if (!remote.updated_at) return null;+ const parsed = new Date(remote.updated_at);+ return Number.isNaN(parsed.getTime()) ? null : parsed;+ }++ protected async shouldSync(+ context: ShouldSyncContext<RilletPayment, RilletPayment>+ ): Promise<boolean | string> {+ // Push is gated entirely in PaymentSyncerBase.pushToAccounting (origin,+ // documents-mode, single-settlement, FX) — shouldSync only governs the pull.+ const { family, documentRemoteId } = parseRilletPaymentSyncEntityId(+ context.entityId+ );++ // Documents-mode gate: inbound payment sync-back is allowed only when the+ // payment's AR/AP family is in `documents` mode (Carbon owns the settled+ // documents). A `journals`/`none` family does not pull payments — a benign+ // skip, like the ownership skip below. An unconfigured integration defaults+ // to documents, preserving today's Rillet AR behavior.+ if (!(await this.isPaymentSyncbackEnabled(family))) {+ return `payment sync-back is disabled: the ${family} family is not in documents mode`;+ }++ // Ownership gate: Rillet feeds/webhooks are organization-level and cannot be+ // filtered by subsidiary, so with several Carbon instances writing to one+ // Rillet org (one subsidiary each), every instance receives every payment+ // event. The pushed document's mapping is the ownership record: no local+ // mapping means the invoice/bill belongs to another instance's subsidiary or+ // was created directly in Rillet — either way there is no Carbon document to+ // settle here, and that is a benign skip, not a failure.+ if (family === "ap") {+ const purchaseInvoiceId = await this.mappingService.getEntityId(+ this.provider.id,+ documentRemoteId,+ "bill"+ );+ if (!purchaseInvoiceId) {+ return `Rillet bill ${documentRemoteId} has no Carbon mapping — the payment belongs to another Carbon instance's subsidiary or to a bill created directly in Rillet`;+ }+ } else {+ const salesInvoiceId = await this.mappingService.getEntityId(+ this.provider.id,+ documentRemoteId,+ "invoice"+ );+ if (!salesInvoiceId) {+ return `Rillet invoice ${documentRemoteId} has no Carbon mapping — the payment belongs to another Carbon instance's subsidiary or to an invoice created directly in Rillet`;+ }+ }++ // A payment first seen as FAILED was never recorded — nothing to void.+ if (context.remoteEntity?.status === "FAILED" && context.isFirstSync) {+ return "Failed Rillet payment was never recorded in Carbon — nothing to do";+ }++ // FX gate: mapToNormalized hardcodes exchangeRate 1 (a documented v1+ // same-currency simplification), which would silently mis-state a+ // cross-currency settlement. Park (skip with reason) any payment whose+ // currency differs from the company base currency; a same-currency or+ // currency-less payment proceeds unchanged.+ const paymentCurrency = context.remoteEntity+ ? getRilletPaymentCurrency(context.remoteEntity)+ : null;+ if (paymentCurrency) {+ const baseCurrency = await this.getBaseCurrency();+ if (paymentCurrency !== baseCurrency) {+ return `FX payment (${paymentCurrency} ≠ base ${baseCurrency}) — not supported v1`;+ }+ }++ return true;+ }++ // =================================================================+ // 3. NORMALIZATION (Rillet -> family-agnostic NormalizedPayment)+ // =================================================================++ protected mapToNormalized(+ remote: RilletPayment,+ entityId: string+ ): NormalizedPayment {+ const { family, documentRemoteId, paymentRemoteId } =+ parseRilletPaymentSyncEntityId(entityId);++ if (family === "ap") {+ const bill = remote as Rillet.BillPayment;+ const paidDate = (+ bill.date ??+ bill.payment_date ??+ bill.updated_at ??+ bill.created_at ??+ new Date().toISOString()+ ).slice(0, 10);++ return {+ family: "ap",+ documentRemoteId,+ paymentRemoteId,+ amount: getRilletPaymentAmount(bill),+ currencyCode: getRilletPaymentCurrency(bill),+ exchangeRate: 1,+ paidDate,+ // The Rillet bill-payment id is the human/provider reference.+ reference: paymentRemoteId,+ status: bill.status === "FAILED" ? "failed" : "settled"+ };+ }++ const local = mapRilletPaymentToLocal(remote as Rillet.InvoicePayment);++ return {+ family: "ar",+ documentRemoteId,+ paymentRemoteId,+ amount: local.amount ?? 0,+ currencyCode: local.currencyCode ?? null,+ exchangeRate: 1,+ paidDate: local.date ?? new Date().toISOString().slice(0, 10),+ reference: paymentRemoteId,+ status:+ (remote as Rillet.InvoicePayment).status === "FAILED"+ ? "failed"+ : "settled"+ };+ }++ // =================================================================+ // 4. PUSH (Phase G — Carbon-born payment → Rillet payment document)+ // =================================================================++ /**+ * Create one Rillet payment for the settled document. Resolves the document's+ * Rillet id and the bank account's Rillet code from the mappings. A missing+ * document mapping → UNSYNCED_DOCUMENT Warning (the bill/invoice must sync+ * first — a dependency-ordering issue, NOT a missing account); a missing bank+ * account code → UNMAPPED_ACCOUNTS Warning (map it on the integration settings+ * page). Otherwise POSTs the payment and returns its id + the composite mapping id.+ */+ protected async pushRemotePayment(+ context: PaymentPushContext+ ): Promise<{ remoteId: string; compositeEntityId: string }> {+ const documentRemoteId = await this.mappingService.getExternalId(+ context.family === "ar" ? "invoice" : "bill",+ context.targetDocumentId,+ this.provider.id+ );+ if (!documentRemoteId) {+ throw new JournalEntrySyncError({+ errorCode: "UNSYNCED_DOCUMENT",+ message: `The settled ${+ context.family === "ar" ? "invoice" : "bill"+ } has not synced to Rillet yet — sync it, then retry the payment`,+ warning: true,+ metadata: { targetDocumentId: context.targetDocumentId }+ });+ }++ const accountCode = (await this.getAccountCodesById()).get(+ context.bankAccountId+ );+ if (!accountCode) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `The payment's bank/cash account is not mapped to a Rillet account — map it on the integration settings page, then retry`,+ warning: true,+ metadata: { bankAccountId: context.bankAccountId }+ });+ }++ const payload = {+ amount: toRilletMoney(context.amount, context.currencyCode),+ date: context.paidDate,+ account_code: accountCode,+ external_references: [+ { type: RILLET_CARBON_REFERENCE_TYPE, id: context.carbonPaymentId }+ ]+ };++ const idempotencyKey = buildRilletIdempotencyKey({+ companyId: this.companyId,+ operation:+ context.family === "ar"+ ? "create invoice payment"+ : "create bill payment",+ localId: `${context.carbonPaymentId}:${context.targetDocumentId}`+ });++ const created =+ context.family === "ar"+ ? await this.rilletProvider.createInvoicePayment(+ documentRemoteId,+ payload,+ idempotencyKey+ )+ : await this.rilletProvider.createBillPayment(+ documentRemoteId,+ payload,+ idempotencyKey+ );++ const compositeEntityId =+ context.family === "ar"+ ? getRilletPaymentSyncEntityId(documentRemoteId, created.id)+ : getRilletBillPaymentSyncEntityId(documentRemoteId, created.id);++ return { remoteId: created.id, compositeEntityId };+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/entities/shared.ts b/packages/ee/src/accounting/providers/rillet/entities/shared.tsnew file mode 100644index 0000000000..7cf51a0e71--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/shared.ts@@ -0,0 +1,785 @@+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";+import { getAccountMappings } from "../../../core/account-mapping";+import {+ buildDimensionFieldLookup,+ buildDimensionValueMappingEntityId,+ buildDimensionValueMappingLookup,+ getDimensionMappings,+ getDimensionValueMappings,+ loadDimensionNames,+ resolveDimensionValueLabels,+ upsertDimensionMapping,+ upsertDimensionValueMapping+} from "../../../core/dimension-mapping";+import {+ JournalEntrySyncError,+ type JournalLineDimensionRef,+ type PostingSyncSettings,+ resolvePostingSyncSettings,+ roundCurrency+} from "../../../core/posting";+import {+ type Accounting,+ BaseEntitySyncer,+ type BatchSyncResult,+ type SyncResult+} from "../../../core/types";+import { withTriggersDisabled } from "../../../core/utils";+import { parseRilletDate, type Rillet } from "../models";+import {+ buildRilletIdempotencyKey,+ isRilletUnknownExternalReferenceTypeError,+ type RilletProvider+} from "../provider";++/**+ * Shared plumbing for the Rillet entity syncers:+ *+ * - `RilletEntitySyncer` — a thin BaseEntitySyncer specialization for the+ * push-only master-data syncers (customer, vendor, item): preserves+ * structured JournalEntrySyncFailure envelopes on `SyncResult.error`+ * (the same pushToAccounting-override pattern the Xero/QBO syncers+ * established) and centralizes the push-only pull rejections.+ * - `RilletTransactionSyncer` — the create-only variant for documents+ * (invoice, bill, journal entry): pushed documents are immutable in v1,+ * so an existing mapping is a hard skip (the QBO journal-syncer+ * contract), replacing the master-data lastSyncedAt fast bailout.+ * - Pure mapping helpers (money formatting, the all-or-nothing address+ * group, payment-terms parsing, the carbon external reference) exported+ * for tests.+ */++/** external_references entries Carbon writes always use this type. */+export const RILLET_CARBON_REFERENCE_TYPE = "carbon";++/**+ * Origin tag for multi-instance deployments: several self-hosted Carbon+ * instances can write to one Rillet organization (one subsidiary each),+ * and Carbon entity ids are only unique within one database. The company+ * reference makes every pushed document's origin auditable from Rillet.+ */+export const RILLET_CARBON_COMPANY_REFERENCE_TYPE = "carbon-company";++export function carbonExternalReference(id: string): Rillet.ExternalReference {+ return { type: RILLET_CARBON_REFERENCE_TYPE, id };+}++export function carbonCompanyExternalReference(+ companyId: string+): Rillet.ExternalReference {+ return { type: RILLET_CARBON_COMPANY_REFERENCE_TYPE, id: companyId };+}++/**+ * Rillet's built-in "custom source" external-reference type. When a Rillet org+ * has Revenue Recognition enabled, rev-rec validation rejects an AR invoice+ * unless the invoice + items carry a reference from a KNOWN integration —+ * billing/rev-rec partners (TABS, Maxio, …) or the generic CUSTOMER_HISTORICAL /+ * CUSTOMER_CUSTOM. Carbon's `"carbon"` type is not on that list. Carbon IS a+ * custom source, so it tags AR invoices with CUSTOMER_CUSTOM (alongside the+ * `"carbon"` audit refs) so they land whether or not the org runs rev-rec —+ * without depending on Rillet-side configuration.+ */+export const RILLET_CUSTOMER_CUSTOM_REFERENCE_TYPE = "CUSTOMER_CUSTOM";++export function customerCustomExternalReference(+ id: string,+ url: string+): Rillet.ExternalReference {+ // Rillet REQUIRES a url on CUSTOMER_CUSTOM references ("The URL is+ // required for external reference for Customer_Custom", verified on the+ // sandbox 2026-08-12) — it is the link back into the source system.+ return { type: RILLET_CUSTOMER_CUSTOM_REFERENCE_TYPE, id, url };+}++/**+ * Run a Rillet write, and when the org hasn't registered Carbon's+ * external-reference type slugs (dashboard-only setup: Rillet Settings →+ * External References), retry once WITHOUT the optional+ * external_references so the push still lands — the reference is audit+ * metadata, not required data. Only for payloads where references are+ * optional; AR_ONLY invoices (references required) surface a structured+ * Warning instead.+ */+export async function writeDroppingUnregisteredReferences<+ TPayload extends { external_references?: unknown },+ TResult+>(+ payload: TPayload,+ write: (payload: TPayload) => Promise<TResult>+): Promise<TResult> {+ try {+ return await write(payload);+ } catch (error) {+ if (+ !isRilletUnknownExternalReferenceTypeError(error) ||+ payload.external_references === undefined+ ) {+ throw error;+ }+ console.warn(+ `[Rillet] external-reference type slugs are not registered for this organization (Rillet Settings → External References: add "${RILLET_CARBON_REFERENCE_TYPE}" and "${RILLET_CARBON_COMPANY_REFERENCE_TYPE}"); retrying without references`+ );+ const { external_references: _dropped, ...stripped } = payload;+ return await write(stripped as TPayload);+ }+}++/** Format a number as Rillet money — a 2-dp decimal STRING plus currency. */+export function toRilletMoney(+ amount: number,+ currency: string+): Rillet.MonetaryAmount {+ return { amount: roundCurrency(amount).toFixed(2), currency };+}++/**+ * Rillet addresses are an all-or-nothing group (line1/city/state/zip_code/+ * country must all be present) — the first Carbon address maps only when+ * complete; a partial address is omitted entirely.+ */+export function mapContactAddressToRilletAddress(+ local: Accounting.Contact+): Rillet.Address | undefined {+ const address = local.addresses[0];+ if (!address) return undefined;++ const { line1, line2, city, region, postalCode, country } = address;+ if (!line1 || !city || !region || !postalCode || !country) return undefined;++ return {+ line1,+ ...(line2 ? { line2 } : {}),+ city,+ state: region,+ zip_code: postalCode,+ country+ };+}++/**+ * Carbon contact paymentTerms is free text; Rillet wants integer days.+ * Only a bare non-negative integer maps (optionally capped — vendors are+ * limited to 0-180 days); anything else is omitted rather than guessed.+ */+export function mapPaymentTermsToRilletDays(+ paymentTerms: string | null | undefined,+ options?: { max?: number }+): number | undefined {+ if (!paymentTerms) return undefined;+ const trimmed = paymentTerms.trim();+ if (!/^\d+$/.test(trimmed)) return undefined;+ const days = Number(trimmed);+ if (options?.max !== undefined && days > options.max) return undefined;+ return days;+}++/**+ * Carbon account.id → Rillet account code, from the account-mapping rows+ * (entityType "account"). Rillet journal/bill items address accounts by+ * CODE, so the mapping's stored externalCode is the resolution target —+ * the same contract as the Xero journal syncer's getAccountCodesById;+ * mappings without a stored code count as unmapped.+ */+export async function loadRilletAccountCodesById(+ database: Kysely<KyselyDatabase>,+ args: { companyId: string; integration: string }+): Promise<Map<string, string>> {+ const mappings = await getAccountMappings(database, {+ companyId: args.companyId,+ integration: args.integration+ });++ if (mappings.error) {+ throw new Error(`Failed to load account mappings: ${mappings.error}`);+ }++ const codesById = new Map<string, string>();+ for (const mapping of mappings.data ?? []) {+ if (mapping.externalCode) {+ codesById.set(mapping.accountId, mapping.externalCode);+ }+ }+ return codesById;+}++/**+ * company.baseCurrencyCode — Rillet payloads always carry an explicit+ * ISO-4217 currency, and Carbon journals/products have none of their own.+ */+export async function loadCompanyBaseCurrency(+ database: Kysely<KyselyDatabase>,+ companyId: string+): Promise<string> {+ const company = await database+ .selectFrom("company")+ .select("baseCurrencyCode")+ .where("id", "=", companyId)+ .executeTakeFirst();++ return company?.baseCurrencyCode ?? "USD";+}++/** Every Rillet read shape carries an optional updated_at timestamp. */+export type RilletTimestamped = { updated_at?: string };++/**+ * Base class for the push-only Rillet master-data syncers (customer,+ * vendor, item).+ *+ * Reimplements the push workflow with the SAME behavior as+ * BaseEntitySyncer.pushToAccounting (mapping check, shouldSync gate,+ * lastSyncedAt fast bailout, map → upsert → link) so that a thrown+ * JournalEntrySyncError reaches the caller as the structured failure+ * object on `SyncResult.error` — the base catch flattens every throw to a+ * string, which would lose errorCode/warning/metadata. Also centralizes+ * the push-only pull rejections (v1 forces push for these entities).+ */+export abstract class RilletEntitySyncer<+ TLocal,+ TRemote extends RilletTimestamped,+ TOmit extends string | symbol | number+> extends BaseEntitySyncer<TLocal, TRemote, TOmit> {+ protected get rilletProvider(): RilletProvider {+ return this.provider as RilletProvider;+ }++ /** Plural label used in push-only rejection messages, e.g. "Customers". */+ protected abstract get pushOnlyEntityLabel(): string;++ protected getRemoteUpdatedAt(remote: TRemote): Date | null {+ return parseRilletDate(remote.updated_at);+ }++ /**+ * Rillet has no bulk upsert endpoints — batch writes are sequential+ * single upserts (each with its own idempotency key).+ */+ protected async upsertRemoteBatch(+ data: Array<{ localId: string; payload: Omit<TRemote, TOmit> }>+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>();+ for (const { localId, payload } of data) {+ result.set(localId, await this.upsertRemote(payload, localId));+ }+ return result;+ }++ /**+ * Base push workflow, verbatim in behavior, plus: a thrown+ * JournalEntrySyncError returns its structured failure on+ * `SyncResult.error` instead of a flattened string.+ */+ async pushToAccounting(entityId: string): Promise<SyncResult> {+ if (!this.config.enabled) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error: "Sync disabled in config"+ };+ }++ try {+ // 1. Check if already linked+ const existingMapping = await this.mappingService.getByEntity(+ this.entityType,+ entityId,+ this.provider.id+ );++ // 2. Fetch local entity+ const localEntity = await this.fetchLocal(entityId);+ if (!localEntity) {+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: `Entity ${entityId} not found in Carbon`+ };+ }++ // 3. Optional business-logic gate+ if (this.shouldSync) {+ const shouldSyncResult = await this.shouldSync({+ direction: "push",+ localEntity,+ isFirstSync: !existingMapping,+ entityId+ });++ if (shouldSyncResult !== true) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error:+ typeof shouldSyncResult === "string"+ ? shouldSyncResult+ : "Entity not eligible for sync"+ };+ }+ }++ const localUpdatedAt = new Date((localEntity as any).updatedAt);++ // 4. Fast bailout: already synced and local unchanged+ if (existingMapping?.lastSyncedAt) {+ if (localUpdatedAt <= new Date(existingMapping.lastSyncedAt)) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ remoteId: existingMapping.externalId,+ error: "Already synced - local unchanged"+ };+ }+ }++ // 5. Map and push+ const remotePayload = await this.mapToRemote(localEntity);+ const remoteId = await this.upsertRemote(remotePayload, entityId);++ // 6. Update mapping+ await withTriggersDisabled(this.database, async (tx) => {+ await this.linkEntities(tx, entityId, remoteId);+ });++ console.log("[SyncLog]", {+ direction: "PUSH",+ entity: this.entityType,+ localId: entityId,+ remoteId,+ status: "success"+ });++ return {+ status: "success",+ action: existingMapping ? "updated" : "created",+ localId: entityId,+ remoteId+ };+ } catch (err) {+ if (err instanceof JournalEntrySyncError) {+ console.error(`[${this.constructor.name}] structured push failure`, {+ entityId,+ ...err.failure+ });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err.failure+ };+ }++ console.error(`[${this.constructor.name}] push failed`, {+ entityId,+ err+ });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err instanceof Error ? err.message : String(err)+ };+ }+ }++ /**+ * Batch push composes the overridden single push so the structured+ * failures survive the drain's batch path too (the base batch loop+ * flattens errors to strings). Operations arrive in claim-sized batches,+ * so a sequential loop costs nothing — and Rillet has no bulk endpoint+ * to lose.+ */+ async pushBatchToAccounting(entityIds: string[]): Promise<BatchSyncResult> {+ const results: SyncResult[] = [];++ for (const entityId of entityIds) {+ results.push(await this.pushToAccounting(entityId));+ }++ return {+ results,+ successCount: results.filter((r) => r.status === "success").length,+ errorCount: results.filter((r) => r.status === "error").length,+ skippedCount: results.filter((r) => r.status === "skipped").length+ };+ }++ // =================================================================+ // PULL WORKFLOW - Not supported (v1 forces push for these entities)+ // =================================================================++ protected async mapToLocal(_remote: TRemote): Promise<Partial<TLocal>> {+ throw new Error(+ `${this.pushOnlyEntityLabel} are push-only for Rillet. Cannot map from Rillet to Carbon.`+ );+ }++ protected async upsertLocal(+ _tx: KyselyTx,+ _data: Partial<TLocal>,+ _remoteId: string+ ): Promise<string> {+ throw new Error(+ `${this.pushOnlyEntityLabel} are push-only for Rillet. Cannot upsert locally from Rillet.`+ );+ }++ async pullFromAccounting(remoteId: string): Promise<SyncResult> {+ return {+ status: "error",+ action: "none",+ remoteId,+ error: `${this.pushOnlyEntityLabel} are push-only for Rillet: pulling from Rillet into Carbon is not supported`+ };+ }++ async pullBatchFromAccounting(remoteIds: string[]): Promise<BatchSyncResult> {+ const results: SyncResult[] = remoteIds.map((remoteId) => ({+ status: "error",+ action: "none",+ remoteId,+ error: `${this.pushOnlyEntityLabel} are push-only for Rillet: pulling from Rillet into Carbon is not supported`+ }));++ return {+ results,+ successCount: 0,+ errorCount: results.length,+ skippedCount: 0+ };+ }+}++/**+ * Base class for the create-only Rillet document syncers (invoice, bill,+ * journal entry): pushed documents are immutable in v1, so the+ * master-data lastSyncedAt fast bailout is replaced with a HARD+ * skip-when-mapped — an existing mapping means the push already happened+ * (the QBO journal-syncer contract). Everything else (structured+ * failures, sequential batches, push-only pulls) comes from+ * RilletEntitySyncer.+ */+export abstract class RilletTransactionSyncer<+ TLocal,+ TRemote extends RilletTimestamped,+ TOmit extends string | symbol | number+> extends RilletEntitySyncer<TLocal, TRemote, TOmit> {+ // Per-instance caches — a drain reuses one syncer across its claimed+ // operations, so the posting-sync settings and the dimension-value+ // lookup are each fetched at most once per drain+ private postingSyncSettingsPromise?: Promise<PostingSyncSettings>;+ private dimensionValueMappingsPromise?: Promise<Map<string, string>>;+ private dimensionFieldMappingsPromise?: Promise<Map<string, string>>;++ /**+ * Per-company posting-sync settings from+ * `companyIntegration.metadata.settings.postingSync`. Public so the+ * drain can gate on `consolidation` ("daily" journals wait for the+ * consolidation cron instead of draining individually).+ */+ public getPostingSyncSettings(): Promise<PostingSyncSettings> {+ if (!this.postingSyncSettingsPromise) {+ this.postingSyncSettingsPromise = (async () => {+ const integration = await this.database+ .selectFrom("companyIntegration")+ .select("metadata")+ .where("id", "=", this.provider.id)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return resolvePostingSyncSettings(integration?.metadata);+ })();+ }+ return this.postingSyncSettingsPromise;+ }++ /**+ * `<dimensionId>:<valueId>` → Rillet field_value uuid from the+ * dimension-value mapping rows (entityType "dimensionValue"). Mutated+ * in place by the autoCreate flow so later pushes in the same drain+ * reuse the upserted values.+ */+ public getDimensionValueMappings(): Promise<Map<string, string>> {+ if (!this.dimensionValueMappingsPromise) {+ this.dimensionValueMappingsPromise = (async () => {+ const mappings = await getDimensionValueMappings(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ if (mappings.error) {+ throw new Error(+ `Failed to load dimension value mappings: ${mappings.error}`+ );+ }+ return buildDimensionValueMappingLookup(mappings.data ?? []);+ })();+ }+ return this.dimensionValueMappingsPromise;+ }++ /**+ * `dimensionId` → Rillet Field id from the dimension mapping rows+ * (entityType "dimension"). Mutated in place by resolveLineDimensions so+ * later pushes in the same drain reuse an auto-provisioned Field.+ */+ public getDimensionFieldMappings(): Promise<Map<string, string>> {+ if (!this.dimensionFieldMappingsPromise) {+ this.dimensionFieldMappingsPromise = (async () => {+ const mappings = await getDimensionMappings(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ if (mappings.error) {+ throw new Error(+ `Failed to load dimension field mappings: ${mappings.error}`+ );+ }+ return buildDimensionFieldLookup(mappings.data ?? []);+ })();+ }+ return this.dimensionFieldMappingsPromise;+ }++ /**+ * Resolve EVERY dimension on the given lines to a Rillet {field, value},+ * auto-provisioning the Rillet Field (createField) and Field value+ * (upsertFieldValue) as needed and persisting both mappings. Returns the+ * two lookups the mapper needs. This is the "send all dimensions" flow that+ * replaces the slot-gated setup for Rillet — Rillet has no field cap, so no+ * dimension is dropped for lack of a slot. Field auto-create is BY NAME+ * (reuse an existing Rillet Field with the same name before creating one);+ * value auto-create is BY the value's resolved READABLE label (part+ * readable id for items, name for everything else). A dimension whose name+ * can't be resolved, or a value whose label can't (source row deleted), is+ * left unmapped and the mapper drops just that ref.+ */+ protected async resolveLineDimensions(+ lines: ReadonlyArray<{ dimensions?: JournalLineDimensionRef[] }>+ ): Promise<{+ fieldIdByDimensionId: ReadonlyMap<string, string>;+ fieldValueIdsByValue: ReadonlyMap<string, string>;+ }> {+ const fieldIdByDimensionId = await this.getDimensionFieldMappings();+ const fieldValueIdsByValue = await this.getDimensionValueMappings();++ // 1. Auto-provision a Rillet Field per distinct dimension not yet mapped.+ const dimensionIds = [+ ...new Set(+ lines.flatMap((line) =>+ (line.dimensions ?? []).map((dimension) => dimension.dimensionId)+ )+ )+ ];+ const unmappedDimensionIds = dimensionIds.filter(+ (id) => !fieldIdByDimensionId.has(id)+ );++ if (unmappedDimensionIds.length > 0) {+ const names = await loadDimensionNames(this.database, {+ dimensionIds: unmappedDimensionIds+ });+ // Reuse an existing Rillet Field with the same name before creating a+ // new one — createField is not idempotent by name server-side.+ const existingFieldIdByName = new Map(+ (await this.rilletProvider.listFields()).map((field) => [+ field.name,+ field.id+ ])+ );++ for (const dimensionId of unmappedDimensionIds) {+ const name = names.get(dimensionId);+ if (!name) continue; // dimension deleted — its values won't attach++ let fieldId = existingFieldIdByName.get(name);+ if (!fieldId) {+ // Journal entries + bills are expense-side (EXPENSES applicability).+ const created = await this.rilletProvider.createField(+ name,+ "EXPENSES",+ buildRilletIdempotencyKey({+ companyId: this.companyId,+ operation: "create-field",+ localId: dimensionId+ })+ );+ fieldId = created.id;+ existingFieldIdByName.set(name, fieldId);+ }++ const persisted = await upsertDimensionMapping(this.database, {+ companyId: this.companyId,+ integration: this.provider.id,+ dimensionId,+ externalId: fieldId,+ externalName: name+ });+ if (persisted.error) {+ throw new Error(+ `Failed to store dimension field mapping: ${persisted.error}`+ );+ }+ fieldIdByDimensionId.set(dimensionId, fieldId);+ }+ }++ // 2. Auto-provision a Rillet Field value per distinct unmapped value whose+ // Field is now known.+ const unmappedValues: JournalLineDimensionRef[] = [];+ const seenValueKeys = new Set<string>();+ for (const line of lines) {+ for (const dimension of line.dimensions ?? []) {+ if (!fieldIdByDimensionId.has(dimension.dimensionId)) continue;+ const key = buildDimensionValueMappingEntityId(+ dimension.dimensionId,+ dimension.valueId+ );+ if (fieldValueIdsByValue.has(key) || seenValueKeys.has(key)) continue;+ seenValueKeys.add(key);+ unmappedValues.push({+ dimensionId: dimension.dimensionId,+ valueId: dimension.valueId+ });+ }+ }++ if (unmappedValues.length > 0) {+ const labels = await resolveDimensionValueLabels(this.database, {+ values: unmappedValues+ });+ for (const value of unmappedValues) {+ const key = buildDimensionValueMappingEntityId(+ value.dimensionId,+ value.valueId+ );+ const label = labels.get(key);+ if (!label) continue; // unresolvable label (source row deleted) — drop+ const fieldId = fieldIdByDimensionId.get(value.dimensionId);+ if (!fieldId) continue;++ const created = await this.rilletProvider.upsertFieldValue(+ fieldId,+ label+ );+ const persisted = await upsertDimensionValueMapping(this.database, {+ companyId: this.companyId,+ integration: this.provider.id,+ dimensionId: value.dimensionId,+ valueId: value.valueId,+ externalId: created.id,+ externalName: label+ });+ if (persisted.error) {+ throw new Error(+ `Failed to store dimension value mapping: ${persisted.error}`+ );+ }+ fieldValueIdsByValue.set(key, created.id);+ }+ }++ return { fieldIdByDimensionId, fieldValueIdsByValue };+ }++ async pushToAccounting(entityId: string): Promise<SyncResult> {+ if (!this.config.enabled) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error: "Sync disabled in config"+ };+ }++ try {+ const existingMapping = await this.mappingService.getByEntity(+ this.entityType,+ entityId,+ this.provider.id+ );++ if (existingMapping?.externalId) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ remoteId: existingMapping.externalId,+ error: `${this.pushOnlyEntityLabel} already pushed to Rillet — skipping (idempotent)`+ };+ }++ const localEntity = await this.fetchLocal(entityId);+ if (!localEntity) {+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: `Entity ${entityId} not found in Carbon`+ };+ }++ if (this.shouldSync) {+ const shouldSyncResult = await this.shouldSync({+ direction: "push",+ localEntity,+ isFirstSync: true,+ entityId+ });++ if (shouldSyncResult !== true) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error:+ typeof shouldSyncResult === "string"+ ? shouldSyncResult+ : "Entity not eligible for sync"+ };+ }+ }++ const remotePayload = await this.mapToRemote(localEntity);+ const remoteId = await this.upsertRemote(remotePayload, entityId);++ await withTriggersDisabled(this.database, async (tx) => {+ await this.linkEntities(tx, entityId, remoteId);+ });++ return {+ status: "success",+ action: "created",+ localId: entityId,+ remoteId+ };+ } catch (err) {+ if (err instanceof JournalEntrySyncError) {+ console.error(`[${this.constructor.name}] pre-flight failure`, {+ entityId,+ ...err.failure+ });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err.failure+ };+ }++ console.error(`[${this.constructor.name}] push failed`, {+ entityId,+ err+ });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err instanceof Error ? err.message : String(err)+ };+ }+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/entities/vendor.ts b/packages/ee/src/accounting/providers/rillet/entities/vendor.tsnew file mode 100644index 0000000000..f967f68594--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/vendor.ts@@ -0,0 +1,275 @@+import type { Accounting } from "../../../core/types";+import type { Rillet, RilletVendorWrite, RilletWriteOmit } from "../models";+import { buildRilletIdempotencyKey } from "../provider";+import {+ carbonCompanyExternalReference,+ carbonExternalReference,+ mapContactAddressToRilletAddress,+ mapPaymentTermsToRilletDays,+ RilletEntitySyncer,+ writeDroppingUnregisteredReferences+} from "./shared";++/**+ * RilletVendorSyncer — Carbon suppliers → Rillet Vendor objects.+ * PUSH-ONLY in v1 (buildRilletSyncConfig forces direction/owner): pull+ * methods come from RilletEntitySyncer's push-only rejections.+ *+ * The vendor half of what Xero handles with one dual-flag ContactSyncer:+ * Rillet Vendors are a separate object, so this syncer reads the supplier+ * tables only, with mapping rows under entityType "vendor". Same+ * contract as RilletCustomerSyncer — no name-matching lookup before+ * create; the carbon external_reference plus the create Idempotency-Key+ * are the duplicate guards in v1.+ */++/** Rillet caps vendor payment terms at 180 days. */+export const RILLET_VENDOR_MAX_PAYMENT_TERMS_DAYS = 180;++// Row shape for supplier queries with address and contact joins+type SupplierRow = {+ id: string;+ name: string;+ companyId: string;+ taxId: string | null;+ phone: string | null;+ fax: string | null;+ website: string | null;+ currencyCode: string | null;+ updatedAt: string | null;+ locationName: string | null;+ addressLine1: string | null;+ addressLine2: string | null;+ city: string | null;+ stateProvince: string | null;+ postalCode: string | null;+ countryCode: string | null;+ contactFirstName: string | null;+ contactLastName: string | null;+ contactEmail: string | null;+ contactMobilePhone: string | null;+ contactHomePhone: string | null;+ contactWorkPhone: string | null;+};++/**+ * Map a Carbon supplier to the Rillet Vendor write payload. Pure —+ * exported for tests.+ *+ * - Vendors carry a single flat `email` (unlike customer `emails[]`).+ * - The address maps only when Rillet's all-or-nothing group is complete.+ * - payment_terms maps only from a bare integer day count within+ * Rillet's 0-180 vendor range.+ * - tax_id from the Carbon supplier tax id when present.+ * - external_references carry the carbon (entity id) and+ * carbon-company (owning Carbon instance) tags.+ */+export function mapContactToRilletVendor(+ local: Accounting.Contact+): RilletVendorWrite {+ const address = mapContactAddressToRilletAddress(local);+ const paymentTerms = mapPaymentTermsToRilletDays(local.paymentTerms, {+ max: RILLET_VENDOR_MAX_PAYMENT_TERMS_DAYS+ });++ return {+ name: local.name,+ ...(local.email ? { email: local.email } : {}),+ ...(address ? { address } : {}),+ ...(paymentTerms !== undefined ? { payment_terms: paymentTerms } : {}),+ ...(local.taxId ? { tax_id: local.taxId } : {}),+ external_references: [+ carbonExternalReference(local.id),+ carbonCompanyExternalReference(local.companyId)+ ]+ };+}++export class RilletVendorSyncer extends RilletEntitySyncer<+ Accounting.Contact,+ Rillet.Vendor,+ RilletWriteOmit+> {+ protected get pushOnlyEntityLabel(): string {+ return "Vendors";+ }++ // =================================================================+ // 1. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(id: string): Promise<Accounting.Contact | null> {+ const suppliers = await this.fetchSuppliersByIds([id]);+ return suppliers.get(id) ?? null;+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.Contact>> {+ return this.fetchSuppliersByIds(ids);+ }++ private async fetchSuppliersByIds(+ ids: string[]+ ): Promise<Map<string, Accounting.Contact>> {+ if (ids.length === 0) return new Map();++ const rows = await (this.database as any)+ .selectFrom("supplier")+ .leftJoin("supplierTax", "supplierTax.supplierId", "supplier.id")+ .leftJoin(+ "supplierLocation",+ "supplierLocation.supplierId",+ "supplier.id"+ )+ .leftJoin("address", "address.id", "supplierLocation.addressId")+ .leftJoin("supplierContact", "supplierContact.supplierId", "supplier.id")+ .leftJoin("contact", "contact.id", "supplierContact.contactId")+ .select([+ "supplier.id",+ "supplier.name",+ "supplier.companyId",+ "supplierTax.taxId as taxId",+ "supplier.phone",+ "supplier.fax",+ "supplier.website",+ "supplier.currencyCode",+ "supplier.updatedAt",+ "supplierLocation.name as locationName",+ "address.addressLine1",+ "address.addressLine2",+ "address.city",+ // stateProvince + countryCode (alpha-2) feed Rillet's+ // all-or-nothing address group (state/country are required there)+ "address.stateProvince",+ "address.postalCode",+ "address.countryCode",+ "contact.firstName as contactFirstName",+ "contact.lastName as contactLastName",+ "contact.email as contactEmail",+ "contact.mobilePhone as contactMobilePhone",+ "contact.homePhone as contactHomePhone",+ "contact.workPhone as contactWorkPhone"+ ])+ .where("supplier.id", "in", ids)+ .where("supplier.companyId", "=", this.companyId)+ .execute();++ return this.groupAndTransformRows(rows as SupplierRow[]);+ }++ private groupAndTransformRows(+ rows: SupplierRow[]+ ): Map<string, Accounting.Contact> {+ const result = new Map<string, Accounting.Contact>();++ const groups = new Map<string, SupplierRow[]>();+ for (const row of rows) {+ const existing = groups.get(row.id) ?? [];+ existing.push(row);+ groups.set(row.id, existing);+ }++ for (const [id, groupRows] of groups) {+ const first = groupRows[0]!;+ const addresses = groupRows+ .filter((r) => r.addressLine1 || r.city)+ .map((r) => ({+ label: r.locationName ?? null,+ type: null,+ line1: r.addressLine1 ?? null,+ line2: r.addressLine2 ?? null,+ city: r.city ?? null,+ country: r.countryCode ?? null,+ region: r.stateProvince ?? null,+ postalCode: r.postalCode ?? null+ }));++ result.set(id, {+ id: first.id,+ name: first.name,+ firstName: first.contactFirstName ?? "",+ lastName: first.contactLastName ?? "",+ companyId: first.companyId,+ email: first.contactEmail ?? undefined,+ website: first.website ?? null,+ taxId: first.taxId ?? null,+ currencyCode: first.currencyCode ?? "USD",+ balance: null,+ creditLimit: null,+ paymentTerms: null,+ updatedAt: first.updatedAt ?? new Date().toISOString(),+ workPhone: first.contactWorkPhone ?? first.phone ?? null,+ mobilePhone: first.contactMobilePhone ?? null,+ fax: first.fax ?? null,+ homePhone: first.contactHomePhone ?? null,+ isVendor: true,+ isCustomer: false,+ addresses,+ raw: first+ });+ }++ return result;+ }++ // =================================================================+ // 2. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Rillet.Vendor | null> {+ return this.rilletProvider.getVendor(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Rillet.Vendor>> {+ const result = new Map<string, Rillet.Vendor>();+ for (const id of ids) {+ const vendor = await this.rilletProvider.getVendor(id);+ if (vendor) result.set(vendor.id, vendor);+ }+ return result;+ }++ // =================================================================+ // 3. TRANSFORMATION (Carbon -> Rillet)+ // =================================================================++ protected async mapToRemote(+ local: Accounting.Contact+ ): Promise<RilletVendorWrite> {+ return mapContactToRilletVendor(local);+ }++ // =================================================================+ // 4. UPSERT REMOTE (create with idempotency key, or PUT update)+ // =================================================================++ protected async upsertRemote(+ data: RilletVendorWrite,+ localId: string+ ): Promise<string> {+ const existingRemoteId = await this.getRemoteId(localId);++ if (existingRemoteId) {+ const updated = await writeDroppingUnregisteredReferences(+ data,+ (payload) => this.rilletProvider.updateVendor(existingRemoteId, payload)+ );+ return updated.id ?? existingRemoteId;+ }++ const created = await writeDroppingUnregisteredReferences(data, (payload) =>+ this.rilletProvider.createVendor(+ payload,+ buildRilletIdempotencyKey({+ companyId: this.companyId,+ operation: "vendor",+ localId+ })+ )+ );+ return created.id;+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/index.ts b/packages/ee/src/accounting/providers/rillet/index.tsnew file mode 100644index 0000000000..f2a1cbf4fe--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/index.ts@@ -0,0 +1,56 @@+import { ProviderID } from "../../core/models";+import { type SyncerRegistry, SyncFactory } from "../../core/sync";+import { RilletBillSyncer } from "./entities/bill";+import { RilletCustomerSyncer } from "./entities/customer";+import { RilletSalesInvoiceSyncer } from "./entities/invoice";+import { RilletItemSyncer } from "./entities/item";+import { RilletJournalEntrySyncer } from "./entities/journal-entry";+import { RilletPaymentSyncer } from "./entities/payment";+import { RilletVendorSyncer } from "./entities/vendor";++export * from "./entities/bill";+export * from "./entities/customer";+export * from "./entities/invoice";+export * from "./entities/item";+// journal-entry exports mapJournalEntryToRilletJournalEntry + the syncer+// for a future Rillet daily-consolidation path, mirroring the Xero/QBO+// barrels' contract+export * from "./entities/journal-entry";+// payment exports the composite entity-id helpers the inbound+// invoice-payment-updated webhook route uses to enqueue operations+export * from "./entities/payment";+export * from "./entities/shared";+export * from "./entities/vendor";+export * from "./models";+export * from "./provider";+export * from "./webhook";++/**+ * Every syncer Rillet implements, keyed by entity type. The module-scope+ * SyncFactory.register call below runs whenever this barrel is imported —+ * same contract as the Xero/QBO barrels (every consumer path evaluates it+ * before SyncFactory.getSyncer can be called with a Rillet context).+ */+export const rilletSyncerRegistry: SyncerRegistry = {+ // Master Data — Rillet keeps Customer and Vendor as separate objects+ // (no Xero-style dual-flag Contact), so each has its own syncer+ customer: RilletCustomerSyncer,+ vendor: RilletVendorSyncer,+ item: RilletItemSyncer,++ // Transaction Data (push-only, create-only in v1)+ bill: RilletBillSyncer,+ invoice: RilletSalesInvoiceSyncer,++ // Posting sync (push-only journal entries -> Rillet journal entries)+ journalEntry: RilletJournalEntrySyncer,++ // Pull-only: Rillet invoice payments settle Carbon sales invoices+ payment: RilletPaymentSyncer++ // Not implemented (force-disabled by buildRilletSyncConfig):+ // - purchaseOrder (Rillet has no PO endpoint)+ // - salesOrder / inventoryAdjustment / employee+};++SyncFactory.register(ProviderID.RILLET, rilletSyncerRegistry);diff --git a/packages/ee/src/accounting/providers/rillet/models.ts b/packages/ee/src/accounting/providers/rillet/models.tsnew file mode 100644index 0000000000..b28d9d4bbd--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/models.ts@@ -0,0 +1,443 @@+import { z } from "zod";++/**+ * Rillet API entity schemas (API version 4, pinned in provider.ts). Field+ * sets are deliberately limited to what the syncers map — Rillet objects+ * carry more fields, and zod strips unknown keys on parse. Reads (GET by+ * id, list endpoints) return the full shape including `id`/`updated_at`;+ * write payloads omit the server-owned fields (see RilletWriteOmit below).+ *+ * Conventions that differ from QBO/Xero:+ * - Money is `{ amount: "1000.00", currency: "USD" }` — the amount is a+ * 2-dp DECIMAL STRING, not a number.+ * - Dates are plain YYYY-MM-DD strings; timestamps are ISO 8601.+ * - Journal items are UNSIGNED with an explicit `side` (DEBIT/CREDIT).+ */+export namespace Rillet {+ /** `{ amount: "1000.00", currency: "USD" }` — amount is a 2-dp string. */+ export const MonetaryAmountSchema = z.object({+ amount: z.string(),+ currency: z.string()+ });++ export type MonetaryAmount = z.infer<typeof MonetaryAmountSchema>;++ /** Carbon always writes `{ type: "carbon", id: <carbon id> }`. */+ export const ExternalReferenceSchema = z.object({+ type: z.string(),+ id: z.string(),+ url: z.string().optional()+ });++ export type ExternalReference = z.infer<typeof ExternalReferenceSchema>;++ /** Chart-of-accounts entry from GET /accounts. */+ export const AccountSchema = z.object({+ id: z.string(),+ code: z.string().nullish(),+ name: z.string().nullish(),+ /** ASSET | LIABILITY | EQUITY | EXPENSE | INCOME — kept lenient. */+ type: z.string().nullish(),+ subtype: z.string().nullish(),+ /** ACTIVE | INACTIVE — only ACTIVE accounts are offered for mapping. */+ status: z.string().nullish(),+ intercompany: z.boolean().nullish(),+ updated_at: z.string().nullish()+ });++ export type Account = z.infer<typeof AccountSchema>;++ /** Entity from GET /subsidiaries (Rillet is multi-entity). */+ export const SubsidiarySchema = z.object({+ id: z.string(),+ name: z.string().nullish()+ });++ export type Subsidiary = z.infer<typeof SubsidiarySchema>;++ export const RelatedEntitySchema = z.object({+ id: z.string(),+ type: z.enum(["CUSTOMER", "VENDOR"])+ });++ export type RelatedEntity = z.infer<typeof RelatedEntitySchema>;++ /**+ * One pick-list value of a Rillet Field (GET /fields → fields[].values).+ * `id` is the uuid journal/bill/invoice items reference via+ * `fields[].field_value_id`.+ */+ export const FieldValueSchema = z.object({+ id: z.string(),+ name: z.string(),+ deactivated: z.boolean().nullish()+ });++ export type FieldValue = z.infer<typeof FieldValueSchema>;++ /**+ * A Rillet Field definition (verified v4 surface, 2026-08-04): the+ * dimension-native analytics field. `settings` describes applicability+ * per area (EXPENSES = bills/manual entries; REVENUE = customers/+ * contracts/invoices/credit memos) with `{ mandatory, display }` where+ * display is STANDALONE (single-select) or FREE_TAG — kept lenient.+ */+ export const FieldSchema = z.object({+ id: z.string(),+ name: z.string(),+ values: z.array(FieldValueSchema).default([]),+ settings: z.record(z.unknown()).nullish(),+ updated_at: z.string().nullish()+ });++ export type Field = z.infer<typeof FieldSchema>;++ /**+ * Field reference on a journal/bill/invoice item: uuid pairs, never+ * names (`fields: [{ field_id, field_value_id }]`).+ */+ export const ItemFieldRefSchema = z.object({+ field_id: z.string(),+ field_value_id: z.string()+ });++ export type ItemFieldRef = z.infer<typeof ItemFieldRefSchema>;++ /** Journal item: unsigned money + explicit side (unlike Xero's signed lines). */+ export const JournalEntryItemSchema = z.object({+ /** Server-assigned on reads. */+ id: z.string().optional(),+ /** Server-resolved from account_code on reads. */+ account_id: z.string().optional(),+ account_code: z.string(),+ amount: MonetaryAmountSchema,+ side: z.enum(["DEBIT", "CREDIT"]),+ description: z.string().optional(),+ vat_code: z.string().optional(),+ vat_type: z.string().optional(),+ /** Dimension refs (Rillet Fields) — uuid pairs. */+ fields: z.array(ItemFieldRefSchema).optional()+ });++ export type JournalEntryItem = z.infer<typeof JournalEntryItemSchema>;++ export const JournalEntrySchema = z.object({+ id: z.string(),+ name: z.string(),+ /** YYYY-MM-DD. */+ date: z.string(),+ /** ISO-4217. */+ currency: z.string(),+ /** Rillet requires >= 2 balanced items. */+ items: z.array(JournalEntryItemSchema).min(2),+ subsidiary_id: z.string().optional(),+ related_entity: RelatedEntitySchema.optional(),+ reversal_date: z.string().optional(),+ exchange_rate: z.number().optional(),+ updated_at: z.string().optional()+ });++ export type JournalEntry = z.infer<typeof JournalEntrySchema>;++ /**+ * Rillet addresses are an all-or-nothing group: line1/city/state/+ * zip_code/country must all be present (line2 optional).+ */+ export const AddressSchema = z.object({+ line1: z.string(),+ line2: z.string().optional(),+ city: z.string(),+ state: z.string(),+ zip_code: z.string(),+ country: z.string()+ });++ export type Address = z.infer<typeof AddressSchema>;++ export const CustomerEmailSchema = z.object({+ email: z.string(),+ type: z.enum(["MAIN_SENDER", "CC", "BCC"])+ });++ export type CustomerEmail = z.infer<typeof CustomerEmailSchema>;++ export const CustomerSchema = z.object({+ id: z.string(),+ name: z.string(),+ name_on_invoice: z.string().nullish(),+ address: AddressSchema.optional(),+ shipping_address: AddressSchema.optional(),+ emails: z.array(CustomerEmailSchema).optional(),+ external_references: z.array(ExternalReferenceSchema).optional(),+ /** Days, integer >= 0. */+ payment_terms: z.number().int().optional(),+ send_invoices_automatically: z.boolean().optional(),+ send_payment_reminders: z.boolean().optional(),+ updated_at: z.string().optional()+ });++ export type Customer = z.infer<typeof CustomerSchema>;++ export const VendorSchema = z.object({+ id: z.string(),+ name: z.string(),+ /** Default expense account code for the vendor's bills. */+ account_code: z.string().nullish(),+ address: AddressSchema.optional(),+ email: z.string().nullish(),+ /** Days, 0-180. */+ payment_terms: z.number().int().optional(),+ external_references: z.array(ExternalReferenceSchema).optional(),+ ten_ninety_nine_eligible: z.boolean().optional(),+ tax_id: z.string().nullish(),+ updated_at: z.string().optional()+ });++ export type Vendor = z.infer<typeof VendorSchema>;++ /**+ * Carbon only ever writes ONE_TIME prices (Rillet also supports+ * FIXED_RECURRING and USAGE; Carbon-generated AR_ONLY invoices carry+ * their own line totals, so the product price is nominal).+ */+ export const ProductPriceSchema = z.object({+ type: z.literal("ONE_TIME"),+ amount: MonetaryAmountSchema+ });++ export type ProductPrice = z.infer<typeof ProductPriceSchema>;++ /** Rillet caps product names at 250 characters. */+ export const ProductSchema = z.object({+ id: z.string(),+ name: z.string().max(250),+ description: z.string(),+ price: ProductPriceSchema,+ include_in_arr_mrr: z.boolean(),+ revenue_pattern: z.enum(["DAILY", "EVEN_PERIOD"]),+ /** Revenue account in Rillet's chart of accounts. */+ account_code: z.string(),+ status: z.enum(["ACTIVE", "INACTIVE"]).optional(),+ external_references: z.array(ExternalReferenceSchema).optional(),+ updated_at: z.string().optional()+ });++ export type Product = z.infer<typeof ProductSchema>;++ /** AR_ONLY invoice item — product_id is REQUIRED on every line. */+ export const InvoiceItemSchema = z.object({+ id: z.string().optional(),+ product_id: z.string(),+ description: z.string(),+ quantity: z.number(),+ total_amount: MonetaryAmountSchema,+ tax_amount: MonetaryAmountSchema.optional(),+ external_references: z.array(ExternalReferenceSchema).min(1)+ });++ export type InvoiceItem = z.infer<typeof InvoiceItemSchema>;++ /**+ * AR_ONLY invoice: Carbon keeps generating/sending the invoice; Rillet+ * carries the receivable. `invoice_number` is Carbon's readable id.+ */+ export const InvoiceSchema = z.object({+ id: z.string(),+ scope: z.literal("AR_ONLY"),+ customer_id: z.string(),+ /** YYYY-MM-DD. */+ invoice_date: z.string(),+ invoice_number: z.string(),+ /** Defaults to invoice_date when omitted. */+ due_date: z.string().optional(),+ tax_amount: MonetaryAmountSchema.optional(),+ subsidiary_id: z.string().optional(),+ exchange_rate: z.number().optional(),+ items: z.array(InvoiceItemSchema).min(1),+ external_references: z.array(ExternalReferenceSchema).min(1),+ status: z.string().optional(),+ updated_at: z.string().optional()+ });++ export type Invoice = z.infer<typeof InvoiceSchema>;++ export const BillItemSchema = z.object({+ id: z.string().optional(),+ account_code: z.string(),+ amount: MonetaryAmountSchema,+ description: z.string().optional(),+ tax_rate: z.number().optional(),+ fields: z.array(ItemFieldRefSchema).optional()+ });++ export type BillItem = z.infer<typeof BillItemSchema>;++ export const BillStatusSchema = z.enum([+ "UNPAID",+ "PAID",+ "PARTIALLY_PAID",+ "CREDITED",+ "PARTIALLY_CREDITED",+ "APPLIED"+ ]);++ export type BillStatus = z.infer<typeof BillStatusSchema>;++ export const BillSchema = z.object({+ id: z.string(),+ vendor_id: z.string(),+ /** Carbon's readable purchase-invoice id. */+ expense_number: z.string(),+ bill_date: z.string(),+ /** REQUIRED by Rillet (unlike Carbon, where dateDue can be null). */+ due_date: z.string(),+ items: z.array(BillItemSchema).min(1),+ subsidiary_id: z.string().optional(),+ impact_date: z.string().optional(),+ external_references: z.array(ExternalReferenceSchema).optional(),+ exchange_rate: z.number().optional(),+ status: BillStatusSchema.optional(),+ updated_at: z.string().optional()+ });++ export type Bill = z.infer<typeof BillSchema>;++ /**+ * Payment status union across BOTH sources: the list endpoint+ * (GET /invoices/{id}/payments → SUCCESSFUL | FAILED | UNCLEARED) and+ * the invoice-payment-updated webhook (UNCLEARED | CLEARED | RECONCILED+ * | FAILED). Anything except FAILED settles the invoice.+ */+ export const InvoicePaymentStatusSchema = z.enum([+ "SUCCESSFUL",+ "FAILED",+ "UNCLEARED",+ "CLEARED",+ "RECONCILED"+ ]);++ export type InvoicePaymentStatus = z.infer<typeof InvoicePaymentStatusSchema>;++ /**+ * One invoice payment. Accepts both wire shapes: the list endpoint+ * carries `amount: { amount, currency }` + `date`/`account_code`; the+ * webhook payload carries a flat `amount` + `currency` ++ * `payment_date`/`cash_account_code`. Use getRilletPaymentAmount /+ * getRilletPaymentCurrency (entities/payment.ts) to normalize.+ */+ export const InvoicePaymentSchema = z.object({+ id: z.string(),+ status: InvoicePaymentStatusSchema,+ invoice_id: z.string().optional(),+ amount: z.union([MonetaryAmountSchema, z.string(), z.number()]).optional(),+ currency: z.string().optional(),+ date: z.string().optional(),+ payment_date: z.string().optional(),+ account_code: z.string().optional(),+ cash_account_code: z.string().optional(),+ created_at: z.string().optional(),+ updated_at: z.string().optional()+ });++ export type InvoicePayment = z.infer<typeof InvoicePaymentSchema>;++ /**+ * One bill payment (AP mirror of InvoicePayment). Read from+ * `GET /bills/{billId}/payments` and the org-wide `GET /bill-payments`+ * feed. Same amount/currency/date wire shapes as invoice payments; the+ * parent link is `bill_id` (not `invoice_id`).+ *+ * VERIFY: the bill-payment status vocabulary is not confirmed against the+ * live Rillet OpenAPI, so `status` is kept lenient (a bare string) — only+ * "FAILED" reverses a recorded payment; anything else settles, mirroring+ * the invoice-payment rule (Anything except FAILED settles).+ */+ export const BillPaymentSchema = z.object({+ id: z.string(),+ status: z.string(),+ bill_id: z.string().optional(),+ amount: z.union([MonetaryAmountSchema, z.string(), z.number()]).optional(),+ currency: z.string().optional(),+ date: z.string().optional(),+ payment_date: z.string().optional(),+ account_code: z.string().optional(),+ cash_account_code: z.string().optional(),+ created_at: z.string().optional(),+ updated_at: z.string().optional()+ });++ export type BillPayment = z.infer<typeof BillPaymentSchema>;+}++/** Server-owned fields every Rillet write payload omits. */+export type RilletWriteOmit = "id" | "updated_at";++/** Transaction documents additionally carry a server-owned status. */+export type RilletTransactionWriteOmit = RilletWriteOmit | "status";++export type RilletJournalEntryCreate = Omit<+ Rillet.JournalEntry,+ RilletWriteOmit+>;+export type RilletCustomerWrite = Omit<Rillet.Customer, RilletWriteOmit>;+export type RilletVendorWrite = Omit<Rillet.Vendor, RilletWriteOmit>;+export type RilletProductWrite = Omit<Rillet.Product, RilletWriteOmit>;+export type RilletInvoiceCreate = Omit<+ Rillet.Invoice,+ RilletTransactionWriteOmit+>;+export type RilletBillCreate = Omit<Rillet.Bill, RilletTransactionWriteOmit>;++/**+ * Create payload for a Rillet payment recorded against one document+ * (`POST /invoices/{id}/payments` for AR, `POST /bills/{id}/payments` for AP —+ * the parent document is in the path). Used by the Phase G outbound payment+ * write-back for Carbon-born payments (e.g. a bill paid through Ramp).+ *+ * VERIFY: neither the create endpoints/paths nor the exact field names are+ * confirmed against the live Rillet OpenAPI (no local spec exists). The shape+ * mirrors the READ schemas (InvoicePaymentSchema / BillPaymentSchema) —+ * `amount` as a MonetaryAmount, an ISO `date`, and the cash/bank+ * `account_code` — plus the Carbon external reference. If a field is wrong,+ * the create 400s and the sync operation lands Failed (visible, not silent).+ */+export type RilletPaymentCreate = {+ amount: Rillet.MonetaryAmount;+ /** YYYY-MM-DD. VERIFIED (sandbox 2026-08-11): the create endpoints take+ * `date`, not `payment_date` — the latter 400s with "date must not be+ * null". */+ date: string;+ /** Rillet cash/bank account code the payment clears through. */+ account_code: string;+ /** Carbon payment id, tagged like every other pushed document. */+ external_references?: Rillet.ExternalReference[];+};++/**+ * Local shape of a pulled Rillet invoice payment. Core has no+ * Accounting.Payment schema yet, so the payment syncer's TLocal stays+ * provider-local: it describes what upsertLocal writes into the Carbon+ * `payment` + `invoiceSettlement` tables, not a core contract.+ */+export type RilletLocalPayment = {+ /** Composite sync entity id — see getRilletPaymentSyncEntityId. */+ id: string;+ invoiceRemoteId: string;+ paymentRemoteId: string;+ amount: number;+ currencyCode: string | null;+ /** YYYY-MM-DD. */+ date: string;+ status: Rillet.InvoicePaymentStatus;+ updatedAt: string;+};++/**+ * Parse a Rillet timestamp (ISO 8601). Returns null for missing/invalid+ * values — same contract as parseQboDate.+ */+export function parseRilletDate(value: string | null | undefined): Date | null {+ if (!value) return null;+ const parsed = new Date(value);+ return Number.isNaN(parsed.getTime()) ? null : parsed;+}diff --git a/packages/ee/src/accounting/providers/rillet/provider.ts b/packages/ee/src/accounting/providers/rillet/provider.tsnew file mode 100644index 0000000000..7b1840a66a--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/provider.ts@@ -0,0 +1,1153 @@+import { createHash } from "node:crypto";+import { ProviderID } from "../../core/models";+import type {+ AccountingEntityType,+ AuthProvider,+ DimensionTarget,+ GlobalSyncConfig,+ ListChangesResult,+ ProviderCapabilities,+ ProviderChange,+ ProviderConfig,+ ProviderCredentials+} from "../../core/types";+import { BaseProvider } from "../../core/types";+import {+ AccountingApiError,+ type ApiErrorDetails,+ HTTPClient,+ type HttpResponse+} from "../../core/utils";+import {+ getRilletBillPaymentSyncEntityId,+ getRilletPaymentSyncEntityId+} from "./entities/payment";+import type {+ Rillet,+ RilletBillCreate,+ RilletCustomerWrite,+ RilletInvoiceCreate,+ RilletJournalEntryCreate,+ RilletPaymentCreate,+ RilletProductWrite,+ RilletVendorWrite+} from "./models";++const RILLET_PRODUCTION_HOST = "https://api.rillet.com";+const RILLET_SANDBOX_HOST = "https://sandbox.api.rillet.com";++/**+ * Pinned Rillet API version, sent as X-Rillet-API-Version on every request+ * — the server-side default flips on 2026-08-01, so pinning is what keeps+ * the wire contract stable. Bump deliberately, in one place.+ */+export const RILLET_API_VERSION = "4";++/** Rillet's page-size cap for cursor-paginated list endpoints. */+export const RILLET_PAGE_SIZE = 100;++/** Dimension slot target prefix: `field:<fieldId>` (Rillet Field uuid). */+const RILLET_FIELD_TARGET_PREFIX = "field:";++export function buildRilletFieldTarget(fieldId: string): string {+ return `${RILLET_FIELD_TARGET_PREFIX}${fieldId}`;+}++/** The Field uuid inside a `field:<id>` target; null otherwise. */+export function parseRilletFieldTarget(target: string): string | null {+ if (!target.startsWith(RILLET_FIELD_TARGET_PREFIX)) return null;+ const fieldId = target.slice(RILLET_FIELD_TARGET_PREFIX.length);+ return fieldId.length > 0 ? fieldId : null;+}++// /********************************************************\+// * RFC 9457 problem parsing *+// \********************************************************/++/**+ * Parse a Rillet error response into structured ApiErrorDetails. Rillet+ * errors are RFC 9457 problem details — `{ type (uri), title, status,+ * detail }` — optionally carrying an `errors` array extension whose entry+ * shape is not pinned by the docs, so it is read defensively (strings or+ * objects with pointer/field + detail/message).+ */+export function extractRilletErrorDetails(+ statusCode: number,+ statusText: string,+ responseData: unknown+): ApiErrorDetails {+ const details: ApiErrorDetails = {+ statusCode,+ statusText,+ rawResponse: responseData+ };++ let data: unknown = responseData;+ if (typeof responseData === "string") {+ try {+ data = JSON.parse(responseData);+ } catch {+ if (responseData.length < 500) {+ details.providerMessage = responseData;+ }+ return details;+ }+ }++ if (typeof data !== "object" || data === null) {+ return details;+ }++ const problem = data as Record<string, unknown>;++ if (typeof problem.type === "string") {+ details.providerErrorType = problem.type;+ }+ if (+ typeof problem.status === "number" ||+ typeof problem.status === "string"+ ) {+ details.providerErrorCode = problem.status;+ }+ if (typeof problem.detail === "string") {+ details.providerMessage = problem.detail;+ } else if (typeof problem.title === "string") {+ details.providerMessage = problem.title;+ }++ if (Array.isArray(problem.errors)) {+ const validationErrors: Array<{ field?: string; message: string }> = [];+ for (const entry of problem.errors) {+ if (typeof entry === "string") {+ validationErrors.push({ message: entry });+ continue;+ }+ if (typeof entry !== "object" || entry === null) continue;++ const record = entry as Record<string, unknown>;+ const field = [record.pointer, record.field, record.path].find(+ (value): value is string => typeof value === "string"+ );+ const message = [record.detail, record.message, record.title].find(+ (value): value is string => typeof value === "string"+ );+ validationErrors.push({+ field,+ message: message ?? JSON.stringify(entry)+ });+ }+ if (validationErrors.length > 0) {+ details.validationErrors = validationErrors;+ }+ }++ return details;+}++/**+ * Creates, logs and throws an AccountingApiError from a failed Rillet+ * response (parallel to throwQboApiError / throwXeroApiError).+ */+export function throwRilletApiError(+ operation: string,+ response: { error: boolean; message: string; code: number; data: unknown }+): never {+ const details = extractRilletErrorDetails(+ response.code,+ response.message,+ response.data+ );++ const error = new AccountingApiError("rillet", operation, details);++ console.error(`[Rillet API Error] ${operation}`, {+ statusCode: details.statusCode,+ statusText: details.statusText,+ providerErrorType: details.providerErrorType,+ providerErrorCode: details.providerErrorCode,+ providerMessage: details.providerMessage,+ validationErrors: details.validationErrors+ });++ throw error;+}++/**+ * True when Rillet rejected a write because an external_references entry+ * uses a type slug the organization hasn't registered. Reference types are+ * dashboard-only configuration (Rillet Settings → External References) —+ * there is no API to create them — so callers degrade: optional references+ * are stripped and the write retried; required ones (AR_ONLY invoices)+ * surface a user-fixable Warning.+ */+export function isRilletUnknownExternalReferenceTypeError(+ error: unknown+): boolean {+ if (!(error instanceof AccountingApiError)) return false;+ // Rillet's RFC 9457 type URI is the stable signal; the message text is a+ // fallback for older responses that only carried the detail.+ if (+ typeof error.details.providerErrorType === "string" &&+ error.details.providerErrorType.endsWith(+ "/exception/external_reference_type_not_found"+ )+ ) {+ return true;+ }+ return (+ typeof error.details.providerMessage === "string" &&+ error.details.providerMessage.includes(+ "External reference type does not exist"+ )+ );+}++/**+ * Deterministic Idempotency-Key for a Rillet create POST (Rillet replays+ * the stored response for 24h): the same company + operation + local+ * entity always produces the same key, so a retried push cannot+ * double-create — even when the retry's payload drifted (dimension+ * resolution, an edit between attempts). The payload is deliberately NOT+ * hashed (v4 spec, Pillar C): a crash between the remote create and the+ * local mapping write retries the push, and a payload-sensitive key would+ * mint a fresh key for the drifted payload and duplicate the document+ * remotely. Every call site's localId identifies one logical create+ * (composite ids for payments, `:reversal`-suffixed ids for reversal+ * journals, batch keys for consolidated journals).+ */+export function buildRilletIdempotencyKey(args: {+ companyId: string;+ operation: string;+ localId: string;+}): string {+ return createHash("sha256")+ .update(`${args.companyId}:${args.operation}:${args.localId}`)+ .digest("hex");+}++// /********************************************************\+// * Sync-config constraints *+// \********************************************************/++/**+ * Entities Rillet syncs in v1 — every one of them PUSH-ONLY (Carbon →+ * Rillet). Rillet is the ledger of record for what Carbon pushes; pulling+ * master data back is a follow-up.+ */+export const RILLET_PUSH_ONLY_ENTITIES = [+ "customer",+ "vendor",+ "item",+ "invoice",+ "bill",+ "journalEntry"+] as const satisfies readonly AccountingEntityType[];++/**+ * Entities Rillet syncs TWO-WAY: `payment`. Inbound (pull) — provider-recorded+ * invoice/bill payments settle Carbon documents (Phase F). Outbound (push) —+ * Carbon-born Posted payments (e.g. a bill paid through Ramp, recorded in+ * Carbon) are written to Rillet as payment documents (Phase G). Which direction+ * fires per record is decided by origin: a payment already carrying a `payment`+ * mapping is provider-known and skips push; a mapping-less Carbon payment is+ * pushed. Both flow through the same `payment` syncer.+ */+export const RILLET_TWO_WAY_ENTITIES = [+ "payment"+] as const satisfies readonly AccountingEntityType[];++/**+ * Entities Rillet does not sync (force-disabled): Rillet has no purchase+ * order endpoint, and inventory adjustments flow as journals through the+ * posting sync.+ */+export const RILLET_DISABLED_ENTITIES = [+ "purchaseOrder",+ "salesOrder",+ "inventoryAdjustment",+ "employee"+] as const satisfies readonly AccountingEntityType[];++/**+ * Constrain a resolved sync config to what Rillet supports (modeled on+ * buildQbdSyncConfig): supported document entities are forced to direction+ * "push-to-accounting" with owner "carbon" (push-only is a capability+ * limit, not a preference — stored two-way/pull overrides are ignored)+ * while their per-company `enabled` flag survives; `payment` is forced+ * `two-way` AND enabled (inbound pull + outbound push must both work as soon+ * as the integration is connected — there is no per-company toggle for it,+ * and the documents-mode families gate governs whether it actually runs);+ * everything else is force-disabled.+ */+export function buildRilletSyncConfig(+ resolved: GlobalSyncConfig+): GlobalSyncConfig {+ const entities = Object.fromEntries(+ Object.entries(resolved.entities).map(([entityType, entityConfig]) => [+ entityType,+ { ...entityConfig }+ ])+ ) as GlobalSyncConfig["entities"];++ for (const entityType of RILLET_PUSH_ONLY_ENTITIES) {+ entities[entityType] = {+ ...entities[entityType],+ direction: "push-to-accounting",+ owner: "carbon"+ };+ }++ for (const entityType of RILLET_TWO_WAY_ENTITIES) {+ entities[entityType] = {+ ...entities[entityType],+ direction: "two-way",+ owner: "accounting",+ enabled: true+ };+ }++ for (const entityType of RILLET_DISABLED_ENTITIES) {+ entities[entityType] = { ...entities[entityType], enabled: false };+ }++ // Always-on: automated postings sync whenever the integration is connected.+ // Forced here (defense-in-depth over the DEFAULT_SYNC_CONFIG default) so a+ // stale stored `enabled: false` override can't silently turn journals off.+ entities.journalEntry = { ...entities.journalEntry, enabled: true };++ return { entities };+}++// /********************************************************\+// * Provider *+// \********************************************************/++type RilletProviderConfig = ProviderConfig<{+ /**+ * Credentials parsed from `companyIntegration.metadata.credentials`+ * (parseStoredCredentials). Expected to be the `apiKey` variant; absent+ * until an API key is entered on the integration settings page.+ */+ credentials?: ProviderCredentials;+}> & { id: ProviderID.RILLET };++const NO_OAUTH_MESSAGE =+ "Rillet authenticates with an API key entered on the integration settings page — there is no OAuth flow";++function getRilletApiKeyCredentials(+ credentials: ProviderCredentials+): Extract<ProviderCredentials, { type: "apiKey" }> {+ if (credentials.type !== "apiKey") {+ throw new Error(+ `Rillet requires apiKey credentials, received "${credentials.type}"`+ );+ }+ return credentials;+}++/**+ * Rillet single-object endpoints are documented as returning the bare+ * object, but be defensive about a wrapped envelope (e.g.+ * `{ journal_entry: {...} }`) — accept both.+ */+function unwrapRilletEntity<T>(data: unknown, envelopeKey: string): T | null {+ if (data === null || typeof data !== "object") return null;+ const wrapped = (data as Record<string, unknown>)[envelopeKey];+ if (wrapped && typeof wrapped === "object") return wrapped as T;+ return data as T;+}++export class RilletProvider extends BaseProvider {+ static id = ProviderID.RILLET;++ readonly capabilities: ProviderCapabilities = {+ transport: "rest",+ supportsWebhooks: true,+ supportsJournalPush: true+ };++ /** No cap: /invoice-payments `updated.gt` reaches arbitrarily far back. */+ readonly pullLookbackDays?: number;++ http: HTTPClient;++ private readonly syncConfig: GlobalSyncConfig;++ constructor(public config: Omit<RilletProviderConfig, "id">) {+ super();+ this.creds = config.credentials;+ this.syncConfig = buildRilletSyncConfig(config.syncConfig);++ // API keys are environment-specific — the stored credentials pick the host+ const environment =+ config.credentials?.type === "apiKey"+ ? config.credentials.environment+ : "production";+ this.http = new HTTPClient(+ environment === "sandbox" ? RILLET_SANDBOX_HOST : RILLET_PRODUCTION_HOST+ );++ // No OAuth client: the API key IS the whole connection. getCredentials+ // still works so generic code can read the stored credentials.+ const auth: AuthProvider = {+ getCredentials: () => {+ if (!this.creds) {+ throw new Error(+ "Rillet integration has no stored credentials — enter an API key on the integration settings page"+ );+ }+ return this.creds;+ },+ getAuthUrl: () => {+ throw new Error(NO_OAUTH_MESSAGE);+ },+ exchangeCode: () => {+ throw new Error(NO_OAUTH_MESSAGE);+ },+ refresh: () => {+ throw new Error(NO_OAUTH_MESSAGE);+ }+ };+ this.auth = auth;+ }++ get id(): ProviderID.RILLET {+ return ProviderID.RILLET;+ }++ getSyncConfig(entity: AccountingEntityType) {+ return this.syncConfig.entities[entity];+ }++ async authenticate(): Promise<ProviderCredentials> {+ throw new Error(NO_OAUTH_MESSAGE);+ }++ /** `providerMetadata.subsidiaryId` when configured, else null. */+ get subsidiaryId(): string | null {+ if (this.creds?.type !== "apiKey") return null;+ const value = this.creds.providerMetadata?.subsidiaryId;+ return typeof value === "string" && value.length > 0 ? value : null;+ }++ /** `providerMetadata.webhookToken` — the inbound webhook route's shared secret. */+ get webhookToken(): string | null {+ if (this.creds?.type !== "apiKey") return null;+ const value = this.creds.providerMetadata?.webhookToken;+ return typeof value === "string" && value.length > 0 ? value : null;+ }++ /**+ * Perform an authenticated Rillet request. Every call carries the bearer+ * API key and the pinned X-Rillet-API-Version. There is NO 401-refresh+ * retry: API keys don't refresh, so a 401 is terminal (revoked/wrong+ * key). HTTPClient already converts 429 into a RatelimitError.+ */+ async request<T>(+ method: string,+ url: string,+ options?: RequestInit & { idempotencyKey?: string }+ ): Promise<HttpResponse<T>> {+ const credentials = getRilletApiKeyCredentials(this.auth.getCredentials());+ const { idempotencyKey, ...init } = options ?? {};++ const headers: Record<string, string> = {+ Authorization: `Bearer ${credentials.apiKey}`,+ "X-Rillet-API-Version": RILLET_API_VERSION,+ Accept: "application/json",+ "Content-Type": "application/json",+ ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),+ ...((init.headers ?? {}) as Record<string, string>)+ };++ return this.http.request<T>(method, url, { ...init, headers });+ }++ /**+ * Drain a cursor-paginated list endpoint (`?limit=100&cursor=...` →+ * `pagination.next_cursor`, absent on the last page) in ONE pass —+ * Rillet cursors expire after 2 hours, so pagination is never resumed+ * across runs.+ */+ private async listPaginated<T>(+ path: string,+ extractRows: (data: Record<string, unknown>) => T[] | undefined+ ): Promise<T[]> {+ const rows: T[] = [];+ let cursor: string | undefined;++ do {+ const separator = path.includes("?") ? "&" : "?";+ const url = `${path}${separator}limit=${RILLET_PAGE_SIZE}${+ cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""+ }`;++ const response = await this.request<Record<string, unknown>>("GET", url);+ if (response.error) {+ throwRilletApiError(`list ${path}`, response);+ }++ rows.push(...(extractRows(response.data ?? {}) ?? []));++ const pagination = (+ response.data as {+ pagination?: { next_cursor?: string | null };+ } | null+ )?.pagination;+ cursor = pagination?.next_cursor ?? undefined;+ } while (cursor);++ return rows;+ }++ /** Credentials work iff GET /accounts succeeds. */+ async validate(): Promise<boolean> {+ try {+ const response = await this.request<{ accounts?: Rillet.Account[] }>(+ "GET",+ "/accounts"+ );+ return !response.error;+ } catch (error) {+ console.error("Rillet validate error:", error);+ return false;+ }+ }++ // =================================================================+ // Chart of accounts+ // =================================================================++ /**+ * Fetch the active Rillet chart of accounts, normalized to the+ * `{ id, code, name }` shape the settings loader / account-mapping UI+ * consumes. INACTIVE and code-less accounts are dropped — journal/bill+ * items address accounts by CODE. Returns [] on failure, mirroring the+ * Xero/QBO forgiving contract.+ */+ async listChartOfAccounts(): Promise<+ Array<{ id: string; code: string; name: string }>+ > {+ try {+ // GET /accounts is documented unpaginated+ const response = await this.request<{ accounts?: Rillet.Account[] }>(+ "GET",+ "/accounts"+ );+ if (response.error) {+ throwRilletApiError("list accounts", response);+ }++ const accounts = response.data?.accounts ?? [];+ return accounts+ .filter((account) => account.status === "ACTIVE" && account.code)+ .map((account) => ({+ id: account.id,+ code: account.code!,+ name: account.name ?? account.code!+ }));+ } catch (error) {+ console.error("Failed to fetch Rillet accounts:", error);+ return [];+ }+ }++ /**+ * Fetch the Rillet subsidiaries (multi-entity ledger; the configured+ * `providerMetadata.subsidiaryId` scopes every pushed document). Returns+ * [] on failure — a settings-surface read, same forgiving contract as+ * listChartOfAccounts.+ */+ async listSubsidiaries(): Promise<Rillet.Subsidiary[]> {+ try {+ return await this.listPaginated<Rillet.Subsidiary>(+ "/subsidiaries",+ (data) => data.subsidiaries as Rillet.Subsidiary[] | undefined+ );+ } catch (error) {+ console.error("Failed to fetch Rillet subsidiaries:", error);+ return [];+ }+ }++ // =================================================================+ // Fields (dimensions) — verified v4 surface (spec changelog 2026-08-04)+ // =================================================================++ /**+ * Fetch the Rillet Field definitions with their pick-list values+ * (GET /fields → `{ fields: [...] }`). The endpoint is documented+ * unpaginated, but a cursor is followed defensively if one ever+ * appears. Throws a structured error on API failure.+ */+ async listFields(): Promise<Rillet.Field[]> {+ const fields: Rillet.Field[] = [];+ let cursor: string | undefined;++ do {+ const url = `/fields${+ cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""+ }`;+ const response = await this.request<Record<string, unknown>>("GET", url);+ if (response.error) {+ throwRilletApiError("list fields", response);+ }++ const data = response.data ?? {};+ fields.push(...((data.fields as Rillet.Field[] | undefined) ?? []));++ const pagination = (+ data as { pagination?: { next_cursor?: string | null } }+ ).pagination;+ cursor = pagination?.next_cursor ?? undefined;+ } while (cursor);++ return fields;+ }++ /**+ * The journal dimension targets this org supports: one+ * `field:<fieldId>` target per Rillet Field (dimension-native — no+ * structural cap). Returns [] on failure, mirroring the forgiving+ * settings-surface contract of listChartOfAccounts.+ */+ async journalDimensionTargets(): Promise<DimensionTarget[]> {+ try {+ const fields = await this.listFields();+ return fields.map((field) => ({+ id: buildRilletFieldTarget(field.id),+ label: field.name,+ capacity: 1+ }));+ } catch (error) {+ console.error("Failed to fetch Rillet fields:", error);+ return [];+ }+ }++ /**+ * Upsert a Field pick-list value BY NAME+ * (POST /fields/{id}/values `{ name }`) — Rillet returns the FULL Field+ * including the created value's uuid. NOT idempotent server-side (verified+ * on sandbox 2026-08-14: a name that already exists — e.g. provisioned by+ * an earlier Carbon instance whose mappings are gone, or seeded in the+ * Rillet UI — 400s `Value "<name>" already exists`), so on that rejection+ * the existing value is recovered by name via `GET /fields` (there is no+ * `GET /fields/{id}` — 405). Throws when Rillet accepts the write but the+ * value cannot be found on the returned Field (contract drift — fail loud,+ * not with a broken ref).+ */+ async upsertFieldValue(+ fieldId: string,+ rawName: string+ ): Promise<Rillet.FieldValue> {+ // Rillet TRIMS value names on write and dedupes them trim-insensitively+ // (verified on sandbox 2026-08-14: creating "Test " comes back stored as+ // "Test", and a later POST of "Test" 400s `already exists`). Carbon's+ // dimension labels can carry inconsistent whitespace across lines ("Test"+ // vs "Test "), so we normalize to Rillet's own behavior — trim on write and+ // match trimmed on both sides — so those resolve to ONE Field value instead+ // of failing the whole journal on an exact-string miss.+ const name = rawName.trim();+ let field: Rillet.Field;+ try {+ field = await this.writeEntity<Rillet.Field>({+ method: "POST",+ path: `/fields/${fieldId}/values`,+ envelopeKey: "field",+ operation: "upsert field value",+ payload: { name }+ });+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ if (/already exists/i.test(message)) {+ const existingField = (await this.listFields()).find(+ (candidate) => candidate.id === fieldId+ );+ const existingValue =+ existingField?.values?.find(+ (candidate) =>+ candidate.name?.trim() === name && !candidate.deactivated+ ) ??+ existingField?.values?.find(+ (candidate) => candidate.name?.trim() === name+ );+ if (existingValue) return existingValue;+ }+ throw err;+ }++ const value = (field.values ?? []).find(+ (candidate) => candidate.name?.trim() === name+ );+ if (!value) {+ throw new Error(+ `Rillet accepted the field-value upsert but "${name}" is not on the returned field ${fieldId}`+ );+ }++ return value;+ }++ /**+ * Create a Field definition (a whole dimension) BY NAME+ * (POST /fields). `area` is the applicability scope — EXPENSES covers+ * bills + manual journal entries, REVENUE covers invoices/credit memos —+ * written as `settings.<AREA> = { mandatory, display }` with display+ * STANDALONE (single-select; one value per line per Carbon dimension).+ * Unlike upsertFieldValue this is NOT idempotent by name server-side, so+ * callers must check for an existing Field first (see resolveLineDimensions)+ * and pass a deterministic Idempotency-Key to guard a create-retry.+ *+ * VERIFY: the POST /fields request body is inferred from the documented+ * GET /fields shape (v3 spec changelog 2026-08-04) — confirm against the+ * live Rillet sandbox before relying on auto-provisioning in production.+ */+ async createField(+ name: string,+ area: "EXPENSES" | "REVENUE",+ idempotencyKey?: string+ ): Promise<Rillet.Field> {+ return this.writeEntity<Rillet.Field>({+ method: "POST",+ path: "/fields",+ envelopeKey: "field",+ operation: "create field",+ payload: {+ name,+ settings: { [area]: { mandatory: false, display: "STANDALONE" } }+ },+ idempotencyKey+ });+ }++ /** All Rillet customers (cursor-drained). Throws on API failure. */+ async listCustomers(): Promise<Rillet.Customer[]> {+ return this.listPaginated<Rillet.Customer>(+ "/customers",+ (data) => data.customers as Rillet.Customer[] | undefined+ );+ }++ /** All Rillet vendors (cursor-drained). Throws on API failure. */+ async listVendors(): Promise<Rillet.Vendor[]> {+ return this.listPaginated<Rillet.Vendor>(+ "/vendors",+ (data) => data.vendors as Rillet.Vendor[] | undefined+ );+ }++ // =================================================================+ // Entity reads/writes (reads return null on failure; writes throw a+ // structured AccountingApiError; creates carry an Idempotency-Key)+ // =================================================================++ private async readEntity<T>(+ path: string,+ envelopeKey: string+ ): Promise<T | null> {+ const response = await this.request<unknown>("GET", path);+ if (response.error) return null;+ return unwrapRilletEntity<T>(response.data, envelopeKey);+ }++ private async writeEntity<T>(args: {+ method: "POST" | "PUT";+ path: string;+ envelopeKey: string;+ operation: string;+ payload: unknown;+ idempotencyKey?: string;+ }): Promise<T> {+ const response = await this.request<unknown>(args.method, args.path, {+ body: JSON.stringify(args.payload),+ idempotencyKey: args.idempotencyKey+ });++ if (response.error) {+ throwRilletApiError(args.operation, response);+ }++ const entity = unwrapRilletEntity<T>(response.data, args.envelopeKey);+ if (!entity) {+ throw new Error(+ `Rillet returned success but no ${args.envelopeKey} body for ${args.operation}`+ );+ }++ return entity;+ }++ async getJournalEntry(id: string): Promise<Rillet.JournalEntry | null> {+ return this.readEntity<Rillet.JournalEntry>(+ `/journal-entries/${id}`,+ "journal_entry"+ );+ }++ /**+ * Create a Rillet journal entry. No update counterpart: pushed journals+ * are immutable (the journal syncer hard-skips already-mapped ids).+ */+ async createJournalEntry(+ journalEntry: RilletJournalEntryCreate,+ idempotencyKey?: string+ ): Promise<Rillet.JournalEntry> {+ return this.writeEntity({+ method: "POST",+ path: "/journal-entries",+ envelopeKey: "journal_entry",+ operation: "create journal entry",+ payload: journalEntry,+ idempotencyKey+ });+ }++ async getCustomer(id: string): Promise<Rillet.Customer | null> {+ return this.readEntity<Rillet.Customer>(`/customers/${id}`, "customer");+ }++ async createCustomer(+ customer: RilletCustomerWrite,+ idempotencyKey?: string+ ): Promise<Rillet.Customer> {+ return this.writeEntity({+ method: "POST",+ path: "/customers",+ envelopeKey: "customer",+ operation: "create customer",+ payload: customer,+ idempotencyKey+ });+ }++ async updateCustomer(+ id: string,+ customer: RilletCustomerWrite+ ): Promise<Rillet.Customer> {+ return this.writeEntity({+ method: "PUT",+ path: `/customers/${id}`,+ envelopeKey: "customer",+ operation: "update customer",+ payload: customer+ });+ }++ async getVendor(id: string): Promise<Rillet.Vendor | null> {+ return this.readEntity<Rillet.Vendor>(`/vendors/${id}`, "vendor");+ }++ async createVendor(+ vendor: RilletVendorWrite,+ idempotencyKey?: string+ ): Promise<Rillet.Vendor> {+ return this.writeEntity({+ method: "POST",+ path: "/vendors",+ envelopeKey: "vendor",+ operation: "create vendor",+ payload: vendor,+ idempotencyKey+ });+ }++ async updateVendor(+ id: string,+ vendor: RilletVendorWrite+ ): Promise<Rillet.Vendor> {+ return this.writeEntity({+ method: "PUT",+ path: `/vendors/${id}`,+ envelopeKey: "vendor",+ operation: "update vendor",+ payload: vendor+ });+ }++ async getProduct(id: string): Promise<Rillet.Product | null> {+ return this.readEntity<Rillet.Product>(`/products/${id}`, "product");+ }++ async createProduct(+ product: RilletProductWrite,+ idempotencyKey?: string+ ): Promise<Rillet.Product> {+ return this.writeEntity({+ method: "POST",+ path: "/products",+ envelopeKey: "product",+ operation: "create product",+ payload: product,+ idempotencyKey+ });+ }++ async updateProduct(+ id: string,+ product: RilletProductWrite+ ): Promise<Rillet.Product> {+ return this.writeEntity({+ method: "PUT",+ path: `/products/${id}`,+ envelopeKey: "product",+ operation: "update product",+ payload: product+ });+ }++ async getInvoice(id: string): Promise<Rillet.Invoice | null> {+ return this.readEntity<Rillet.Invoice>(`/invoices/${id}`, "invoice");+ }++ /** Create an AR_ONLY invoice (Carbon invoices; Rillet carries the receivable). */+ async createInvoice(+ invoice: RilletInvoiceCreate,+ idempotencyKey?: string+ ): Promise<Rillet.Invoice> {+ return this.writeEntity({+ method: "POST",+ path: "/invoices",+ envelopeKey: "invoice",+ operation: "create invoice",+ payload: invoice,+ idempotencyKey+ });+ }++ async getBill(id: string): Promise<Rillet.Bill | null> {+ return this.readEntity<Rillet.Bill>(`/bills/${id}`, "bill");+ }++ async createBill(+ bill: RilletBillCreate,+ idempotencyKey?: string+ ): Promise<Rillet.Bill> {+ return this.writeEntity({+ method: "POST",+ path: "/bills",+ envelopeKey: "bill",+ operation: "create bill",+ payload: bill,+ idempotencyKey+ });+ }++ /**+ * Payments recorded against one invoice. Throws on API failure (unlike+ * the getX reads) — the payment pull needs to distinguish "invoice has+ * no such payment" from "the listing itself failed".+ */+ async listInvoicePayments(+ invoiceId: string+ ): Promise<Rillet.InvoicePayment[]> {+ const response = await this.request<{+ payments?: Rillet.InvoicePayment[];+ }>("GET", `/invoices/${invoiceId}/payments`);++ if (response.error) {+ throwRilletApiError("list invoice payments", response);+ }++ return response.data?.payments ?? [];+ }++ /**+ * All invoice payments in the organization changed since `updatedAfter`+ * (GET /invoice-payments — org-wide; no subsidiary or invoice filter+ * exists on this endpoint).+ */+ async listInvoicePaymentsUpdatedSince(+ updatedAfter: string+ ): Promise<Rillet.InvoicePayment[]> {+ return this.listPaginated<Rillet.InvoicePayment>(+ `/invoice-payments?updated.gt=${encodeURIComponent(+ updatedAfter+ )}&sort_by=updated`,+ (data) => data.payments as Rillet.InvoicePayment[] | undefined+ );+ }++ /**+ * Payments recorded against one bill (AP mirror of listInvoicePayments).+ * Throws on API failure so the pull can distinguish "bill has no such+ * payment" from "the listing itself failed".+ *+ * VERIFY: the `GET /bills/{billId}/payments` endpoint and its `{ payments:+ * [...] }` envelope are assumed to mirror `/invoices/{id}/payments`; not yet+ * confirmed against the live Rillet OpenAPI.+ */+ async listBillPayments(billId: string): Promise<Rillet.BillPayment[]> {+ const response = await this.request<{+ payments?: Rillet.BillPayment[];+ }>("GET", `/bills/${billId}/payments`);++ if (response.error) {+ throwRilletApiError("list bill payments", response);+ }++ return response.data?.payments ?? [];+ }++ /**+ * Bills changed since `updatedAfter` (VERIFIED on sandbox 2026-08-13:+ * `GET /bills?updated.gt` returns the `{ bills, pagination }` envelope,+ * accepts `sort_by=updated`, and paying a bill bumps its `updated_at` —+ * so the bill feed is a complete change signal for payment activity).+ */+ async listBillsUpdatedSince(updatedAfter: string): Promise<Rillet.Bill[]> {+ return this.listPaginated<Rillet.Bill>(+ `/bills?updated.gt=${encodeURIComponent(updatedAfter)}&sort_by=updated`,+ (data) => data.bills as Rillet.Bill[] | undefined+ );+ }++ /**+ * All bill payments in the organization changed since `updatedAfter`+ * (AP mirror of listInvoicePaymentsUpdatedSince).+ *+ * There is NO org-wide bill-payment feed: `GET /bill-payments` does not+ * exist (VERIFIED on sandbox 2026-08-13 — 404, which threw here and killed+ * every pull sweep). Composed instead from the two endpoints that do+ * exist: bills changed since the cursor (payment activity bumps the+ * bill's `updated_at`), then each changed bill's payments via+ * GET /bills/{id}/payments. Costs one extra request per changed bill,+ * bounded by the sweep window. Bill payments from the per-bill endpoint+ * carry no `updated_at` of their own, so each is stamped with its bill's+ * — the change signal that surfaced it.+ */+ async listBillPaymentsUpdatedSince(+ updatedAfter: string+ ): Promise<Rillet.BillPayment[]> {+ const bills = await this.listBillsUpdatedSince(updatedAfter);++ const payments: Rillet.BillPayment[] = [];+ for (const bill of bills) {+ const billPayments = await this.listBillPayments(bill.id);+ for (const payment of billPayments) {+ payments.push({+ ...payment,+ bill_id: payment.bill_id ?? bill.id,+ updated_at: payment.updated_at ?? bill.updated_at+ });+ }+ }+ return payments;+ }++ /**+ * Record a payment against one AR invoice (Phase G outbound write-back for a+ * Carbon-born payment). Returns the created Rillet payment so its id can seed+ * the composite mapping. Idempotency-Key protects against double-create on a+ * push retry (Rillet replays the stored response for 24h).+ *+ * Request body is FLAT (writeEntity never wraps requests; envelopeKey only+ * unwraps responses, and unwrapRilletEntity falls back to the flat object).+ * VERIFIED on the bill mirror (sandbox 2026-08-11): flat body with `date`+ * (not `payment_date`), flat response payment object. The invoice path is+ * assumed to mirror it; not separately confirmed.+ */+ async createInvoicePayment(+ invoiceId: string,+ payment: RilletPaymentCreate,+ idempotencyKey?: string+ ): Promise<Rillet.InvoicePayment> {+ return this.writeEntity({+ method: "POST",+ path: `/invoices/${invoiceId}/payments`,+ envelopeKey: "payment",+ operation: "create invoice payment",+ payload: payment,+ idempotencyKey+ });+ }++ /**+ * Record a payment against one AP bill (AP mirror of createInvoicePayment).+ *+ * VERIFIED (sandbox 2026-08-11): POST /bills/{id}/payments takes a FLAT+ * body `{ amount, date, account_code, external_references? }` — `payment_date`+ * 400s ("date must not be null") — and returns the created payment FLAT+ * (`{ id, status, bill_id, amount, date, account_code }`, status UNCLEARED);+ * unwrapRilletEntity's flat fallback handles it.+ */+ async createBillPayment(+ billId: string,+ payment: RilletPaymentCreate,+ idempotencyKey?: string+ ): Promise<Rillet.BillPayment> {+ return this.writeEntity({+ method: "POST",+ path: `/bills/${billId}/payments`,+ envelopeKey: "payment",+ operation: "create bill payment",+ payload: payment,+ idempotencyKey+ });+ }++ /**+ * SupportsIncrementalPull: invoice AND bill payments changed since `since`,+ * for the generic accounting-pull-sweep cron. Both feeds are organization-+ * wide while this instance owns one subsidiary, so every change carries a+ * dependsOnMapping on its document (invoice for AR, bill for AP) — the sweep+ * drops changes whose document has no local mapping (another instance's+ * subsidiary, or a document created directly in Rillet) without ledger noise.+ * Payments missing their document id cannot be addressed (composite id) and+ * are logged and dropped.+ */+ async listChanges(args: { since: string }): Promise<ListChangesResult> {+ const paymentConfig = this.getSyncConfig("payment");+ if (!paymentConfig.enabled) {+ return { changes: [] };+ }++ const changes: ProviderChange[] = [];++ // AR — invoice payments settle Carbon sales invoices.+ const invoicePayments = await this.listInvoicePaymentsUpdatedSince(+ args.since+ );+ for (const payment of invoicePayments) {+ if (!payment.invoice_id) {+ console.warn(+ `[Rillet] ignoring invoice payment ${payment.id} with no invoice_id`+ );+ continue;+ }+ changes.push({+ entityType: "payment",+ remoteId: getRilletPaymentSyncEntityId(payment.invoice_id, payment.id),+ updatedAt: payment.updated_at ?? null,+ dependsOnMapping: {+ entityType: "invoice",+ remoteId: payment.invoice_id+ }+ });+ }++ // AP — bill payments settle Carbon purchase invoices. Poll is the+ // correctness guarantee: Rillet documents no bill-payment webhook event+ // (only bill-created/updated/deleted), so this feed is the only mechanism.+ const billPayments = await this.listBillPaymentsUpdatedSince(args.since);+ for (const payment of billPayments) {+ if (!payment.bill_id) {+ console.warn(+ `[Rillet] ignoring bill payment ${payment.id} with no bill_id`+ );+ continue;+ }+ changes.push({+ entityType: "payment",+ remoteId: getRilletBillPaymentSyncEntityId(payment.bill_id, payment.id),+ updatedAt: payment.updated_at ?? null,+ dependsOnMapping: {+ entityType: "bill",+ remoteId: payment.bill_id+ }+ });+ }++ return { changes };+ }+}diff --git a/packages/ee/src/accounting/providers/rillet/webhook.ts b/packages/ee/src/accounting/providers/rillet/webhook.tsnew file mode 100644index 0000000000..1fbaa2e838--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/webhook.ts@@ -0,0 +1,69 @@+import { createHmac, timingSafeEqual } from "node:crypto";++/**+ * Rillet webhook delivery headers. Every delivery carries all five; the+ * signature covers the dot-joined values of the other four plus the raw+ * body.+ */+export type RilletWebhookHeaders = {+ /** X-Rillet-Signature — base64 HMAC-SHA256, possibly comma-separated (token rotation, up to 10). */+ signature: string;+ /** X-Rillet-Timestamp — ISO-8601 dispatch time. */+ timestamp: string;+ /** X-Rillet-Id — unique delivery UUID (idempotency). */+ id: string;+ /** X-Rillet-Entity — object type, e.g. "invoice". */+ entity: string;+ /** X-Rillet-Event — action type, e.g. "payment-updated". */+ event: string;+};++/** The exact byte string Rillet signs: `$timestamp.$id.$entity.$event.$body`. */+export function buildRilletSignedPayload(+ headers: Omit<RilletWebhookHeaders, "signature">,+ body: string+): string {+ return `${headers.timestamp}.${headers.id}.${headers.entity}.${headers.event}.${body}`;+}++/**+ * Verify a Rillet webhook delivery against the per-webhook token+ * (base64-encoded, from Rillet → Organization Settings → Webhooks).+ *+ * The signature header may contain up to 10 comma-separated signatures+ * (token rotation); the delivery is valid if ANY matches. Comparison is+ * constant-time per candidate.+ */+export function verifyRilletWebhookSignature(args: {+ headers: RilletWebhookHeaders;+ body: string;+ token: string;+}): boolean {+ const { headers, body, token } = args;+ if (!headers.signature || !token) return false;++ let expected: Buffer;+ try {+ expected = createHmac("sha256", Buffer.from(token, "base64"))+ .update(buildRilletSignedPayload(headers, body))+ .digest();+ } catch {+ return false;+ }++ return headers.signature+ .split(",")+ .slice(0, 10)+ .some((candidate) => {+ let provided: Buffer;+ try {+ provided = Buffer.from(candidate.trim(), "base64");+ } catch {+ return false;+ }+ return (+ provided.length === expected.length &&+ timingSafeEqual(provided, expected)+ );+ });+}diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/bill.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/bill.test.tsnew file mode 100644index 0000000000..3cc9f5dd28--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/bill.test.ts@@ -0,0 +1,296 @@+import { describe, expect, it } from "vitest";+import type { CostingLine } from "../../../../core/document-costing";+import { JournalEntrySyncError } from "../../../../core/posting";+import type { Accounting } from "../../../../core/types";+import type { Xero } from "../../models";+import { BillSyncer, buildXeroBillLineItems } from "../bill";++/**+ * Xero ACCPAY bills are an account-costed replay of the posted Purchase+ * Invoice journal: AccountCode = the journal's mapped account, tax-neutral+ * (TaxType NONE), transaction-currency amounts with CurrencyRate pinned.+ */++const CODES: ReadonlyMap<string, string> = new Map([+ ["acct_grir", "2125"],+ ["acct_ppv", "5210"]+]);++const bill = (overrides: Partial<Accounting.Bill> = {}): Accounting.Bill =>+ ({+ id: "pi_1",+ companyId: "company-1",+ invoiceId: "AP000001",+ supplierId: "sup_1",+ supplierExternalId: "contact-1",+ status: "Pending",+ dateIssued: "2026-08-04",+ dateDue: null,+ datePaid: null,+ currencyCode: "USD",+ exchangeRate: 1,+ subtotal: 300,+ totalTax: 0,+ totalDiscount: 0,+ totalAmount: 300,+ balance: 300,+ supplierReference: null,+ lines: [],+ updatedAt: "2026-08-04T00:00:00.000Z",+ ...overrides+ }) as unknown as Accounting.Bill;++describe("buildXeroBillLineItems (account-costed journal replay)", () => {+ it("maps to the journal account codes, TaxType NONE, item label, ItemCode only for known-non-tracked", () => {+ const costingLines: CostingLine[] = [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 280,+ description: "GR/IR Clearing",+ sourceItem: { id: "item-1", code: "WIDGET-1", name: "Widget" }+ },+ {+ id: "jl-2",+ accountId: "acct_ppv",+ amount: 20,+ description: "Purchase Price Variance"+ }+ ];++ const lines = buildXeroBillLineItems({+ bill: bill(),+ costingLines,+ accountCodesById: CODES,+ nonTrackedItemIds: new Set(["item-1"])+ });++ expect(lines).toEqual([+ {+ Description: "WIDGET-1 Widget",+ LineAmount: 280,+ AccountCode: "2125",+ TaxType: "NONE",+ ItemCode: "WIDGET-1"+ },+ {+ Description: "Purchase Price Variance",+ LineAmount: 20,+ AccountCode: "5210",+ TaxType: "NONE"+ }+ ]);+ });++ it("omits ItemCode when the item is not known non-tracked", () => {+ const lines = buildXeroBillLineItems({+ bill: bill(),+ costingLines: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 280,+ description: "GR/IR",+ sourceItem: { id: "item-1", code: "WIDGET-1", name: "Widget" }+ }+ ],+ accountCodesById: CODES+ // nonTrackedItemIds omitted → nothing known non-tracked+ });+ expect("ItemCode" in lines[0]!).toBe(false);+ });++ it("passes a negative (credit PPV) line through", () => {+ const lines = buildXeroBillLineItems({+ bill: bill(),+ costingLines: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR"+ },+ { id: "jl-2", accountId: "acct_ppv", amount: -20, description: "PPV" }+ ],+ accountCodesById: CODES+ });+ expect(lines[1]?.LineAmount).toBe(-20);+ });++ it("warns (UNMAPPED_ACCOUNTS) on an unmapped account", () => {+ try {+ buildXeroBillLineItems({+ bill: bill(),+ costingLines: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR"+ }+ ],+ accountCodesById: new Map()+ });+ expect.unreachable("should have thrown");+ } catch (error) {+ const failure = (error as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(failure.warning).toBe(true);+ }+ });++ it("warns when the bill has no posted journal", () => {+ expect(() =>+ buildXeroBillLineItems({+ bill: bill(),+ costingLines: [],+ accountCodesById: CODES+ })+ ).toThrowError(JournalEntrySyncError);+ });+});++// Table-dispatching Kysely fake for the mapToRemote drive.+function makeBillDb(config: {+ purchaseInvoice: { currencyCode: string; exchangeRate: number };+ journalLine: Array<{+ id: string;+ accountId: string | null;+ amount: number;+ description: string | null;+ documentLineReference: string | null;+ accountClass: string | null;+ }>;+ accountDefault: { payablesAccount: string | null };+ accountMappings: Array<{+ id: string;+ accountId: string;+ externalId: string | null;+ metadata: unknown;+ lastSyncedAt: string | null;+ accountNumber: string | null;+ accountName: string | null;+ }>;+}) {+ const makeBuilder = (table: string) => {+ const builder: any = {+ select: () => builder,+ innerJoin: () => builder,+ leftJoin: () => builder,+ where: () => builder,+ orderBy: () => builder,+ async execute() {+ if (table === "journalLine") return config.journalLine;+ if (table === "journalLineDimension") return [];+ if (table === "purchaseOrderLine") return [];+ if (table === "externalIntegrationMapping as m")+ return config.accountMappings;+ return [];+ },+ async executeTakeFirst() {+ if (table === "purchaseInvoice") return config.purchaseInvoice;+ if (table === "accountDefault") return config.accountDefault;+ return undefined;+ }+ };+ return builder;+ };+ return { selectFrom: (t: string) => makeBuilder(t) } as never;+}++function makeBillSyncer(db: never, remoteId: string | null) {+ const syncer = new BillSyncer({+ database: db,+ companyId: "company-1",+ provider: { id: "xero", settings: {} } as never,+ config: { enabled: true, direction: "two-way", owner: "accounting" },+ entityType: "bill"+ });+ (syncer as unknown as Record<string, unknown>).getRemoteId = async () =>+ remoteId;+ return syncer as unknown as {+ mapToRemote(local: Accounting.Bill): Promise<Xero.Invoice>;+ shouldSync(context: {+ direction: "push" | "pull";+ localEntity: Accounting.Bill;+ }): boolean | string;+ };+}++describe("BillSyncer.mapToRemote (FX + guards)", () => {+ const fxDb = () =>+ makeBillDb({+ purchaseInvoice: { currencyCode: "EUR", exchangeRate: 2 },+ journalLine: [+ {+ id: "jl-1",+ accountId: "acct_grir",+ amount: 300,+ description: "GR/IR Clearing",+ documentLineReference: null,+ accountClass: "Asset"+ },+ {+ id: "jl-2",+ accountId: "acct_ap",+ amount: 300,+ description: "Accounts Payable",+ documentLineReference: null,+ accountClass: "Liability"+ }+ ],+ accountDefault: { payablesAccount: "acct_ap" },+ accountMappings: [+ {+ id: "m-1",+ accountId: "acct_grir",+ externalId: "grir-remote",+ metadata: { externalCode: "2125" },+ lastSyncedAt: null,+ accountNumber: "2125",+ accountName: "GR/IR Clearing"+ }+ ]+ });++ it("pins CurrencyRate and replays transaction-currency amounts (AP excluded)", async () => {+ const payload = await makeBillSyncer(fxDb(), null).mapToRemote(+ bill({ currencyCode: "EUR", exchangeRate: 2 })+ );++ expect(payload.CurrencyCode).toBe("EUR");+ expect(payload.CurrencyRate).toBe(2);+ expect(payload.LineItems).toEqual([+ {+ Description: "GR/IR Clearing",+ LineAmount: 150,+ AccountCode: "2125",+ TaxType: "NONE"+ }+ ]);+ // Tax-neutral replay: no totals sent (Xero computes from NONE-taxed lines).+ expect(payload.SubTotal).toBeUndefined();+ expect(payload.TotalTax).toBeUndefined();+ });++ it("lands a DOC_HAS_PAYMENTS Warning when re-pushing a paid bill", async () => {+ try {+ await makeBillSyncer(fxDb(), "xero-bill-1").mapToRemote(+ bill({ status: "Paid" })+ );+ expect.unreachable("should have thrown");+ } catch (error) {+ const failure = (error as JournalEntrySyncError).failure;+ expect(failure.errorCode).toBe("DOC_HAS_PAYMENTS");+ expect(failure.warning).toBe(true);+ }+ });++ it("skips a Draft bill in shouldSync", () => {+ const result = makeBillSyncer(fxDb(), null).shouldSync({+ direction: "push",+ localEntity: bill({ status: "Draft" })+ });+ expect(result).toContain("must be posted");+ });+});diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/invoice.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/invoice.test.tsnew file mode 100644index 0000000000..d24c8e1175--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/invoice.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it } from "vitest";+import type { Accounting } from "../../../../core/types";+import type { Xero } from "../../models";+import { SalesInvoiceSyncer } from "../invoice";++/**+ * Item-referenced AR invoices post to the item's mapped REVENUE account+ * (accountDefault.salesAccount → account-mapping externalCode) — the same+ * resolution that feeds Rillet's product account_code and QBO's+ * IncomeAccountRef. There is no blunt default-account-code fallback: when+ * the company default is unset or unmapped, mapToRemote throws the+ * structured UNMAPPED_ACCOUNTS Warning instead. COGS stays on the shipment+ * journal.+ */++const invoice = (): Accounting.SalesInvoice =>+ ({+ id: "si_1",+ invoiceId: "INV000001",+ companyId: "company-1",+ customerId: "cust-1",+ customerExternalId: null,+ status: "Pending",+ currencyCode: "USD",+ exchangeRate: 1,+ dateIssued: "2026-08-04",+ dateDue: null,+ datePaid: null,+ customerReference: null,+ subtotal: 100,+ totalTax: 0,+ totalDiscount: 0,+ totalAmount: 100,+ balance: 100,+ lines: [+ {+ id: "sil-1",+ invoiceLineType: "Part",+ itemId: "item-1",+ itemCode: "WIDGET-1",+ description: "Widget",+ quantity: 2,+ unitPrice: 50,+ taxPercent: 0,+ lineAmount: 100+ }+ ],+ updatedAt: "2026-08-04T00:00:00.000Z"+ }) as unknown as Accounting.SalesInvoice;++function makeInvoiceDb(config: {+ accountDefault: { salesAccount: string | null };+ accountMappings: Array<{+ id: string;+ accountId: string;+ externalId: string | null;+ metadata: unknown;+ lastSyncedAt: string | null;+ accountNumber: string | null;+ accountName: string | null;+ }>;+}) {+ const makeBuilder = (table: string) => {+ const builder: any = {+ select: () => builder,+ innerJoin: () => builder,+ leftJoin: () => builder,+ where: () => builder,+ orderBy: () => builder,+ async execute() {+ if (table === "externalIntegrationMapping as m")+ return config.accountMappings;+ return [];+ },+ async executeTakeFirst() {+ if (table === "accountDefault") return config.accountDefault;+ return undefined;+ }+ };+ return builder;+ };+ return { selectFrom: (t: string) => makeBuilder(t) } as never;+}++function makeInvoiceSyncer(db: never) {+ const syncer = new SalesInvoiceSyncer({+ database: db,+ companyId: "company-1",+ provider: {+ id: "xero"+ } as never,+ config: { enabled: true, direction: "two-way", owner: "carbon" },+ entityType: "invoice"+ });+ (syncer as unknown as Record<string, unknown>).getRemoteId = async () => null;+ (syncer as unknown as Record<string, unknown>).ensureDependencySynced =+ async (type: string) => `${type}-remote`;+ return syncer as unknown as {+ mapToRemote(local: Accounting.SalesInvoice): Promise<Xero.Invoice>;+ };+}++describe("SalesInvoiceSyncer.mapToRemote (item revenue account)", () => {+ it("posts to the mapped sales account", async () => {+ const payload = await makeInvoiceSyncer(+ makeInvoiceDb({+ accountDefault: { salesAccount: "acct_sales" },+ accountMappings: [+ {+ id: "m-1",+ accountId: "acct_sales",+ externalId: "sales-remote",+ metadata: { externalCode: "4000" },+ lastSyncedAt: null,+ accountNumber: "4000",+ accountName: "Sales Revenue"+ }+ ]+ })+ ).mapToRemote(invoice());++ expect(payload.LineItems[0]?.AccountCode).toBe("4000");+ // Item still referenced; tax handling unchanged (Exclusive + NONE at 0 tax).+ expect(payload.LineItems[0]?.ItemCode).toBe("WIDGET-1");+ expect(payload.LineItems[0]?.TaxType).toBe("NONE");+ expect(payload.LineAmountTypes).toBe("Exclusive");+ });++ it("throws the structured UNMAPPED_ACCOUNTS warning when the company has no default sales account", async () => {+ const syncer = makeInvoiceSyncer(+ makeInvoiceDb({+ accountDefault: { salesAccount: null },+ accountMappings: []+ })+ );++ await expect(syncer.mapToRemote(invoice())).rejects.toMatchObject({+ name: "JournalEntrySyncError",+ failure: expect.objectContaining({ errorCode: "UNMAPPED_ACCOUNTS" })+ });+ });++ it("throws the structured UNMAPPED_ACCOUNTS warning when the default sales account has no Xero mapping", async () => {+ const syncer = makeInvoiceSyncer(+ makeInvoiceDb({+ accountDefault: { salesAccount: "acct_sales" },+ accountMappings: []+ })+ );++ await expect(syncer.mapToRemote(invoice())).rejects.toMatchObject({+ name: "JournalEntrySyncError",+ failure: expect.objectContaining({ errorCode: "UNMAPPED_ACCOUNTS" })+ });+ });+});diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/item.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/item.test.tsnew file mode 100644index 0000000000..68dcdbf00a--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/item.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it, vi } from "vitest";+import type { Accounting } from "../../../../core/types";+import type { Xero } from "../../models";+import { ItemSyncer } from "../item";++/**+ * Xero items are pushed NON-TRACKED so the provider never books inventory+ * (bills) or COGS (invoices) — per-SKU valuation stays in Carbon. On create+ * we force `IsTrackedAsInventory: false`; on update we OMIT it (Xero rejects+ * untracking an item with stock/transactions) and warn if the remote is still+ * tracked.+ */++const item = (overrides: Partial<Accounting.Item> = {}): Accounting.Item =>+ ({+ id: "item-1",+ code: "WIDGET-1",+ name: "Widget",+ description: "A widget",+ companyId: "company-1",+ type: "Part",+ unitOfMeasureCode: "EA",+ unitCost: 10,+ unitSalePrice: 25,+ isPurchased: true,+ isSold: true,+ isTrackedAsInventory: true,+ updatedAt: "2026-08-04T00:00:00.000Z",+ ...overrides+ }) as unknown as Accounting.Item;++function makeItemSyncer(+ remoteId: string | null,+ remote?: Partial<Xero.Item> | null+) {+ const syncer = new ItemSyncer({+ database: {} as never,+ companyId: "company-1",+ provider: { id: "xero" } as never,+ config: { enabled: true, direction: "two-way", owner: "carbon" },+ entityType: "item"+ });+ (syncer as unknown as Record<string, unknown>).getRemoteId = async () =>+ remoteId;+ (syncer as unknown as Record<string, unknown>).fetchRemote = async () =>+ remote ?? null;+ return syncer as unknown as {+ mapToRemote(local: Accounting.Item): Promise<Xero.Item>;+ };+}++describe("Xero ItemSyncer.mapToRemote (non-tracked representation)", () => {+ it("forces IsTrackedAsInventory: false on create", async () => {+ const payload = await makeItemSyncer(null).mapToRemote(item());+ expect(payload.IsTrackedAsInventory).toBe(false);+ expect(payload.Code).toBe("WIDGET-1");+ });++ it("omits IsTrackedAsInventory on update (non-tracked remote)", async () => {+ const payload = await makeItemSyncer("xero-item-1", {+ ItemID: "xero-item-1",+ IsTrackedAsInventory: false+ }).mapToRemote(item());+ expect("IsTrackedAsInventory" in payload).toBe(false);+ });++ it("warns (and still omits the field) when the remote item is still tracked", async () => {+ const warnSpy = vi+ .spyOn(console, "warn")+ .mockImplementation(() => undefined);++ const payload = await makeItemSyncer("xero-item-1", {+ ItemID: "xero-item-1",+ IsTrackedAsInventory: true+ }).mapToRemote(item());++ expect("IsTrackedAsInventory" in payload).toBe(false);+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining("still tracked as inventory")+ );+ warnSpy.mockRestore();+ });+});diff --git a/packages/ee/src/accounting/providers/xero/entities/__tests__/payment.test.ts b/packages/ee/src/accounting/providers/xero/entities/__tests__/payment.test.tsnew file mode 100644index 0000000000..a28f9c0490--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/entities/__tests__/payment.test.ts@@ -0,0 +1,313 @@+import { describe, expect, it, vi } from "vitest";+import type { NormalizedPayment } from "../../../../core/payment-application";+import { SyncFactory } from "../../../../core/sync";+import type { Xero } from "../../models";+// Importing the provider barrel registers the Xero syncer registry (side+// effect) so SyncFactory.getSyncer can resolve `payment`.+import "../../index";+import {+ getXeroBillPaymentSyncEntityId,+ getXeroPaymentDate,+ getXeroPaymentSyncEntityId,+ parseXeroPaymentSyncEntityId,+ XeroPaymentSyncer+} from "../payment";++// The base dynamically imports @carbon/auth/client.server only when posting;+// mock it so nothing touches server env during these pure-mapper tests.+vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: () => ({ functions: { invoke: vi.fn() } })+}));++describe("composite payment sync entity id (Xero)", () => {+ it("round-trips invoice + payment ids as a prefix-less AR id", () => {+ const entityId = getXeroPaymentSyncEntityId("inv-remote-1", "pay-1");+ expect(entityId).toBe("inv-remote-1:pay-1");+ expect(parseXeroPaymentSyncEntityId(entityId)).toEqual({+ family: "ar",+ documentRemoteId: "inv-remote-1",+ paymentRemoteId: "pay-1"+ });+ });++ it("round-trips bill + payment ids as a `bill:`-prefixed AP id", () => {+ const entityId = getXeroBillPaymentSyncEntityId("bill-remote-1", "pay-2");+ expect(entityId).toBe("bill:bill-remote-1:pay-2");+ expect(parseXeroPaymentSyncEntityId(entityId)).toEqual({+ family: "ap",+ documentRemoteId: "bill-remote-1",+ paymentRemoteId: "pay-2"+ });+ });++ it("throws on malformed ids (both families)", () => {+ expect(() => parseXeroPaymentSyncEntityId("no-separator")).toThrow(+ /Invalid Xero payment sync entity id/+ );+ expect(() => parseXeroPaymentSyncEntityId(":pay-1")).toThrow(+ /Invalid Xero payment sync entity id/+ );+ expect(() => parseXeroPaymentSyncEntityId("inv-1:")).toThrow(+ /Invalid Xero payment sync entity id/+ );+ expect(() => parseXeroPaymentSyncEntityId("bill:no-separator")).toThrow(+ /Invalid Xero payment sync entity id/+ );+ });+});++describe("getXeroPaymentDate", () => {+ it("takes the YYYY-MM-DD part of a plain date", () => {+ expect(getXeroPaymentDate("2026-08-01")).toBe("2026-08-01");+ expect(getXeroPaymentDate("2026-08-01T00:00:00")).toBe("2026-08-01");+ });++ it("parses a serialized .NET date defensively", () => {+ // 2026-08-01T00:00:00Z = 1785542400000 ms+ expect(getXeroPaymentDate("/Date(1785542400000+0000)/")).toBe("2026-08-01");+ });+});++function makeMapperSyncer() {+ const syncer = new XeroPaymentSyncer({+ database: {} as never,+ companyId: "company-1",+ provider: { id: "xero" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ return syncer as unknown as {+ mapToNormalized(remote: Xero.Payment, entityId: string): NormalizedPayment;+ };+}++describe("XeroPaymentSyncer.mapToNormalized", () => {+ it("normalizes an ACCPAY (bill) payment to a settled AP NormalizedPayment", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ PaymentID: "pay-1",+ Amount: 500,+ Date: "2026-08-01",+ Status: "AUTHORISED",+ PaymentType: "ACCPAYPAYMENT",+ Invoice: {+ InvoiceID: "bill-remote-1",+ Type: "ACCPAY",+ CurrencyCode: "USD"+ },+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ },+ "bill:bill-remote-1:pay-1"+ );++ expect(normalized).toEqual({+ family: "ap",+ documentRemoteId: "bill-remote-1",+ paymentRemoteId: "pay-1",+ amount: 500,+ currencyCode: "USD",+ exchangeRate: 1,+ paidDate: "2026-08-01",+ reference: "pay-1",+ status: "settled"+ });+ });++ it("normalizes an ACCREC (sales invoice) payment to a settled AR NormalizedPayment", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ PaymentID: "pay-2",+ Amount: 125,+ Date: "2026-07-15T00:00:00",+ Status: "AUTHORISED",+ PaymentType: "ACCRECPAYMENT",+ CurrencyRate: 1.1,+ Invoice: {+ InvoiceID: "inv-remote-1",+ Type: "ACCREC",+ CurrencyCode: "EUR"+ },+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ },+ "inv-remote-1:pay-2"+ );++ expect(normalized).toEqual({+ family: "ar",+ documentRemoteId: "inv-remote-1",+ paymentRemoteId: "pay-2",+ amount: 125,+ currencyCode: "EUR",+ exchangeRate: 1.1,+ paidDate: "2026-07-15",+ reference: "pay-2",+ status: "settled"+ });+ });++ it("maps a DELETED payment to void (the reverse path)", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ PaymentID: "pay-3",+ Amount: 500,+ Date: "2026-08-02",+ Status: "DELETED",+ Invoice: { InvoiceID: "bill-remote-1", Type: "ACCPAY" },+ UpdatedDateUTC: "/Date(1785628800000+0000)/"+ },+ "bill:bill-remote-1:pay-3"+ );+ expect(normalized.status).toBe("void");+ expect(normalized.family).toBe("ap");+ expect(normalized.documentRemoteId).toBe("bill-remote-1");+ });++ it("carries a partial-payment amount through unchanged", () => {+ const normalized = makeMapperSyncer().mapToNormalized(+ {+ PaymentID: "pay-4",+ Amount: 40,+ Date: "2026-08-03",+ Status: "AUTHORISED",+ Invoice: { InvoiceID: "inv-remote-1", Type: "ACCREC" },+ UpdatedDateUTC: "/Date(1785715200000+0000)/"+ },+ "inv-remote-1:pay-4"+ );+ expect(normalized.amount).toBe(40);+ expect(normalized.currencyCode).toBeNull();+ expect(normalized.exchangeRate).toBe(1);+ });+});++// Fake Kysely db answering only the documents-mode gate's metadata read.+// `metadata` undefined = no row (gate resolves to defaults = documents).+function makeMetadataDb(metadata: unknown) {+ const chain: any = {+ select: () => chain,+ where: () => chain,+ executeTakeFirst: async () =>+ metadata === undefined ? undefined : { metadata }+ };+ return { selectFrom: () => chain } as never;+}++function familyModeMetadata(family: "ar" | "ap", mode: string) {+ return { settings: { postingSync: { families: { [family]: mode } } } };+}++describe("XeroPaymentSyncer.shouldSync ownership gate", () => {+ function makeSyncer(mappedDocId: string | null, metadata?: unknown) {+ const syncer = new XeroPaymentSyncer({+ database: makeMetadataDb(metadata),+ companyId: "company-1",+ provider: { id: "xero" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ (syncer as unknown as Record<string, unknown>).mappingService = {+ getEntityId: async () => mappedDocId+ };+ return syncer as unknown as {+ shouldSync(context: {+ direction: "push" | "pull";+ remoteEntity?: Xero.Payment;+ isFirstSync: boolean;+ entityId: string;+ }): Promise<boolean | string>;+ };+ }++ it("skips (does not fail) when the AP family is not in documents mode", async () => {+ const result = await makeSyncer(+ "purchase-invoice-1",+ familyModeMetadata("ap", "journals")+ ).shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:pay-1",+ remoteEntity: {+ PaymentID: "pay-1",+ Status: "AUTHORISED",+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ },+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("payment sync-back is disabled");+ expect(result).toContain("ap");+ });++ it("skips (does not fail) an AP payment on a bill with no local mapping", async () => {+ const result = await makeSyncer(null).shouldSync({+ direction: "pull",+ entityId: "bill:bill-other:pay-1",+ isFirstSync: true+ });+ expect(typeof result).toBe("string");+ expect(result).toContain("no Carbon mapping");+ expect(result).toContain("bill");+ });++ it("skips an AR payment on an invoice with no local mapping", async () => {+ const result = await makeSyncer(null).shouldSync({+ direction: "pull",+ entityId: "inv-other:pay-1",+ isFirstSync: true+ });+ expect(result).toContain("no Carbon mapping");+ expect(result).toContain("invoice");+ });++ it("proceeds for a payment on a locally-mapped document", async () => {+ const result = await makeSyncer("purchase-invoice-1").shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:pay-1",+ remoteEntity: {+ PaymentID: "pay-1",+ Status: "AUTHORISED",+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ },+ isFirstSync: true+ });+ expect(result).toBe(true);+ });++ it("skips a first-seen DELETED (void) payment on a mapped document", async () => {+ const result = await makeSyncer("purchase-invoice-1").shouldSync({+ direction: "pull",+ entityId: "bill:bill-ours:pay-1",+ remoteEntity: {+ PaymentID: "pay-1",+ Status: "DELETED",+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ },+ isFirstSync: true+ });+ expect(result).toContain("never recorded");+ });+});++describe("Xero payment syncer registration", () => {+ it("resolves via SyncFactory.getSyncer({provider:'xero', entityType:'payment'})", () => {+ const syncer = SyncFactory.getSyncer({+ database: {} as never,+ companyId: "company-1",+ provider: { id: "xero" } as never,+ config: {+ enabled: true,+ direction: "pull-from-accounting",+ owner: "accounting"+ },+ entityType: "payment"+ });+ expect(syncer).toBeInstanceOf(XeroPaymentSyncer);+ });+});diff --git a/packages/ee/src/accounting/providers/xero/entities/bill.ts b/packages/ee/src/accounting/providers/xero/entities/bill.tsindex 7221b5045f..7b7b841503 100644--- a/packages/ee/src/accounting/providers/xero/entities/bill.ts+++ b/packages/ee/src/accounting/providers/xero/entities/bill.ts@@ -1,16 +1,22 @@import type { KyselyTx } from "@carbon/database/client";import { sql } from "kysely";+import { loadAccountCodesById } from "../../../core/account-mapping";+import {+ type CostingLine,+ costingLineItemLabel,+ loadBillCostingLines,+ toTransactionCurrencyLines+} from "../../../core/document-costing";import { createMappingService } from "../../../core/external-mapping";-import { type Accounting, BaseEntitySyncer } from "../../../core/types";+import { JournalEntrySyncError, roundCurrency } from "../../../core/posting";+import {+ type Accounting,+ BaseEntitySyncer,+ type ShouldSyncContext+} from "../../../core/types";import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";import type { XeroProvider } from "../provider";-import {- xeroCurrencyRate,- xeroMoney,- xeroQuantity,- xeroUnitAmount-} from "../serialize";// Note: This syncer uses the default ID mapping from BaseEntitySyncer// which uses the externalIntegrationMapping table with entityType "bill"@@ -88,11 +94,115 @@ const XERO_TO_CARBON_STATUS: Record<DELETED: "Voided"};+// Only posted bills are pushed (Draft has no journal to replay).+const SYNCABLE_STATUSES: Accounting.Bill["status"][] = [+ "Pending",+ "Open",+ "Return",+ "Debit Note Issued",+ "Partially Paid",+ "Paid",+ "Overdue"+];++// Xero rejects line edits on a bill that already carries payments.+const PAID_STATUSES: Accounting.Bill["status"][] = ["Paid", "Partially Paid"];++/**+ * Build Xero ACCPAY line items as an account-costed replay of the bill's+ * posted "Purchase Invoice" journal: `AccountCode` = the journal line's+ * mapped account (GR-IR / PPV / clearing), NOT the item's account and NOT the+ * blunt `defaultPurchaseAccountCode`. Tax-neutral (`TaxType: "NONE"`, no+ * `TaxAmount`) — the purchase posting folds tax into cost, so the replay+ * amounts already embed it. Pure — exported for tests. Amounts are already in+ * the invoice's transaction currency (`toTransactionCurrencyLines`).+ *+ * `ItemCode` is attached ONLY for items known non-tracked (`nonTrackedItemIds`)+ * — a tracked Xero item would make Xero override the AccountCode with the+ * item's inventory account and double-post inventory.+ *+ * Unmapped / account-less / no-journal lines throw the structured+ * UNMAPPED_ACCOUNTS Warning (user-fixable: map the account, then retry).+ */+export function buildXeroBillLineItems(args: {+ bill: Accounting.Bill;+ costingLines: CostingLine[];+ accountCodesById: ReadonlyMap<string, string>;+ nonTrackedItemIds?: ReadonlySet<string>;+}): Xero.InvoiceLineItem[] {+ const { bill } = args;++ if (args.costingLines.length === 0) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync bill ${bill.invoiceId}: no posted Purchase Invoice journal found — the bill's G/L costing comes from its posting journal. Post the invoice (with accounting enabled), then retry.`,+ warning: true,+ metadata: { billId: bill.id }+ });+ }++ const unmapped = new Set<string>();+ const lineIdsWithoutAccount: string[] = [];+ for (const line of args.costingLines) {+ if (!line.accountId) {+ lineIdsWithoutAccount.push(line.id);+ continue;+ }+ if (!args.accountCodesById.get(line.accountId)) {+ unmapped.add(line.accountId);+ }+ }++ if (unmapped.size > 0 || lineIdsWithoutAccount.length > 0) {+ const parts: string[] = [];+ if (unmapped.size > 0) {+ parts.push(`${unmapped.size} account(s) have no Xero account mapping`);+ }+ if (lineIdsWithoutAccount.length > 0) {+ parts.push(+ `${lineIdsWithoutAccount.length} posting journal line(s) have no account`+ );+ }+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `Cannot sync bill ${bill.invoiceId}: ${parts.join(+ "; "+ )}. Map the account(s) on the integration settings page, then retry.`,+ warning: true,+ metadata: {+ billId: bill.id,+ unmappedAccountIds: [...unmapped],+ ...(lineIdsWithoutAccount.length > 0 ? { lineIdsWithoutAccount } : {})+ }+ });+ }++ const nonTracked = args.nonTrackedItemIds;+ return args.costingLines.map((line) => {+ const attachItemCode =+ line.sourceItem && nonTracked?.has(line.sourceItem.id)+ ? line.sourceItem.code+ : null;+ return {+ Description: costingLineItemLabel(line) ?? line.description ?? undefined,+ LineAmount: roundCurrency(line.amount),+ AccountCode: args.accountCodesById.get(line.accountId!)!,+ TaxType: "NONE",+ ...(attachItemCode ? { ItemCode: attachItemCode.slice(0, 30) } : {})+ };+ });+}+export class BillSyncer extends BaseEntitySyncer<Accounting.Bill,Xero.Invoice,"UpdatedDateUTC"> {+ private accountCodesByIdPromise?: Promise<Map<string, string>>;+ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }+// =================================================================// 1. ID MAPPING - Uses default implementation from BaseEntitySyncer// The entityType "bill" maps to the purchaseInvoice table@@ -275,10 +385,9 @@ export class BillSyncer extends BaseEntitySyncer<// =================================================================async fetchRemote(id: string): Promise<Xero.Invoice | null> {- const result = await this.provider.request<{ Invoices: Xero.Invoice[] }>(- "GET",- `/Invoices/${id}`- );+ const result = await this.xeroProvider.request<{+ Invoices: Xero.Invoice[];+ }>("GET", `/Invoices/${id}`);if (result.error) return null;@@ -299,10 +408,9 @@ export class BillSyncer extends BaseEntitySyncer<const result = new Map<string, Xero.Invoice>();if (ids.length === 0) return result;- const response = await this.provider.request<{ Invoices: Xero.Invoice[] }>(- "GET",- `/Invoices?IDs=${ids.join(",")}`- );+ const response = await this.xeroProvider.request<{+ Invoices: Xero.Invoice[];+ }>("GET", `/Invoices?IDs=${ids.join(",")}`);if (response.error) {throwXeroApiError("fetch bills batch", response);@@ -320,7 +428,43 @@ export class BillSyncer extends BaseEntitySyncer<}// =================================================================- // 5. TRANSFORMATION (Carbon -> Xero)+ // SHOULD SYNC (posted-bill gate on push)+ // =================================================================++ protected shouldSync(+ context: ShouldSyncContext<Accounting.Bill, Xero.Invoice>+ ): boolean | string {+ if (context.direction === "push" && context.localEntity) {+ if (!SYNCABLE_STATUSES.includes(context.localEntity.status)) {+ return `Bill must be posted before syncing (current status: ${context.localEntity.status})`;+ }+ }++ return true;+ }++ private getAccountCodesById(): Promise<Map<string, string>> {+ if (!this.accountCodesByIdPromise) {+ this.accountCodesByIdPromise = loadAccountCodesById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountCodesByIdPromise;+ }++ /** accountDefault.payablesAccount — the AP control line to exclude. */+ private async getPayablesAccountId(): Promise<string | null> {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select("payablesAccount")+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();+ return defaults?.payablesAccount ?? null;+ }++ // =================================================================+ // 5. TRANSFORMATION (Carbon -> Xero) — account-costed journal replay// =================================================================protected async mapToRemote(@@ -328,6 +472,18 @@ export class BillSyncer extends BaseEntitySyncer<): Promise<Omit<Xero.Invoice, "UpdatedDateUTC">> {const existingRemoteId = await this.getRemoteId(local.id);+ // Paid-doc guard: Xero rejects line-item edits to a bill that already+ // carries payments — surface a Warning instead of pushing a line rewrite+ // (forward-only; the operator voids/unapplies the payment to re-push).+ if (existingRemoteId && PAID_STATUSES.includes(local.status)) {+ throw new JournalEntrySyncError({+ errorCode: "DOC_HAS_PAYMENTS",+ message: `Cannot re-push bill ${local.invoiceId} to Xero: it is ${local.status} and Xero rejects edits to a bill with payments. Void/unapply the payment in Xero, then retry (or leave it — the original push already reflects Carbon's journal).`,+ warning: true,+ metadata: { billId: local.id, status: local.status }+ });+ }+// Get supplier's Xero ContactID - ensure supplier is synced firstlet contactId = local.supplierExternalId;if (!contactId && local.supplierId) {@@ -340,54 +496,35 @@ export class BillSyncer extends BaseEntitySyncer<);}- // Get default account code from provider settings- const xeroProvider = this.provider as XeroProvider;- const defaultAccountCode =- xeroProvider.settings?.defaultPurchaseAccountCode;-- // Map line items- const lineItems: Xero.InvoiceLineItem[] = await Promise.all(- local.lines.map(async (line) => {- let itemCode = line.itemCode;-- // If we have an itemId but no itemCode, try to get it from the item table- if (!itemCode && line.itemId) {- const item = await this.database- .selectFrom("item")- .select("readableId")- .where("id", "=", line.itemId)- .executeTakeFirst();- itemCode = item?.readableId ?? null;- }-- // Embed PO line reference in description for later extraction- let description = line.description ?? undefined;- if (line.purchaseOrderLineId) {- const ref = `[ref:${line.purchaseOrderLineId}]`;- description = description ? `${description} ${ref}` : ref;- }-- // Determine if line has tax- const hasTax =- (line.taxPercent != null && line.taxPercent > 0) ||- (line.taxAmount != null && line.taxAmount > 0);+ // Account-costed replay of the bill's posted Purchase Invoice journal.+ const payablesAccountId = await this.getPayablesAccountId();+ const accountCodesById = await this.getAccountCodesById();+ const {+ lines: costingLines,+ currencyCode,+ exchangeRate+ } = await loadBillCostingLines(this.database, {+ companyId: this.companyId,+ billId: local.id,+ payablesAccountId+ });- return {- Description: description,- Quantity: xeroQuantity(line.quantity),- UnitAmount: xeroUnitAmount(line.unitPrice),- ItemCode: itemCode?.slice(0, 30) ?? undefined,- // Use line's account number if specified, otherwise use default from settings- AccountCode: line.accountNumber ?? defaultAccountCode,- TaxAmount:- line.taxAmount != null ? xeroMoney(line.taxAmount) : undefined,- LineAmount: xeroMoney(line.totalAmount),- // TaxType is required by Xero: INPUT for purchase tax, NONE for zero tax- TaxType: hasTax ? "INPUT" : "NONE"- };- })+ const transactionLines = toTransactionCurrencyLines(+ costingLines,+ exchangeRate);+ const lineItems = buildXeroBillLineItems({+ bill: local,+ costingLines: transactionLines,+ accountCodesById,+ // v1: no item gets ItemCode on a bill line — proving a Xero item is+ // non-tracked needs a live per-item fetch (env-gated); attaching+ // ItemCode for a tracked item would double-post inventory. The+ // account-costed lines carry the item in Description instead.+ nonTrackedItemIds: undefined+ });+// Calculate due date: use dateDue if provided, otherwise default to Net 30let dueDate = local.dateDue;if (!dueDate && local.dateIssued) {@@ -410,15 +547,12 @@ export class BillSyncer extends BaseEntitySyncer<Date: local.dateIssued ?? undefined,DueDate: dueDate,Status: CARBON_TO_XERO_STATUS[local.status],- CurrencyCode: local.currencyCode,- CurrencyRate:- local.exchangeRate !== 1- ? xeroCurrencyRate(local.exchangeRate)- : undefined,- LineItems: lineItems,- SubTotal: xeroMoney(local.subtotal),- TotalTax: xeroMoney(local.totalTax),- Total: xeroMoney(local.totalAmount)+ CurrencyCode: currencyCode,+ // Pin the provider rate on FX bills (omit at parity rate 1).+ CurrencyRate: exchangeRate !== 1 ? exchangeRate : undefined,+ // Tax-neutral replay: lines embed tax; let Xero compute totals from the+ // NONE-taxed line amounts (no SubTotal/TotalTax/Total conflict).+ LineItems: lineItems};}@@ -756,11 +890,9 @@ export class BillSyncer extends BaseEntitySyncer<? [{ ...data, InvoiceID: existingRemoteId }]: [data];- const result = await this.provider.request<{ Invoices: Xero.Invoice[] }>(- "POST",- "/Invoices",- { body: JSON.stringify({ Invoices: invoices }) }- );+ const result = await this.xeroProvider.request<{+ Invoices: Xero.Invoice[];+ }>("POST", "/Invoices", { body: JSON.stringify({ Invoices: invoices }) });if (result.error) {throwXeroApiError(@@ -800,11 +932,9 @@ export class BillSyncer extends BaseEntitySyncer<localIdOrder.push(localId);}- const response = await this.provider.request<{ Invoices: Xero.Invoice[] }>(- "POST",- "/Invoices",- { body: JSON.stringify({ Invoices: invoices }) }- );+ const response = await this.xeroProvider.request<{+ Invoices: Xero.Invoice[];+ }>("POST", "/Invoices", { body: JSON.stringify({ Invoices: invoices }) });if (response.error) {throwXeroApiError("batch upsert bills", response);diff --git a/packages/ee/src/accounting/providers/xero/entities/contact.ts b/packages/ee/src/accounting/providers/xero/entities/contact.tsindex 3a3a5093ae..3097c58305 100644--- a/packages/ee/src/accounting/providers/xero/entities/contact.ts+++ b/packages/ee/src/accounting/providers/xero/entities/contact.ts@@ -3,6 +3,7 @@ import { createMappingService } from "../../../core/external-mapping";import { type Accounting, BaseEntitySyncer } from "../../../core/types";import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";+import type { XeroProvider } from "../provider";// Type for rows returned from customer/supplier queries with address and contact joinstype EntityRow = {@@ -34,6 +35,10 @@ export class ContactSyncer extends BaseEntitySyncer<Xero.Contact,"UpdatedDateUTC"> {+ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }+// =================================================================// 1. ID MAPPING (Override to check both customer and supplier)// =================================================================@@ -302,10 +307,9 @@ export class ContactSyncer extends BaseEntitySyncer<// =================================================================async fetchRemote(id: string): Promise<Xero.Contact | null> {- const result = await this.provider.request<{ Contacts: Xero.Contact[] }>(- "GET",- `/Contacts/${id}`- );+ const result = await this.xeroProvider.request<{+ Contacts: Xero.Contact[];+ }>("GET", `/Contacts/${id}`);return result.error ? null : (result.data?.Contacts?.[0] ?? null);}@@ -316,10 +320,9 @@ export class ContactSyncer extends BaseEntitySyncer<const result = new Map<string, Xero.Contact>();if (ids.length === 0) return result;- const response = await this.provider.request<{ Contacts: Xero.Contact[] }>(- "GET",- `/Contacts?IDs=${ids.join(",")}`- );+ const response = await this.xeroProvider.request<{+ Contacts: Xero.Contact[];+ }>("GET", `/Contacts?IDs=${ids.join(",")}`);if (response.error) {throwXeroApiError("fetch contacts batch", response);@@ -639,11 +642,9 @@ export class ContactSyncer extends BaseEntitySyncer<? [{ ...data, ContactID: existingRemoteId }]: [data];- const result = await this.provider.request<{ Contacts: Xero.Contact[] }>(- "POST",- "/Contacts",- { body: JSON.stringify({ Contacts: contacts }) }- );+ const result = await this.xeroProvider.request<{+ Contacts: Xero.Contact[];+ }>("POST", "/Contacts", { body: JSON.stringify({ Contacts: contacts }) });if (result.error) {throwXeroApiError(@@ -668,10 +669,9 @@ export class ContactSyncer extends BaseEntitySyncer<private async findRemoteContactByName(name: string): Promise<string | null> {// Xero where filter requires double-quoting string values and escaping quotesconst escapedName = name.replace(/"/g, '\\"');- const result = await this.provider.request<{ Contacts: Xero.Contact[] }>(- "GET",- `/Contacts?where=Name=="${escapedName}"`- );+ const result = await this.xeroProvider.request<{+ Contacts: Xero.Contact[];+ }>("GET", `/Contacts?where=Name=="${escapedName}"`);if (!result.error && result.data?.Contacts?.[0]?.ContactID) {return result.data.Contacts[0].ContactID;@@ -702,11 +702,9 @@ export class ContactSyncer extends BaseEntitySyncer<localIdOrder.push(localId);}- const response = await this.provider.request<{ Contacts: Xero.Contact[] }>(- "POST",- "/Contacts",- { body: JSON.stringify({ Contacts: contacts }) }- );+ const response = await this.xeroProvider.request<{+ Contacts: Xero.Contact[];+ }>("POST", "/Contacts", { body: JSON.stringify({ Contacts: contacts }) });if (response.error) {throwXeroApiError("batch upsert contacts", response);diff --git a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.tsindex c768dea8d0..b374d228af 100644--- a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts+++ b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts@@ -2,7 +2,7 @@ import type { KyselyTx } from "@carbon/database/client";import { type Accounting, BaseEntitySyncer } from "../../../core/types";import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";-import { xeroMoney } from "../serialize";+import type { XeroProvider } from "../provider";// Note: This is a push-only syncer (Carbon -> Xero).// Inventory adjustments are pushed as Manual Journals to Xero since@@ -32,6 +32,10 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<Xero.ManualJournal,"UpdatedDateUTC"> {+ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }+// =================================================================// 1. ID MAPPING - Uses default implementation from BaseEntitySyncer// =================================================================@@ -161,7 +165,7 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<// =================================================================async fetchRemote(id: string): Promise<Xero.ManualJournal | null> {- const result = await this.provider.request<{+ const result = await this.xeroProvider.request<{ManualJournals: Xero.ManualJournal[];}>("GET", `/ManualJournals/${id}`);return result.error ? null : (result.data?.ManualJournals?.[0] ?? null);@@ -173,7 +177,7 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<const result = new Map<string, Xero.ManualJournal>();if (ids.length === 0) return result;- const response = await this.provider.request<{+ const response = await this.xeroProvider.request<{ManualJournals: Xero.ManualJournal[];}>("GET", `/ManualJournals?IDs=${ids.join(",")}`);@@ -198,9 +202,7 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<local: Accounting.InventoryAdjustment): Promise<Omit<Xero.ManualJournal, "UpdatedDateUTC">> {const existingRemoteId = await this.getRemoteId(local.id);- // Serialize at Xero's monetary contract — raw float products must not- // reach the API- const amount = xeroMoney(Math.abs(local.quantity) * local.unitCost);+ const amount = Math.abs(local.quantity) * local.unitCost;const isPositive = local.entryType === "Positive Adjmt.";// Ensure item dependency is synced@@ -276,7 +278,7 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<? [{ ...data, ManualJournalID: existingRemoteId }]: [data];- const result = await this.provider.request<{+ const result = await this.xeroProvider.request<{ManualJournals: Xero.ManualJournal[];}>("POST", "/ManualJournals", {body: JSON.stringify({ ManualJournals: journals })@@ -325,7 +327,7 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<localIdOrder.push(localId);}- const response = await this.provider.request<{+ const response = await this.xeroProvider.request<{ManualJournals: Xero.ManualJournal[];}>("POST", "/ManualJournals", {body: JSON.stringify({ ManualJournals: journals })diff --git a/packages/ee/src/accounting/providers/xero/entities/invoice.ts b/packages/ee/src/accounting/providers/xero/entities/invoice.tsindex f791aa7e5c..f66d77e0b4 100644--- a/packages/ee/src/accounting/providers/xero/entities/invoice.ts+++ b/packages/ee/src/accounting/providers/xero/entities/invoice.ts@@ -1,6 +1,8 @@import type { KyselyTx } from "@carbon/database/client";import { getLogger } from "@carbon/logger";+import { loadAccountCodesById } from "../../../core/account-mapping";import { createMappingService } from "../../../core/external-mapping";+import { JournalEntrySyncError } from "../../../core/posting";import {type Accounting,BaseEntitySyncer,@@ -9,12 +11,6 @@ import {import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";import type { XeroProvider } from "../provider";-import {- xeroCurrencyRate,- xeroMoney,- xeroQuantity,- xeroUnitAmount-} from "../serialize";const logger = getLogger("ee", "accounting", "xero");@@ -107,6 +103,62 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<Xero.Invoice,"UpdatedDateUTC"> {+ private salesAccountCodePromise?: Promise<string>;++ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }++ /**+ * The Xero AccountCode item-referenced AR invoice lines post to: the item's+ * mapped REVENUE account (`accountDefault.salesAccount` → the account-mapping+ * externalCode) — the same resolution that feeds Rillet's product+ * `account_code` and QBO's `IncomeAccountRef`. No blunt default-account-code+ * fallback: when the company default is unset or unmapped, throws the+ * structured UNMAPPED_ACCOUNTS Warning (same contract as the Rillet/QBO item+ * syncers' revenue-account check) so the gap is surfaced and fixed rather+ * than silently posted to the wrong account. Per-company defaults are+ * resolved once.+ */+ private getSalesAccountCode(): Promise<string> {+ if (!this.salesAccountCodePromise) {+ this.salesAccountCodePromise = (async () => {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select("salesAccount")+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (!defaults?.salesAccount) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message:+ "Cannot sync invoice: the company account defaults are missing salesAccount — Xero invoice lines require a revenue account code. Map the account on the integration settings page, then retry.",+ warning: true,+ metadata: { missingDefaults: ["salesAccount"] }+ });+ }++ const codesById = await loadAccountCodesById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ const code = codesById.get(defaults.salesAccount);+ if (!code) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message:+ "Cannot sync invoice: the default sales account has no Xero account mapping. Map the account on the integration settings page, then retry.",+ warning: true,+ metadata: { unmappedAccountIds: [defaults.salesAccount] }+ });+ }+ return code;+ })();+ }+ return this.salesAccountCodePromise;+ }+// =================================================================// 1. ID MAPPING - Uses default implementation from BaseEntitySyncer// The entityType "invoice" maps to the salesInvoice table@@ -282,10 +334,9 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<// =================================================================async fetchRemote(id: string): Promise<Xero.Invoice | null> {- const result = await this.provider.request<{ Invoices: Xero.Invoice[] }>(- "GET",- `/Invoices/${id}`- );+ const result = await this.xeroProvider.request<{+ Invoices: Xero.Invoice[];+ }>("GET", `/Invoices/${id}`);return result.error ? null : (result.data?.Invoices?.[0] ?? null);}@@ -295,10 +346,9 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<const result = new Map<string, Xero.Invoice>();if (ids.length === 0) return result;- const response = await this.provider.request<{ Invoices: Xero.Invoice[] }>(- "GET",- `/Invoices?IDs=${ids.join(",")}`- );+ const response = await this.xeroProvider.request<{+ Invoices: Xero.Invoice[];+ }>("GET", `/Invoices?IDs=${ids.join(",")}`);if (response.error) {throwXeroApiError("fetch invoices batch", response);@@ -328,33 +378,27 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<local.customerId);- // Get default account code from provider settings- const xeroProvider = this.provider as XeroProvider;- const defaultAccountCode = xeroProvider.settings?.defaultSalesAccountCode;+ // Item-referenced AR posts to the item's mapped REVENUE account+ // (accountDefault.salesAccount) — throws UNMAPPED_ACCOUNTS when unset+ // or unmapped (see getSalesAccountCode).+ const salesAccountCode = await this.getSalesAccountCode();- logger.info("Provider settings", {- settings: xeroProvider.settings,- defaultAccountCode- });+ logger.info("Sales AccountCode", { salesAccountCode });// Build line items, resolving item dependenciesconst lineItems: Xero.InvoiceLineItem[] = [];for (const line of local.lines) {- // Round once, then derive: Xero recomputes the extension from what we- // send, so a rounded Quantity with an extension built from the unrounded- // one makes Quantity x UnitAmount disagree with LineAmount.- const quantity = xeroQuantity(line.quantity);- const unitAmount = xeroUnitAmount(line.unitPrice);- const taxAmount = (quantity * unitAmount * line.taxPercent) / 100;+ const taxAmount =+ (line.quantity * line.unitPrice * line.taxPercent) / 100;const lineItem: Xero.InvoiceLineItem = {Description: line.description ?? undefined,- Quantity: quantity,- UnitAmount: unitAmount,- TaxAmount: xeroMoney(taxAmount),- LineAmount: xeroMoney(quantity * unitAmount),- // Use default account code from settings if no account specified- AccountCode: defaultAccountCode,+ Quantity: line.quantity,+ UnitAmount: line.unitPrice,+ TaxAmount: taxAmount,+ LineAmount: line.quantity * line.unitPrice,+ // The item's mapped revenue account (item-referenced AR).+ AccountCode: salesAccountCode,// TaxType is required by Xero: OUTPUT for sales tax, NONE for zero taxTaxType: line.taxPercent > 0 ? "OUTPUT" : "NONE"};@@ -398,16 +442,13 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<Status: CARBON_TO_XERO_STATUS[local.status],LineAmountTypes: "Exclusive", // Tax is calculated separatelyLineItems: lineItems,- SubTotal: xeroMoney(local.subtotal),- TotalTax: xeroMoney(local.totalTax),- Total: xeroMoney(local.totalAmount),- AmountDue: xeroMoney(local.balance),- AmountPaid: xeroMoney(local.totalAmount - local.balance),+ SubTotal: local.subtotal,+ TotalTax: local.totalTax,+ Total: local.totalAmount,+ AmountDue: local.balance,+ AmountPaid: local.totalAmount - local.balance,CurrencyCode: local.currencyCode,- CurrencyRate:- local.exchangeRate !== 1- ? xeroCurrencyRate(local.exchangeRate)- : undefined+ CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined};}@@ -504,11 +545,9 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<? [{ ...data, InvoiceID: existingRemoteId }]: [data];- const result = await this.provider.request<{ Invoices: Xero.Invoice[] }>(- "POST",- "/Invoices",- { body: JSON.stringify({ Invoices: invoices }) }- );+ const result = await this.xeroProvider.request<{+ Invoices: Xero.Invoice[];+ }>("POST", "/Invoices", { body: JSON.stringify({ Invoices: invoices }) });if (result.error) {throwXeroApiError(@@ -548,11 +587,9 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<localIdOrder.push(localId);}- const response = await this.provider.request<{ Invoices: Xero.Invoice[] }>(- "POST",- "/Invoices",- { body: JSON.stringify({ Invoices: invoices }) }- );+ const response = await this.xeroProvider.request<{+ Invoices: Xero.Invoice[];+ }>("POST", "/Invoices", { body: JSON.stringify({ Invoices: invoices }) });if (response.error) {throwXeroApiError("batch upsert invoices", response);diff --git a/packages/ee/src/accounting/providers/xero/entities/item.ts b/packages/ee/src/accounting/providers/xero/entities/item.tsindex 743bb60792..2db4171cb5 100644--- a/packages/ee/src/accounting/providers/xero/entities/item.ts+++ b/packages/ee/src/accounting/providers/xero/entities/item.ts@@ -2,6 +2,7 @@ import type { KyselyTx } from "@carbon/database/client";import { type Accounting, BaseEntitySyncer } from "../../../core/types";import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";+import type { XeroProvider } from "../provider";// Type for rows returned from item queries with cost/price joinstype ItemRow = {@@ -25,6 +26,10 @@ export class ItemSyncer extends BaseEntitySyncer<Xero.Item,"UpdatedDateUTC"> {+ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }+// =================================================================// 1. ID MAPPING - Uses default implementation from BaseEntitySyncer// =================================================================@@ -120,7 +125,7 @@ export class ItemSyncer extends BaseEntitySyncer<// =================================================================async fetchRemote(id: string): Promise<Xero.Item | null> {- const result = await this.provider.request<{ Items: Xero.Item[] }>(+ const result = await this.xeroProvider.request<{ Items: Xero.Item[] }>("GET",`/Items/${id}`);@@ -133,7 +138,7 @@ export class ItemSyncer extends BaseEntitySyncer<const result = new Map<string, Xero.Item>();if (ids.length === 0) return result;- const response = await this.provider.request<{ Items: Xero.Item[] }>(+ const response = await this.xeroProvider.request<{ Items: Xero.Item[] }>("GET",`/Items?IDs=${ids.join(",")}`);@@ -160,14 +165,16 @@ export class ItemSyncer extends BaseEntitySyncer<): Promise<Omit<Xero.Item, "UpdatedDateUTC">> {const existingRemoteId = await this.getRemoteId(local.id);- return {+ // Provider items are pushed NON-TRACKED so Xero never books inventory+ // (on bills) or COGS (on invoices) — per-SKU valuation stays in Carbon+ // (representation model, spec invariant 4).+ const base: Omit<Xero.Item, "UpdatedDateUTC" | "IsTrackedAsInventory"> = {ItemID: existingRemoteId!,Code: local.code.slice(0, 30),Name: local.name.slice(0, 50),Description: local.description?.slice(0, 4000) ?? undefined,IsPurchased: local.isPurchased,IsSold: local.isSold,- IsTrackedAsInventory: local.isTrackedAsInventory,PurchaseDetails: local.isPurchased? { UnitPrice: local.unitCost }: undefined,@@ -175,6 +182,25 @@ export class ItemSyncer extends BaseEntitySyncer<? { UnitPrice: local.unitSalePrice }: undefined};++ // CREATE: force non-tracked.+ if (!existingRemoteId) {+ return { ...base, IsTrackedAsInventory: false };+ }++ // UPDATE: Xero rejects flipping a tracked item to non-tracked once it has+ // stock/transactions, so OMIT the field. If the remote item is still+ // tracked, record a Warning telling the operator to untrack it manually+ // (zero the stock, untrack in Xero, retry) — the update still proceeds+ // (name/price sync) so item sync is never blocked.+ const remote = await this.fetchRemote(existingRemoteId);+ if (remote?.IsTrackedAsInventory) {+ console.warn(+ `[XeroItemSyncer] Xero item ${local.code} (${existingRemoteId}) is still tracked as inventory. Bills/invoices referencing it will post inventory/COGS in Xero, double-counting Carbon's valuation. Zero its stock and untrack it in Xero (Products & Services → the item → untick "I track this item"), then retry.`+ );+ }++ return base;}// =================================================================@@ -284,7 +310,7 @@ export class ItemSyncer extends BaseEntitySyncer<*/private async findRemoteItemByCode(code: string): Promise<string | null> {const escapedCode = code.replace(/"/g, '\\"');- const result = await this.provider.request<{ Items: Xero.Item[] }>(+ const result = await this.xeroProvider.request<{ Items: Xero.Item[] }>("GET",`/Items?where=Code=="${escapedCode}"`);@@ -316,7 +342,7 @@ export class ItemSyncer extends BaseEntitySyncer<? [{ ...data, ItemID: existingRemoteId }]: [data];- const result = await this.provider.request<{ Items: Xero.Item[] }>(+ const result = await this.xeroProvider.request<{ Items: Xero.Item[] }>("POST","/Items",{ body: JSON.stringify({ Items: items }) }@@ -358,7 +384,7 @@ export class ItemSyncer extends BaseEntitySyncer<localIdOrder.push(localId);}- const response = await this.provider.request<{ Items: Xero.Item[] }>(+ const response = await this.xeroProvider.request<{ Items: Xero.Item[] }>("POST","/Items",{ body: JSON.stringify({ Items: items }) }diff --git a/packages/ee/src/accounting/providers/xero/entities/journal-entry.test.ts b/packages/ee/src/accounting/providers/xero/entities/journal-entry.test.tsnew file mode 100644index 0000000000..845e307d5d--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/entities/journal-entry.test.ts@@ -0,0 +1,676 @@+import { describe, expect, it } from "vitest";+import { validateDimensionSlots } from "../../../core/dimension-mapping";+import {+ POSTING_SYNC_DEFAULT_SOURCE_TYPES,+ POSTING_SYNC_EXCLUDED_SOURCE_TYPES+} from "../../../core/models";+import {+ addDaysToIsoDate,+ DEFAULT_POSTING_SYNC_SETTINGS,+ evaluatePeriodLock,+ getJournalEntrySyncEntityId,+ getPostingSyncSourceTypeSkipReason,+ isBalancedJournal,+ isJournalEntrySyncFailure,+ JournalEntrySyncError,+ type PostingSyncSettings,+ parseJournalEntrySyncEntityId,+ resolvePostingSyncSettings,+ runJournalEntryPreflight+} from "../../../core/posting";+import type { Accounting } from "../../../core/types";+import {+ buildXeroTrackingTarget,+ parseXeroTrackingTarget,+ XERO_MAX_JOURNAL_DIMENSION_SLOTS+} from "../provider";+import { mapJournalEntryToManualJournal } from "./journal-entry";++// 3-line balanced fixture: Dr Inventory 150.00, Dr Freight 25.50,+// Cr GRNI accrual 175.50 (Carbon signed amounts: positive = debit)+const makeJournal = (+ overrides?: Partial<Accounting.JournalEntry>+): Accounting.JournalEntry => ({+ id: "je_123",+ companyId: "company-1",+ journalEntryId: "JE000042",+ description: "Receipt posting",+ postingDate: "2026-07-01",+ status: "Posted",+ sourceType: "Purchase Receipt",+ reversalOfId: null,+ reversedById: null,+ reversal: false,+ lines: [+ {+ id: "line-1",+ accountId: "acc-inventory",+ amount: 150,+ description: "Inventory"+ },+ { id: "line-2", accountId: "acc-freight", amount: 25.5, description: null },+ {+ id: "line-3",+ accountId: "acc-accrual",+ amount: -175.5,+ description: "GRNI accrual"+ }+ ],+ updatedAt: "2026-07-01T12:00:00.000Z",+ ...overrides+});++const ACCOUNT_CODES: ReadonlyMap<string, string> = new Map([+ ["acc-inventory", "1400"],+ ["acc-freight", "5200"],+ ["acc-accrual", "2150"]+]);++/**+ * Build settings through the resolver so stored-fragment shapes (including+ * v2 `sourceTypes: string[]` / `includeManual` overrides — upgraded by the+ * schema shim) are exercised exactly as production reads them.+ */+const makeSettings = (+ fragment?: Record<string, unknown>+): PostingSyncSettings =>+ resolvePostingSyncSettings({+ settings: { postingSync: { enabled: true, ...fragment } }+ });++const passingPreflightArgs = () => ({+ journal: makeJournal(),+ accountCodesById: ACCOUNT_CODES,+ controlAccountIds: new Set<string>(),+ lockDate: null,+ settings: makeSettings()+});++describe("mapJournalEntryToManualJournal", () => {+ it("maps a 3-line journal with Carbon signs (positive = debit), mapped codes and TaxType NONE", () => {+ const payload = mapJournalEntryToManualJournal({+ journal: makeJournal(),+ accountCodesById: ACCOUNT_CODES,+ pushDate: "2026-07-01"+ });++ expect(payload.Narration).toBe("Carbon JE000042 je_123");+ expect(payload.Date).toBe("2026-07-01");+ expect(payload.Status).toBe("POSTED");+ expect(payload.JournalLines).toEqual([+ {+ LineAmount: 150,+ AccountCode: "1400",+ Description: "Inventory",+ TaxType: "NONE"+ },+ {+ // Line without a description falls back to the journal description+ LineAmount: 25.5,+ AccountCode: "5200",+ Description: "Receipt posting",+ TaxType: "NONE"+ },+ {+ LineAmount: -175.5,+ AccountCode: "2150",+ Description: "GRNI accrual",+ TaxType: "NONE"+ }+ ]);++ // The mapped payload balances exactly like the Carbon journal+ const sum = (payload.JournalLines ?? []).reduce(+ (total, line) => total + Math.round(line.LineAmount * 100),+ 0+ );+ expect(sum).toBe(0);+ });++ it("negates every LineAmount and uses the reversal narration for reversal pushes", () => {+ const payload = mapJournalEntryToManualJournal({+ journal: makeJournal({ status: "Reversed", reversal: true }),+ accountCodesById: ACCOUNT_CODES,+ pushDate: "2026-07-01"+ });++ expect(payload.Narration).toBe("Carbon reversal of JE000042");+ expect((payload.JournalLines ?? []).map((line) => line.LineAmount)).toEqual(+ [-150, -25.5, 175.5]+ );+ });++ it("appends the original date to the narration when the push was re-dated", () => {+ const payload = mapJournalEntryToManualJournal({+ journal: makeJournal(),+ accountCodesById: ACCOUNT_CODES,+ pushDate: "2026-07-02",+ redatedFromDate: "2026-07-01"+ });++ expect(payload.Narration).toBe(+ "Carbon JE000042 je_123 | original date 2026-07-01"+ );+ expect(payload.Date).toBe("2026-07-02");+ });++ it("throws the structured UNMAPPED_ACCOUNTS error when a line's account has no code", () => {+ expect(() =>+ mapJournalEntryToManualJournal({+ journal: makeJournal(),+ accountCodesById: new Map([["acc-inventory", "1400"]]),+ pushDate: "2026-07-01"+ })+ ).toThrowError(JournalEntrySyncError);+ });+});++describe("runJournalEntryPreflight", () => {+ it("passes a fully mapped, balanced, unlocked journal through with its posting date", () => {+ const result = runJournalEntryPreflight(passingPreflightArgs());+ expect(result).toEqual({ failure: null, pushDate: "2026-07-01" });+ });++ it("returns UNMAPPED_ACCOUNTS (warning) with the unmapped account ids in metadata", () => {+ const result = runJournalEntryPreflight({+ ...passingPreflightArgs(),+ accountCodesById: new Map([+ ["acc-inventory", "1400"],+ ["acc-accrual", "2150"]+ ])+ });++ expect(result.failure?.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(result.failure?.warning).toBe(true);+ expect(result.failure?.metadata?.unmappedAccountIds).toEqual([+ "acc-freight"+ ]);+ });++ it("treats lines without an account as UNMAPPED_ACCOUNTS with the line ids in metadata", () => {+ const journal = makeJournal();+ const brokenLine = journal.lines[1];+ if (!brokenLine) throw new Error("fixture must have 3 lines");+ brokenLine.accountId = null;++ const result = runJournalEntryPreflight({+ ...passingPreflightArgs(),+ journal+ });++ expect(result.failure?.errorCode).toBe("UNMAPPED_ACCOUNTS");+ expect(result.failure?.metadata?.lineIdsWithoutAccount).toEqual(["line-2"]);+ });++ it("returns CONTROL_ACCOUNT_LINE (warning) when a line hits an AR/AP control account", () => {+ const result = runJournalEntryPreflight({+ ...passingPreflightArgs(),+ controlAccountIds: new Set(["acc-accrual"])+ });++ expect(result.failure?.errorCode).toBe("CONTROL_ACCOUNT_LINE");+ expect(result.failure?.warning).toBe(true);+ expect(result.failure?.metadata?.lineIds).toEqual(["line-3"]);+ });++ it("returns UNBALANCED_JOURNAL as a hard failure (warning: false)", () => {+ const journal = makeJournal();+ const creditLine = journal.lines[2];+ if (!creditLine) throw new Error("fixture must have 3 lines");+ creditLine.amount = -175.49;++ const result = runJournalEntryPreflight({+ ...passingPreflightArgs(),+ journal+ });++ expect(result.failure?.errorCode).toBe("UNBALANCED_JOURNAL");+ expect(result.failure?.warning).toBe(false);+ });++ it("returns PERIOD_LOCKED (warning) under the park policy when postingDate <= lock date", () => {+ const result = runJournalEntryPreflight({+ ...passingPreflightArgs(),+ lockDate: "2026-07-01" // equal to postingDate → locked+ });++ expect(result.failure?.errorCode).toBe("PERIOD_LOCKED");+ expect(result.failure?.warning).toBe(true);+ expect(result.failure?.metadata).toEqual({+ postingDate: "2026-07-01",+ lockDate: "2026-07-01"+ });+ });++ it("re-dates to lock date + 1 (keeping the original date for the narration) under the redate policy", () => {+ const result = runJournalEntryPreflight({+ ...passingPreflightArgs(),+ lockDate: "2026-07-01",+ settings: makeSettings({ periodLockPolicy: "redate" })+ });++ expect(result).toEqual({+ failure: null,+ pushDate: "2026-07-02",+ redatedFromDate: "2026-07-01"+ });+ });++ it("does not lock journals dated after the lock date", () => {+ const result = runJournalEntryPreflight({+ ...passingPreflightArgs(),+ lockDate: "2026-06-30"+ });++ expect(result.failure).toBeNull();+ });++ it("reports unmapped accounts before the balance check", () => {+ const journal = makeJournal();+ const creditLine = journal.lines[2];+ if (!creditLine) throw new Error("fixture must have 3 lines");+ creditLine.amount = -175.49; // unbalanced AND unmapped++ const result = runJournalEntryPreflight({+ ...passingPreflightArgs(),+ journal,+ accountCodesById: new Map()+ });++ expect(result.failure?.errorCode).toBe("UNMAPPED_ACCOUNTS");+ });+});++describe("getPostingSyncSourceTypeSkipReason", () => {+ it("never pushes document-represented source types in documents mode, even when listed in sourceTypes", () => {+ // Doc-backed types (a synced document carries the amounts) exclude;+ // memos/returns have NO document representation yet, so their skip+ // reason is the loud delivery-hole message instead — either way the+ // journal is never pushed in documents mode.+ const backed = ["Sales Invoice", "Purchase Invoice", "Payment"];++ for (const sourceType of POSTING_SYNC_EXCLUDED_SOURCE_TYPES) {+ const expected = backed.includes(sourceType)+ ? "excluded from posting sync"+ : "no document representation";++ expect(+ getPostingSyncSourceTypeSkipReason(sourceType, makeSettings()),+ `${sourceType} should not push`+ ).toContain(expected);++ expect(+ getPostingSyncSourceTypeSkipReason(+ sourceType,+ makeSettings({ sourceTypes: [sourceType] })+ ),+ `${sourceType} should stay unpushed when explicitly listed`+ ).toContain(expected);+ }+ });++ it("pushes every default source type under default settings", () => {+ for (const sourceType of POSTING_SYNC_DEFAULT_SOURCE_TYPES) {+ expect(+ getPostingSyncSourceTypeSkipReason(sourceType, makeSettings()),+ `${sourceType} should be allowed by default`+ ).toBeNull();+ }+ });++ it("never pushes Manual journals — even a stored includeManual cannot enable them", () => {+ expect(+ getPostingSyncSourceTypeSkipReason("Manual", makeSettings())+ ).toContain("Manual journals are never synced");+ // The v2 shim maps includeManual → sourceTypes.Manual.enabled, but the+ // policy (syncable: false) overrides any stored config: Manual is the+ // only path to arbitrary/unmapped accounts and the external ledger owns+ // manual journals.+ expect(+ getPostingSyncSourceTypeSkipReason(+ "Manual",+ makeSettings({ includeManual: true })+ )+ ).toContain("Manual journals are never synced");+ });++ it("always-on: a narrowed stored sourceTypes list cannot disable an automated type", () => {+ const narrowed = makeSettings({ sourceTypes: ["Purchase Receipt"] });+ expect(+ getPostingSyncSourceTypeSkipReason("Purchase Receipt", narrowed)+ ).toBeNull();+ // Sales Shipment is absent from the stored v2 list, but automated+ // postings always sync — stored per-type enables are parse-compatible+ // legacy fields the decision no longer reads.+ expect(+ getPostingSyncSourceTypeSkipReason("Sales Shipment", narrowed)+ ).toBeNull();+ });++ it("skips journals without a source type", () => {+ expect(getPostingSyncSourceTypeSkipReason(null, makeSettings())).toContain(+ "no source type"+ );+ });+});++describe("resolvePostingSyncSettings", () => {+ it("defaults to ALWAYS-ON posting sync when nothing is stored", () => {+ expect(resolvePostingSyncSettings(undefined)).toEqual(+ DEFAULT_POSTING_SYNC_SETTINGS+ );+ expect(resolvePostingSyncSettings({})).toEqual(+ DEFAULT_POSTING_SYNC_SETTINGS+ );+ expect(resolvePostingSyncSettings({ settings: {} })).toEqual(+ DEFAULT_POSTING_SYNC_SETTINGS+ );++ // Always-on defaults: enabled (legacy field, no longer read by the+ // decision core), documents-mode families, source-type record total over+ // the enum with policy defaults, warn on unmapped dims+ expect(DEFAULT_POSTING_SYNC_SETTINGS.enabled).toBe(true);+ expect(DEFAULT_POSTING_SYNC_SETTINGS.families).toEqual({+ ar: "documents",+ ap: "documents"+ });+ expect(DEFAULT_POSTING_SYNC_SETTINGS.periodLockPolicy).toBe("park");+ expect(DEFAULT_POSTING_SYNC_SETTINGS.onUnmappedDimensionValue).toBe("warn");+ expect(DEFAULT_POSTING_SYNC_SETTINGS.dimensionSlots).toEqual([]);+ expect(DEFAULT_POSTING_SYNC_SETTINGS.consolidation).toBe("individual");+ expect(+ DEFAULT_POSTING_SYNC_SETTINGS.sourceTypes["Purchase Receipt"]+ ).toEqual({ enabled: true, granularity: "individual" });+ expect(+ DEFAULT_POSTING_SYNC_SETTINGS.sourceTypes["Production Event"]+ ).toEqual({ enabled: true, granularity: "daily-summary" });+ expect(DEFAULT_POSTING_SYNC_SETTINGS.sourceTypes.Manual).toEqual({+ enabled: false,+ granularity: "individual"+ });+ });++ it("upgrades a stored v2 fragment (global daily consolidation) through the shim", () => {+ const resolved = resolvePostingSyncSettings({+ settings: {+ postingSync: {+ enabled: true,+ consolidation: "daily",+ lockDate: "2026-06-30"+ }+ }+ });++ expect(resolved.enabled).toBe(true);+ expect(resolved.lockDate).toBe("2026-06-30");+ expect(resolved.periodLockPolicy).toBe("park");+ // v2 daily consolidation → every enabled type daily-summary, so the+ // transitional derived hold flag stays "daily"+ expect(resolved.consolidation).toBe("daily");+ expect(resolved.sourceTypes["Purchase Receipt"]).toEqual({+ enabled: true,+ granularity: "daily-summary"+ });+ expect(resolved.sourceTypes.Manual.enabled).toBe(false);+ expect(resolved.families).toEqual({ ar: "documents", ap: "documents" });+ });++ it("upgrades a stored v2 sourceTypes array + includeManual through the shim", () => {+ const resolved = resolvePostingSyncSettings({+ settings: {+ postingSync: {+ enabled: true,+ sourceTypes: ["Purchase Receipt"],+ includeManual: true,+ consolidation: "individual"+ }+ }+ });++ expect(resolved.sourceTypes["Purchase Receipt"]).toEqual({+ enabled: true,+ granularity: "individual"+ });+ expect(resolved.sourceTypes["Sales Shipment"].enabled).toBe(false);+ expect(resolved.sourceTypes.Manual).toEqual({+ enabled: true,+ granularity: "individual"+ });+ expect(resolved.consolidation).toBe("individual");+ });++ it("ignores an invalid stored fragment instead of throwing", () => {+ const resolved = resolvePostingSyncSettings({+ settings: { postingSync: { consolidation: "weekly", enabled: "yes" } }+ });++ expect(resolved).toEqual(DEFAULT_POSTING_SYNC_SETTINGS);+ });+});++describe("journal sync entity-id contract", () => {+ it("round-trips plain and reversal entity ids", () => {+ expect(getJournalEntrySyncEntityId("je_123", false)).toBe("je_123");+ expect(getJournalEntrySyncEntityId("je_123", true)).toBe("je_123:reversal");++ expect(parseJournalEntrySyncEntityId("je_123")).toEqual({+ journalId: "je_123",+ reversal: false+ });+ expect(parseJournalEntrySyncEntityId("je_123:reversal")).toEqual({+ journalId: "je_123",+ reversal: true+ });+ });+});++describe("isJournalEntrySyncFailure", () => {+ it("detects the structured failure envelope on SyncResult.error", () => {+ const failure = new JournalEntrySyncError({+ errorCode: "PERIOD_LOCKED",+ message: "locked",+ warning: true+ }).failure;++ expect(isJournalEntrySyncFailure(failure)).toBe(true);+ expect(isJournalEntrySyncFailure("PERIOD_LOCKED: locked")).toBe(false);+ expect(isJournalEntrySyncFailure(null)).toBe(false);+ expect(+ isJournalEntrySyncFailure({ errorCode: "SOMETHING_ELSE", message: "x" })+ ).toBe(false);+ });++ it("formats the error message as '<code>: <detail>' for string-flattening paths", () => {+ const error = new JournalEntrySyncError({+ errorCode: "UNBALANCED_JOURNAL",+ message: "does not balance",+ warning: false+ });++ expect(error.message).toBe("UNBALANCED_JOURNAL: does not balance");+ });+});++describe("period-lock date helpers", () => {+ it("evaluates the boundary as locked (postingDate == lockDate)", () => {+ expect(+ evaluatePeriodLock({+ postingDate: "2026-07-01",+ lockDate: "2026-07-01",+ policy: "park"+ })+ ).toEqual({ locked: true, policy: "park", lockDate: "2026-07-01" });++ expect(+ evaluatePeriodLock({+ postingDate: "2026-07-02",+ lockDate: "2026-07-01",+ policy: "park"+ })+ ).toEqual({ locked: false });++ expect(+ evaluatePeriodLock({+ postingDate: "2026-07-01",+ lockDate: null,+ policy: "park"+ })+ ).toEqual({ locked: false });+ });++ it("rolls month and year boundaries when adding a day", () => {+ expect(addDaysToIsoDate("2026-06-30", 1)).toBe("2026-07-01");+ expect(addDaysToIsoDate("2026-12-31", 1)).toBe("2027-01-01");+ expect(addDaysToIsoDate("2028-02-28", 1)).toBe("2028-02-29"); // leap year+ });+});++describe("isBalancedJournal", () => {+ it("balances at 2dp without floating-point drift", () => {+ expect(+ isBalancedJournal([{ amount: 0.1 }, { amount: 0.2 }, { amount: -0.3 }])+ ).toBe(true);+ expect(isBalancedJournal([{ amount: 100 }, { amount: -99.99 }])).toBe(+ false+ );+ expect(isBalancedJournal([])).toBe(true);+ });+});++// ── Dimension slots → line Tracking (Phase 2) ────────────────────────────────++describe("mapJournalEntryToManualJournal — dimensions", () => {+ const LOCATION_DIM = "dim_loc";+ const COST_CENTER_DIM = "dim_cc";+ const REGION_CATEGORY = "11111111-1111-1111-1111-111111111111";+ const CC_CATEGORY = "22222222-2222-2222-2222-222222222222";++ const dimensionedJournal = makeJournal({+ lines: [+ {+ id: "line-1",+ accountId: "acc-inventory",+ amount: 150,+ description: "Inventory",+ dimensions: [+ { dimensionId: LOCATION_DIM, valueId: "loc_atl" },+ { dimensionId: COST_CENTER_DIM, valueId: "cc_ops" }+ ]+ },+ {+ id: "line-2",+ accountId: "acc-accrual",+ amount: -150,+ description: null,+ dimensions: [{ dimensionId: LOCATION_DIM, valueId: "loc_bos" }]+ }+ ]+ });++ // Two slots — Xero's org-wide cap on active tracking categories+ const slots = [+ { dimensionId: LOCATION_DIM, target: `tracking:${REGION_CATEGORY}` },+ { dimensionId: COST_CENTER_DIM, target: `tracking:${CC_CATEGORY}` }+ ];++ it("attaches Tracking (category id + option id) per slotted dimension (golden fixture, 2 categories)", () => {+ const payload = mapJournalEntryToManualJournal({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ pushDate: "2026-07-01",+ dimensions: {+ slots,+ optionIdsByValue: new Map([+ ["dim_loc:loc_atl", "opt-atl"],+ ["dim_loc:loc_bos", "opt-bos"],+ ["dim_cc:cc_ops", "opt-ops"]+ ])+ }+ });++ expect(payload.JournalLines?.[0]?.Tracking).toEqual([+ { TrackingCategoryID: REGION_CATEGORY, TrackingOptionID: "opt-atl" },+ { TrackingCategoryID: CC_CATEGORY, TrackingOptionID: "opt-ops" }+ ]);+ expect(payload.JournalLines?.[1]?.Tracking).toEqual([+ { TrackingCategoryID: REGION_CATEGORY, TrackingOptionID: "opt-bos" }+ ]);+ });++ it("omits Tracking for unmapped values (drop path) and when no dimension args are passed", () => {+ const dropped = mapJournalEntryToManualJournal({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ pushDate: "2026-07-01",+ dimensions: {+ slots,+ optionIdsByValue: new Map([["dim_loc:loc_atl", "opt-atl"]])+ }+ });+ expect(dropped.JournalLines?.[0]?.Tracking).toEqual([+ { TrackingCategoryID: REGION_CATEGORY, TrackingOptionID: "opt-atl" }+ ]);+ expect(dropped.JournalLines?.[1]?.Tracking).toBeUndefined();++ const legacy = mapJournalEntryToManualJournal({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ pushDate: "2026-07-01"+ });+ expect(legacy.JournalLines?.[0]?.Tracking).toBeUndefined();+ });++ it("ignores slots whose target is not a tracking target", () => {+ const payload = mapJournalEntryToManualJournal({+ journal: dimensionedJournal,+ accountCodesById: ACCOUNT_CODES,+ pushDate: "2026-07-01",+ dimensions: {+ slots: [{ dimensionId: LOCATION_DIM, target: "class" }],+ optionIdsByValue: new Map([["dim_loc:loc_atl", "opt-atl"]])+ }+ });+ expect(payload.JournalLines?.[0]?.Tracking).toBeUndefined();+ });+});++describe("Xero dimension slot capacity", () => {+ it("caps slots at Xero's 2 active tracking categories via validateDimensionSlots", () => {+ const targets = [+ { id: "tracking:cat-1", label: "Region", capacity: 1 },+ { id: "tracking:cat-2", label: "Cost Center", capacity: 1 },+ { id: "tracking:cat-3", label: "Extra", capacity: 1 }+ ];++ expect(+ validateDimensionSlots({+ slots: [+ { dimensionId: "dim_a", target: "tracking:cat-1" },+ { dimensionId: "dim_b", target: "tracking:cat-2" }+ ],+ targets,+ maxSlots: XERO_MAX_JOURNAL_DIMENSION_SLOTS+ })+ ).toEqual([]);++ const errors = validateDimensionSlots({+ slots: [+ { dimensionId: "dim_a", target: "tracking:cat-1" },+ { dimensionId: "dim_b", target: "tracking:cat-2" },+ { dimensionId: "dim_c", target: "tracking:cat-3" }+ ],+ targets,+ maxSlots: XERO_MAX_JOURNAL_DIMENSION_SLOTS+ });+ expect(errors.some((error) => error.includes("at most 2"))).toBe(true);+ });+});++describe("Xero tracking targets", () => {+ it("builds and parses tracking:<categoryId> targets", () => {+ expect(buildXeroTrackingTarget("cat-1")).toBe("tracking:cat-1");+ expect(parseXeroTrackingTarget("tracking:cat-1")).toBe("cat-1");+ expect(parseXeroTrackingTarget("class")).toBeNull();+ expect(parseXeroTrackingTarget("tracking:")).toBeNull();+ });+});diff --git a/packages/ee/src/accounting/providers/xero/entities/journal-entry.ts b/packages/ee/src/accounting/providers/xero/entities/journal-entry.tsnew file mode 100644index 0000000000..c8dcf50716--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/entities/journal-entry.ts@@ -0,0 +1,830 @@+import type { KyselyTx } from "@carbon/database/client";+import { getAccountMappings } from "../../../core/account-mapping";+import {+ buildDimensionValueMappingEntityId,+ buildDimensionValueMappingLookup,+ ensureDimensionValueExternalIds,+ getDimensionValueMappings,+ loadJournalLineDimensions,+ resolveDimensionValueLabels,+ upsertDimensionValueMapping+} from "../../../core/dimension-mapping";+import type { PostingSyncDimensionSlot } from "../../../core/models";+import {+ getPostingSyncSourceTypeSkipReason,+ JournalEntrySyncError,+ type PostingSyncSettings,+ parseJournalEntrySyncEntityId,+ resolvePostingSyncSettings,+ roundCurrency,+ runJournalEntryPreflight,+ toDebitSignedAmount,+ toPostingDateString+} from "../../../core/posting";+import {+ type Accounting,+ BaseEntitySyncer,+ type BatchSyncResult,+ type ShouldSyncContext,+ type SyncResult+} from "../../../core/types";+import { withTriggersDisabled } from "../../../core/utils";+import { parseDotnetDate, type Xero } from "../models";+import { parseXeroTrackingTarget, type XeroProvider } from "../provider";++/**+ * JournalEntrySyncer — pushes Posted Carbon journals (`journal` ++ * `journalLine`) to Xero as Manual Journals. PUSH-ONLY: pull methods return+ * descriptive not-supported errors.+ *+ * Sign convention: Carbon `journalLine.amount` is signed (positive = debit,+ * negative = credit) and Xero manual-journal lines use the same convention+ * (positive LineAmount = debit) — matching the existing+ * InventoryAdjustmentSyncer. TODO: verify the sign convention against a+ * real/sandbox Xero manual journal before enabling for production+ * companies.+ *+ * Reversal contract (Task 10 sets it up): when a sync operation carries+ * `metadata.reversal: true`, the drain pushes entity id+ * `"<journal.id>:reversal"` (see getJournalEntrySyncEntityId). The syncer+ * then loads the ORIGINAL journal, requires status `Reversed` plus an+ * existing original mapping, negates every LineAmount, uses narration+ * `"Carbon reversal of <journalEntryId>"`, and stores the reversal's+ * mapping under the suffixed entity id — the original mapping is never+ * touched. (Carbon's reverseJournalEntry also inserts a separate negated+ * `Manual` journal; that row is inserted as Posted — never UPDATEd — so the+ * posting trigger does not enqueue it, and with `includeManual` off it is+ * excluded from backfills too.)+ *+ * Failure channel: pre-flight failures (UNMAPPED_ACCOUNTS,+ * CONTROL_ACCOUNT_LINE, PERIOD_LOCKED park, UNBALANCED_JOURNAL) throw+ * JournalEntrySyncError inside the mapping step; pushToAccounting converts+ * them to `SyncResult.error` carrying the structured+ * JournalEntrySyncFailure object (SyncResult.error is typed `unknown` for+ * this). The drain detects them with isJournalEntrySyncFailure and records+ * them via failOperation({ errorCode, errorMessage, warning }). shouldSync+ * gates (wrong status, disabled posting sync, excluded sourceType, already+ * mapped) keep the existing skip-reason-string channel+ * (`SyncResult.status === "skipped"`).+ *+ * Consolidation-aware: the syncer resolves the full posting-sync settings+ * (including `consolidation`) from+ * `companyIntegration.metadata.settings.postingSync` — the drain reads+ * getPostingSyncSettings() to hold journal operations for the daily+ * consolidation cron instead of pushing them individually.+ */++/**+ * Map one Carbon journal to a Xero manual-journal payload. Pure — exported+ * for tests and for the daily-consolidation cron (Task 12).+ *+ * - Lines: LineAmount = signed Carbon amount (negated for reversals),+ * AccountCode from the account mapping, Description = line description+ * falling back to the journal description, TaxType "NONE" (tax mapping is+ * out of scope v1).+ * - Narration: "Carbon <journalEntryId> <journal.id>" (or+ * "Carbon reversal of <journalEntryId>"), with+ * " | original date <postingDate>" appended when the period-lock redate+ * policy moved the push date.+ */+/**+ * Slot config + resolved option ids for the Xero journal mapper: `slots`+ * carry `tracking:<TrackingCategoryID>` targets; `optionIdsByValue`+ * resolves `<dimensionId>:<valueId>` → TrackingOptionID. Slotted line+ * dimensions with no resolvable option are OMITTED — the warn policy+ * parks in pre-flight before mapping, so an unresolved value here is the+ * recorded drop path.+ */+export type XeroJournalDimensionArgs = {+ slots: ReadonlyArray<+ Pick<PostingSyncDimensionSlot, "dimensionId" | "target">+ >;+ optionIdsByValue: ReadonlyMap<string, string>;+};++export function mapJournalEntryToManualJournal(args: {+ journal: Accounting.JournalEntry;+ accountCodesById: ReadonlyMap<string, string>;+ pushDate: string;+ redatedFromDate?: string;+ existingRemoteId?: string | null;+ dimensions?: XeroJournalDimensionArgs;+}): Omit<Xero.ManualJournal, "UpdatedDateUTC"> {+ const { journal } = args;+ const sign = journal.reversal ? -1 : 1;++ const journalLines: Xero.ManualJournalLine[] = journal.lines.map((line) => {+ const accountCode = line.accountId+ ? args.accountCodesById.get(line.accountId)+ : undefined;++ if (!accountCode) {+ // runJournalEntryPreflight fails before mapping; this guards direct+ // callers (consolidation, tests) against unmapped input+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `No Xero account code mapped for account ${+ line.accountId ?? "(none)"+ } on journal ${journal.journalEntryId}`,+ warning: true,+ metadata: {+ unmappedAccountIds: line.accountId ? [line.accountId] : []+ }+ });+ }++ const tracking: Xero.ManualJournalTracking[] = [];+ if (args.dimensions) {+ for (const slot of args.dimensions.slots) {+ const trackingCategoryId = parseXeroTrackingTarget(slot.target);+ if (!trackingCategoryId) continue;+ const dimension = line.dimensions?.find(+ (candidate) => candidate.dimensionId === slot.dimensionId+ );+ if (!dimension) continue;+ const trackingOptionId = args.dimensions.optionIdsByValue.get(+ buildDimensionValueMappingEntityId(+ dimension.dimensionId,+ dimension.valueId+ )+ );+ if (!trackingOptionId) continue; // drop policy — recorded by the caller+ tracking.push({+ TrackingCategoryID: trackingCategoryId,+ TrackingOptionID: trackingOptionId+ });+ }+ }++ return {+ LineAmount: roundCurrency(sign * line.amount),+ AccountCode: accountCode,+ Description: line.description ?? journal.description ?? undefined,+ TaxType: "NONE",+ ...(tracking.length > 0 ? { Tracking: tracking } : {})+ };+ });++ let narration = journal.reversal+ ? `Carbon reversal of ${journal.journalEntryId}`+ : `Carbon ${journal.journalEntryId} ${journal.id}`;+ if (args.redatedFromDate) {+ narration += ` | original date ${args.redatedFromDate}`;+ }++ return {+ ManualJournalID: args.existingRemoteId!,+ Narration: narration,+ Date: args.pushDate,+ Status: "POSTED",+ JournalLines: journalLines+ };+}++export class JournalEntrySyncer extends BaseEntitySyncer<+ Accounting.JournalEntry,+ Xero.ManualJournal,+ "UpdatedDateUTC"+> {+ // Per-instance caches — a drain reuses one syncer across its claimed+ // operations, so settings, mappings, control accounts and the Xero org+ // lock date are each fetched at most once per drain+ private postingSyncSettingsPromise?: Promise<PostingSyncSettings>;+ private accountCodesByIdPromise?: Promise<Map<string, string>>;+ private controlAccountIdsPromise?: Promise<Set<string>>;+ private lockDatePromise?: Promise<string | null>;+ private dimensionValueMappingsPromise?: Promise<Map<string, string>>;++ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }++ /**+ * `<dimensionId>:<valueId>` → Xero TrackingOptionID from the+ * dimension-value mapping rows (entityType "dimensionValue"). Mutated+ * in place by the autoCreate flow so later pushes in the same drain+ * reuse the created options.+ */+ public getDimensionValueMappings(): Promise<Map<string, string>> {+ if (!this.dimensionValueMappingsPromise) {+ this.dimensionValueMappingsPromise = (async () => {+ const mappings = await getDimensionValueMappings(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ if (mappings.error) {+ throw new Error(+ `Failed to load dimension value mappings: ${mappings.error}`+ );+ }+ return buildDimensionValueMappingLookup(mappings.data ?? []);+ })();+ }+ return this.dimensionValueMappingsPromise;+ }++ /**+ * autoCreate (opt-in per slot for Xero): create missing tracking+ * options BY NAME — the value's resolved READABLE label — under the+ * slot's tracking category, then store the mapping and update the+ * lookup in place.+ */+ private async ensureAutoCreatedDimensionValues(+ journal: Accounting.JournalEntry,+ settings: PostingSyncSettings,+ mappings: Map<string, string>+ ): Promise<void> {+ await ensureDimensionValueExternalIds({+ lines: journal.lines,+ slots: settings.dimensionSlots,+ defaultAutoCreate: false, // Xero: opt-in avoids surprise list writes+ mappings,+ resolveLabels: (values) =>+ resolveDimensionValueLabels(this.database, { values }),+ createExternalValue: async (slot, label) => {+ const trackingCategoryId = parseXeroTrackingTarget(slot.target);+ if (!trackingCategoryId) {+ throw new Error(`Unknown Xero dimension target "${slot.target}"`);+ }+ const created = await this.xeroProvider.createTrackingOption(+ trackingCategoryId,+ label+ );+ return created.TrackingOptionID;+ },+ persistMapping: async (value, externalId, label) => {+ const persisted = await upsertDimensionValueMapping(this.database, {+ companyId: this.companyId,+ integration: this.provider.id,+ dimensionId: value.dimensionId,+ valueId: value.valueId,+ externalId,+ externalName: label+ });+ if (persisted.error) {+ throw new Error(+ `Failed to store dimension value mapping: ${persisted.error}`+ );+ }+ }+ });+ }++ // =================================================================+ // 1. SETTINGS + PRE-FLIGHT INPUTS (cached per instance)+ // =================================================================++ /**+ * Per-company posting-sync settings from+ * `companyIntegration.metadata.settings.postingSync`. Public so the+ * drain can gate on `consolidation` ("daily" journals wait for the+ * consolidation cron instead of draining individually).+ */+ public getPostingSyncSettings(): Promise<PostingSyncSettings> {+ if (!this.postingSyncSettingsPromise) {+ this.postingSyncSettingsPromise = (async () => {+ const integration = await this.database+ .selectFrom("companyIntegration")+ .select("metadata")+ .where("id", "=", this.provider.id)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return resolvePostingSyncSettings(integration?.metadata);+ })();+ }+ return this.postingSyncSettingsPromise;+ }++ /**+ * Carbon account.id → Xero account code, from the account-mapping rows+ * (entityType "account"). Mappings without a stored provider account+ * code are treated as unmapped — Xero manual-journal lines require the+ * account CODE. Public (like getPostingSyncSettings) so the+ * daily-consolidation cron runs the same pre-flights on its aggregate.+ */+ public getAccountCodesById(): Promise<Map<string, string>> {+ if (!this.accountCodesByIdPromise) {+ this.accountCodesByIdPromise = (async () => {+ const mappings = await getAccountMappings(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });++ if (mappings.error) {+ throw new Error(`Failed to load account mappings: ${mappings.error}`);+ }++ const codesById = new Map<string, string>();+ for (const mapping of mappings.data ?? []) {+ if (mapping.externalCode) {+ codesById.set(mapping.accountId, mapping.externalCode);+ }+ }+ return codesById;+ })();+ }+ return this.accountCodesByIdPromise;+ }++ /**+ * AR/AP control accounts (accountDefault.receivablesAccount /+ * payablesAccount) — journal lines on these never push. Public for the+ * daily-consolidation cron (same pre-flight inputs as individual pushes).+ */+ public getControlAccountIds(): Promise<Set<string>> {+ if (!this.controlAccountIdsPromise) {+ this.controlAccountIdsPromise = (async () => {+ const defaults = await this.database+ .selectFrom("accountDefault")+ .select(["receivablesAccount", "payablesAccount"])+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return new Set(+ [defaults?.receivablesAccount, defaults?.payablesAccount].filter(+ (id): id is string => typeof id === "string" && id.length > 0+ )+ );+ })();+ }+ return this.controlAccountIdsPromise;+ }++ /**+ * The effective lock date (YYYY-MM-DD): max of the Xero organisation's+ * PeriodLockDate and EndOfYearLockDate plus the manually captured+ * settings.lockDate when present; null when none is set. Fetched once+ * per syncer instance. If the organisation fetch fails the org lock is+ * treated as unknown — Xero itself still rejects locked-period postings,+ * so the push fails with the provider's message instead of parking+ * everything. Public for the daily-consolidation cron (same pre-flight+ * inputs as individual pushes).+ */+ public getLockDate(settings: PostingSyncSettings): Promise<string | null> {+ if (!this.lockDatePromise) {+ this.lockDatePromise = (async () => {+ const candidates: string[] = [];++ const organisation = await this.xeroProvider.getOrganisation();+ for (const raw of [+ organisation?.PeriodLockDate,+ organisation?.EndOfYearLockDate+ ]) {+ if (!raw) continue;+ const parsed = parseDotnetDate(raw);+ if (!Number.isNaN(parsed.getTime())) {+ candidates.push(parsed.toISOString().slice(0, 10));+ }+ }++ if (settings.lockDate) {+ candidates.push(settings.lockDate.slice(0, 10));+ }++ if (candidates.length === 0) return null;+ candidates.sort();+ return candidates[candidates.length - 1] ?? null;+ })();+ }+ return this.lockDatePromise;+ }++ // =================================================================+ // 2. TIMESTAMP EXTRACTION+ // =================================================================++ protected getRemoteUpdatedAt(remote: Xero.ManualJournal): Date | null {+ if (!remote.UpdatedDateUTC) return null;+ return parseDotnetDate(remote.UpdatedDateUTC);+ }++ // =================================================================+ // 3. LOCAL FETCH (Single + Batch)+ // =================================================================++ async fetchLocal(entityId: string): Promise<Accounting.JournalEntry | null> {+ const { journalId, reversal } = parseJournalEntrySyncEntityId(entityId);++ const journal = await this.database+ .selectFrom("journal")+ .select([+ "id",+ "companyId",+ "journalEntryId",+ "description",+ "postingDate",+ "status",+ "sourceType",+ "reversalOfId",+ "reversedById",+ "postedAt",+ "createdAt",+ "updatedAt"+ ])+ .where("id", "=", journalId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (!journal) return null;++ const lines = await this.database+ .selectFrom("journalLine")+ .leftJoin("account", "account.id", "journalLine.accountId")+ .select([+ "journalLine.id",+ "journalLine.accountId",+ "journalLine.amount",+ "journalLine.description",+ "account.class as accountClass"+ ])+ .where("journalId", "=", journalId)+ .where("companyId", "=", this.companyId)+ .orderBy("journalLineReference", "asc")+ .execute();++ const dimensionsByLine = await loadJournalLineDimensions(this.database, {+ companyId: this.companyId,+ journalLineIds: lines.map((line) => line.id)+ });++ return {+ id: journal.id,+ companyId: journal.companyId,+ journalEntryId: journal.journalEntryId,+ description: journal.description ?? null,+ postingDate: toPostingDateString(journal.postingDate),+ status: journal.status,+ sourceType: journal.sourceType ?? null,+ reversalOfId: journal.reversalOfId ?? null,+ reversedById: journal.reversedById ?? null,+ reversal,+ lines: lines.map((line) => {+ const dimensions = dimensionsByLine.get(line.id);+ return {+ id: line.id,+ accountId: line.accountId ?? null,+ // Carbon stores natural-balance-signed amounts; the engine expects+ // debit-signed (see toDebitSignedAmount)+ amount: toDebitSignedAmount(+ line.accountClass,+ Number(line.amount) || 0+ ),+ description: line.description ?? null,+ ...(dimensions ? { dimensions } : {})+ };+ }),+ updatedAt: journal.updatedAt ?? journal.postedAt ?? journal.createdAt+ };+ }++ protected async fetchLocalBatch(+ ids: string[]+ ): Promise<Map<string, Accounting.JournalEntry>> {+ const result = new Map<string, Accounting.JournalEntry>();+ for (const id of ids) {+ const journal = await this.fetchLocal(id);+ if (journal) result.set(id, journal);+ }+ return result;+ }++ // =================================================================+ // 4. REMOTE FETCH (Single + Batch)+ // =================================================================++ async fetchRemote(id: string): Promise<Xero.ManualJournal | null> {+ return this.xeroProvider.getManualJournal(id);+ }++ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Xero.ManualJournal>> {+ const result = new Map<string, Xero.ManualJournal>();+ for (const id of ids) {+ const journal = await this.xeroProvider.getManualJournal(id);+ if (journal) result.set(journal.ManualJournalID, journal);+ }+ return result;+ }++ // =================================================================+ // 5. SHOULD SYNC (skip-reason gate)+ // =================================================================++ protected async shouldSync(+ context: ShouldSyncContext<Accounting.JournalEntry, Xero.ManualJournal>+ ): Promise<boolean | string> {+ if (context.direction === "pull") {+ return "Journal entries are push-only; pulling manual journals from Xero is not supported";+ }++ const local = context.localEntity;+ if (!local) return "Journal could not be loaded";++ // Idempotency: a mapped journal push is never repeated+ if (!context.isFirstSync) {+ return "Journal already pushed to Xero (mapping exists)";+ }++ if (local.reversal) {+ if (local.status !== "Reversed") {+ return `Reversal push requires a Reversed journal (current status: ${local.status})`;+ }+ // Reversal-by-reference: only reverse what was actually pushed+ const originalRemoteId = await this.getRemoteId(local.id);+ if (!originalRemoteId) {+ return `Original journal ${local.journalEntryId} was never pushed to Xero; nothing to reverse`;+ }+ } else if (local.status !== "Posted") {+ return `Journal must be Posted before syncing (current status: ${local.status})`;+ }++ const settings = await this.getPostingSyncSettings();+ const sourceTypeSkipReason = getPostingSyncSourceTypeSkipReason(+ local.sourceType,+ settings,+ {+ inventoryAdjustmentEntitySyncEnabled:+ this.provider.getSyncConfig("inventoryAdjustment")?.enabled ?? false+ }+ );+ if (sourceTypeSkipReason) return sourceTypeSkipReason;++ return true;+ }++ // =================================================================+ // 6. TRANSFORMATION (Carbon -> Xero) with pre-flight+ // =================================================================++ protected async mapToRemote(+ local: Accounting.JournalEntry+ ): Promise<Omit<Xero.ManualJournal, "UpdatedDateUTC">> {+ const settings = await this.getPostingSyncSettings();+ const accountCodesById = await this.getAccountCodesById();+ const controlAccountIds = await this.getControlAccountIds();+ const lockDate = await this.getLockDate(settings);++ // Dimension slots: resolve the value-mapping lookup and auto-create+ // missing tracking options (opt-in per slot) BEFORE pre-flight so+ // freshly created options never park as unmapped+ let dimensionValueMappings: Map<string, string> | undefined;+ if (settings.dimensionSlots.length > 0) {+ dimensionValueMappings = await this.getDimensionValueMappings();+ await this.ensureAutoCreatedDimensionValues(+ local,+ settings,+ dimensionValueMappings+ );+ }++ const preflight = runJournalEntryPreflight({+ journal: local,+ accountCodesById,+ controlAccountIds,+ lockDate,+ settings,+ dimensionValueMappings+ });++ if (preflight.failure) {+ throw new JournalEntrySyncError(preflight.failure);+ }++ if (preflight.droppedDimensionValues?.length) {+ // "drop" policy: pushed without these dimensions. The drain has no+ // success-metadata channel yet, so the record lives in the logs.+ console.warn("[JournalEntrySyncer] dropped unmapped dimension values", {+ journalId: local.id,+ droppedDimensionValues: preflight.droppedDimensionValues+ });+ }++ return mapJournalEntryToManualJournal({+ journal: local,+ accountCodesById,+ pushDate: preflight.pushDate,+ redatedFromDate: preflight.redatedFromDate,+ ...(dimensionValueMappings+ ? {+ dimensions: {+ slots: settings.dimensionSlots,+ optionIdsByValue: dimensionValueMappings+ }+ }+ : {})+ });+ }++ // =================================================================+ // 7. TRANSFORMATION (Xero -> Carbon) - Not supported (push-only)+ // =================================================================++ protected async mapToLocal(+ _remote: Xero.ManualJournal+ ): Promise<Partial<Accounting.JournalEntry>> {+ throw new Error(+ "Journal entries are push-only. Cannot map from Xero to Carbon."+ );+ }++ protected async upsertLocal(+ _tx: KyselyTx,+ _data: Partial<Accounting.JournalEntry>,+ _remoteId: string+ ): Promise<string> {+ throw new Error(+ "Journal entries are push-only. Cannot upsert locally from Xero."+ );+ }++ // =================================================================+ // 8. UPSERT REMOTE (Single + Batch)+ // =================================================================++ protected async upsertRemote(+ data: Omit<Xero.ManualJournal, "UpdatedDateUTC">,+ localId: string+ ): Promise<string> {+ const existingRemoteId = await this.getRemoteId(localId);+ const created = await this.xeroProvider.createManualJournal(+ existingRemoteId ? { ...data, ManualJournalID: existingRemoteId } : data+ );+ return created.ManualJournalID;+ }++ protected async upsertRemoteBatch(+ data: Array<{+ localId: string;+ payload: Omit<Xero.ManualJournal, "UpdatedDateUTC">;+ }>+ ): Promise<Map<string, string>> {+ const result = new Map<string, string>();+ // One journal per POST keeps per-journal idempotency simple; journal+ // volumes per drain are small (claim limit 20)+ for (const { localId, payload } of data) {+ const remoteId = await this.upsertRemote(payload, localId);+ result.set(localId, remoteId);+ }+ return result;+ }++ // =================================================================+ // 9. PUSH WORKFLOW (structured pre-flight failures)+ // =================================================================++ /**+ * Reimplements the base push workflow so pre-flight failures reach the+ * caller as structured JournalEntrySyncFailure objects on+ * `SyncResult.error` (the base catch flattens every throw to a string,+ * which would lose errorCode/warning/metadata). Also replaces the base+ * lastSyncedAt bailout with a hard skip-when-mapped: posted journals are+ * immutable, so an existing mapping means the push already happened.+ */+ async pushToAccounting(entityId: string): Promise<SyncResult> {+ if (!this.config.enabled) {+ return {+ status: "skipped",+ action: "none",+ error: "Sync disabled in config"+ };+ }++ try {+ const existingMapping = await this.mappingService.getByEntity(+ this.entityType,+ entityId,+ this.provider.id+ );++ if (existingMapping?.externalId) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ remoteId: existingMapping.externalId,+ error: "Journal already pushed to Xero — skipping (idempotent)"+ };+ }++ const localEntity = await this.fetchLocal(entityId);+ if (!localEntity) {+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: `Entity ${entityId} not found in Carbon`+ };+ }++ const shouldSyncResult = await this.shouldSync({+ direction: "push",+ localEntity,+ isFirstSync: true,+ entityId+ });++ if (shouldSyncResult !== true) {+ return {+ status: "skipped",+ action: "none",+ localId: entityId,+ error:+ typeof shouldSyncResult === "string"+ ? shouldSyncResult+ : "Entity not eligible for sync"+ };+ }++ const remotePayload = await this.mapToRemote(localEntity);+ const remoteId = await this.upsertRemote(remotePayload, entityId);++ await withTriggersDisabled(this.database, async (tx) => {+ await this.linkEntities(tx, entityId, remoteId);+ });++ return {+ status: "success",+ action: "created",+ localId: entityId,+ remoteId+ };+ } catch (err) {+ if (err instanceof JournalEntrySyncError) {+ console.error("[JournalEntrySyncer] pre-flight failure", {+ entityId,+ ...err.failure+ });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err.failure+ };+ }++ console.error("[JournalEntrySyncer] push failed", { entityId, err });+ return {+ status: "error",+ action: "none",+ localId: entityId,+ error: err instanceof Error ? err.message : String(err)+ };+ }+ }++ /**+ * Batch push composes the overridden single push so structured pre-flight+ * failures survive the batch path too — the base implementation runs its+ * own catch-and-flatten loop, which would reduce JournalEntrySyncError to+ * a string for drains that push journals in groups (individual-mode+ * posting sync). Journals arrive in claim-sized batches (≤20), so a+ * sequential loop costs nothing.+ */+ async pushBatchToAccounting(entityIds: string[]): Promise<BatchSyncResult> {+ const results: SyncResult[] = [];++ for (const entityId of entityIds) {+ results.push(await this.pushToAccounting(entityId));+ }++ return {+ results,+ successCount: results.filter((r) => r.status === "success").length,+ errorCount: results.filter((r) => r.status === "error").length,+ skippedCount: results.filter((r) => r.status === "skipped").length+ };+ }++ // =================================================================+ // 10. PULL WORKFLOW - Not supported (push-only)+ // =================================================================++ async pullFromAccounting(remoteId: string): Promise<SyncResult> {+ return {+ status: "error",+ action: "none",+ remoteId,+ error:+ "Journal entries are push-only: pulling manual journals from Xero into Carbon is not supported"+ };+ }++ async pullBatchFromAccounting(remoteIds: string[]): Promise<BatchSyncResult> {+ const results: SyncResult[] = remoteIds.map((remoteId) => ({+ status: "error",+ action: "none",+ remoteId,+ error:+ "Journal entries are push-only: pulling manual journals from Xero into Carbon is not supported"+ }));++ return {+ results,+ successCount: 0,+ errorCount: results.length,+ skippedCount: 0+ };+ }+}diff --git a/packages/ee/src/accounting/providers/xero/entities/payment.ts b/packages/ee/src/accounting/providers/xero/entities/payment.tsnew file mode 100644index 0000000000..cba7b251c3--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/entities/payment.ts@@ -0,0 +1,315 @@+import { loadAccountCodesById } from "../../../core/account-mapping";+import type { NormalizedPayment } from "../../../core/payment-application";+import {+ type PaymentPushContext,+ PaymentSyncerBase+} from "../../../core/payment-syncer";+import { JournalEntrySyncError } from "../../../core/posting";+import type { ShouldSyncContext } from "../../../core/types";+import { parseDotnetDate, type Xero } from "../models";+import type { XeroProvider } from "../provider";++/**+ * XeroPaymentSyncer — the two-way payment syncer for Xero, on the shared+ * family-agnostic `PaymentSyncerBase`. A Xero `Payment` (on the /Payments+ * endpoint) settles exactly ONE invoice: an ACCPAY invoice (a bill → AP,+ * settling a Carbon purchaseInvoice) or an ACCREC invoice (a sales invoice →+ * AR, settling a Carbon salesInvoice). The base writes a Draft `payment` ++ * `invoiceSettlement` and then invokes the native `post-payment` edge function+ * (GL journal + Posted/Voided status). Two-way as of Phase G: a Carbon-born+ * Posted payment pushes back out as a Xero `/Payments` document (see+ * `pushRemotePayment`).+ *+ * Entity-id contract: the sync operation's entityId is a COMPOSITE, identical+ * to the Rillet AP reference. AR keeps the prefix-less+ * `"<invoiceRemoteId>:<paymentRemoteId>"` form; AP uses a+ * `"bill:<invoiceRemoteId>:<paymentRemoteId>"` form. The `bill:` prefix marks+ * AP and is the family discriminator the syncer branches on. The "document" is+ * the settled Xero invoice's `InvoiceID` (mapped under entityType "invoice" for+ * ACCREC / "bill" for ACCPAY). Xero payments settle exactly one invoice, so+ * there is no multi-document fan-out — one `documentRemoteId`/`amount`.+ */++const SYNC_ID_SEPARATOR = ":";+/** AP composite-id family discriminator prefix. AR is prefix-less. */+const BILL_PREFIX = "bill:";++/** Composite sync entity id for a Xero ACCREC (sales invoice) payment — AR. */+export function getXeroPaymentSyncEntityId(+ invoiceRemoteId: string,+ paymentRemoteId: string+): string {+ return `${invoiceRemoteId}${SYNC_ID_SEPARATOR}${paymentRemoteId}`;+}++/** Composite sync entity id for a Xero ACCPAY (bill) payment — AP (`bill:`). */+export function getXeroBillPaymentSyncEntityId(+ invoiceRemoteId: string,+ paymentRemoteId: string+): string {+ return `${BILL_PREFIX}${invoiceRemoteId}${SYNC_ID_SEPARATOR}${paymentRemoteId}`;+}++/**+ * Split a composite payment entity id into its family, document (invoice)+ * remote id, and payment remote id. A `bill:` prefix marks the AP form;+ * anything else is the AR form. Throws on a malformed id.+ */+export function parseXeroPaymentSyncEntityId(entityId: string): {+ family: "ar" | "ap";+ documentRemoteId: string;+ paymentRemoteId: string;+} {+ const isBill = entityId.startsWith(BILL_PREFIX);+ const remainder = isBill ? entityId.slice(BILL_PREFIX.length) : entityId;++ const separatorIndex = remainder.indexOf(SYNC_ID_SEPARATOR);+ if (separatorIndex <= 0 || separatorIndex === remainder.length - 1) {+ throw new Error(+ `Invalid Xero payment sync entity id "${entityId}" — expected "<invoiceRemoteId>:<paymentRemoteId>" or "bill:<invoiceRemoteId>:<paymentRemoteId>"`+ );+ }+ return {+ family: isBill ? "ap" : "ar",+ documentRemoteId: remainder.slice(0, separatorIndex),+ paymentRemoteId: remainder.slice(separatorIndex + 1)+ };+}++/**+ * Xero's Payment `Date` is usually a plain `YYYY-MM-DD` (sometimes+ * `YYYY-MM-DDT00:00:00`), but be defensive about the serialized .NET+ * `/Date(...)/` form some responses use. Returns the YYYY-MM-DD date part.+ */+export function getXeroPaymentDate(raw: string | undefined): string {+ if (!raw) return new Date().toISOString().slice(0, 10);+ if (raw.startsWith("/Date(")) {+ return parseDotnetDate(raw).toISOString().slice(0, 10);+ }+ return raw.slice(0, 10);+}++export class XeroPaymentSyncer extends PaymentSyncerBase<Xero.Payment> {+ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }++ /** Xero accepts Carbon-born payments back out (Phase G). */+ protected supportsPaymentPush = true;++ /** Carbon account.id → Xero account code, read once per syncer instance. */+ private accountCodesByIdPromise?: Promise<Map<string, string>>;++ private getAccountCodesById(): Promise<Map<string, string>> {+ if (!this.accountCodesByIdPromise) {+ this.accountCodesByIdPromise = loadAccountCodesById(this.database, {+ companyId: this.companyId,+ integration: this.provider.id+ });+ }+ return this.accountCodesByIdPromise;+ }++ /** Xero chart of accounts, read once per syncer instance (BANK-type check). */+ private chartOfAccountsPromise?: Promise<Xero.Account[]>;++ private getChartOfAccounts(): Promise<Xero.Account[]> {+ if (!this.chartOfAccountsPromise) {+ this.chartOfAccountsPromise = this.xeroProvider.listChartOfAccounts();+ }+ return this.chartOfAccountsPromise;+ }++ // =================================================================+ // 1. REMOTE FETCH — composite id → GET /Payments/{PaymentID}+ // =================================================================++ async fetchRemote(entityId: string): Promise<Xero.Payment | null> {+ const { paymentRemoteId } = parseXeroPaymentSyncEntityId(entityId);++ const response = await this.xeroProvider.request<{+ Payments: Xero.Payment[];+ }>("GET", `/Payments/${paymentRemoteId}`);++ if (response.error) return null;+ return response.data?.Payments?.[0] ?? null;+ }++ /**+ * Keyed by the COMPOSITE entity id (the base pull workflow uses the map keys+ * as remote ids, and matches results back to operations by entityId). Xero+ * payments are directly addressable, so each is fetched by its PaymentID.+ */+ protected async fetchRemoteBatch(+ ids: string[]+ ): Promise<Map<string, Xero.Payment>> {+ const result = new Map<string, Xero.Payment>();+ for (const entityId of ids) {+ const payment = await this.fetchRemote(entityId);+ if (payment) result.set(entityId, payment);+ }+ return result;+ }++ // =================================================================+ // 2. TIMESTAMP + SHOULD SYNC+ // =================================================================++ protected getRemoteUpdatedAt(remote: Xero.Payment): Date | null {+ if (!remote.UpdatedDateUTC) return null;+ const parsed = parseDotnetDate(remote.UpdatedDateUTC);+ return Number.isNaN(parsed.getTime()) ? null : parsed;+ }++ protected async shouldSync(+ context: ShouldSyncContext<Xero.Payment, Xero.Payment>+ ): Promise<boolean | string> {+ // Push is gated entirely in PaymentSyncerBase.pushToAccounting (origin,+ // documents-mode, single-settlement, FX) — shouldSync only governs the pull.+ const { family, documentRemoteId } = parseXeroPaymentSyncEntityId(+ context.entityId+ );++ // Documents-mode gate: inbound payment sync-back is allowed only when the+ // payment's AR/AP family is in `documents` mode (Carbon owns the settled+ // documents). A `journals`/`none` family does not pull payments — a benign+ // skip, like the ownership skip below. An unconfigured integration defaults+ // to documents.+ if (!(await this.isPaymentSyncbackEnabled(family))) {+ return `payment sync-back is disabled: the ${family} family is not in documents mode`;+ }++ // Ownership gate: the pushed invoice's mapping is the ownership record. No+ // local mapping means the ACCPAY/ACCREC invoice belongs to another Carbon+ // instance or was created directly in Xero — either way there is no Carbon+ // document to settle here, and that is a benign skip, not a failure. Keyed+ // on "bill" (ACCPAY → purchaseInvoice) / "invoice" (ACCREC → salesInvoice).+ const docEntityType = family === "ap" ? "bill" : "invoice";+ const localDocId = await this.mappingService.getEntityId(+ this.provider.id,+ documentRemoteId,+ docEntityType+ );+ if (!localDocId) {+ return `Xero ${docEntityType} ${documentRemoteId} has no Carbon mapping — the payment belongs to another Carbon instance or to a document created directly in Xero`;+ }++ // A payment first seen as DELETED (void) was never recorded — nothing to+ // void. (The AUTHORISED-only poll filter normally excludes these; guard the+ // webhook/direct-fetch path anyway.)+ if (context.remoteEntity?.Status === "DELETED" && context.isFirstSync) {+ return "Voided (DELETED) Xero payment was never recorded in Carbon — nothing to do";+ }++ return true;+ }++ // =================================================================+ // 3. NORMALIZATION (Xero -> family-agnostic NormalizedPayment)+ // =================================================================++ protected mapToNormalized(+ remote: Xero.Payment,+ entityId: string+ ): NormalizedPayment {+ const { family, documentRemoteId, paymentRemoteId } =+ parseXeroPaymentSyncEntityId(entityId);++ return {+ family,+ documentRemoteId,+ paymentRemoteId,+ amount: remote.Amount ?? 0,+ currencyCode: remote.Invoice?.CurrencyCode ?? null,+ exchangeRate: remote.CurrencyRate ?? 1,+ paidDate: getXeroPaymentDate(remote.Date),+ // The Xero PaymentID is the human/provider reference.+ reference: paymentRemoteId,+ status: remote.Status === "DELETED" ? "void" : "settled"+ };+ }++ // =================================================================+ // 4. PUSH (Phase G — Carbon-born payment → Xero /Payments document)+ // =================================================================++ /**+ * Create one Xero payment for the settled invoice. Resolves the settled+ * document's Xero InvoiceID and the bank account's Xero code from the+ * mappings. A missing document mapping → UNSYNCED_DOCUMENT Warning (the+ * invoice/bill must sync first — a dependency-ordering issue, NOT a missing+ * account); a missing bank account code → UNMAPPED_ACCOUNTS Warning (map it on+ * the integration settings page). Xero's /Payments endpoint additionally+ * requires the payment Account to be a BANK-type account with payments+ * enabled — the mapped code is checked against the chart before the PUT so a+ * non-bank code surfaces a fixable Warning instead of an opaque Xero 400. AR+ * (ACCREC) and AP (ACCPAY) both settle through the same /Payments call.+ */+ protected async pushRemotePayment(+ context: PaymentPushContext+ ): Promise<{ remoteId: string; compositeEntityId: string }> {+ const documentRemoteId = await this.mappingService.getExternalId(+ context.family === "ar" ? "invoice" : "bill",+ context.targetDocumentId,+ this.provider.id+ );+ if (!documentRemoteId) {+ throw new JournalEntrySyncError({+ errorCode: "UNSYNCED_DOCUMENT",+ message: `The settled ${+ context.family === "ar" ? "invoice" : "bill"+ } has not synced to Xero yet — sync it, then retry the payment`,+ warning: true,+ metadata: { targetDocumentId: context.targetDocumentId }+ });+ }++ const bankCode = (await this.getAccountCodesById()).get(+ context.bankAccountId+ );+ if (!bankCode) {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `The payment's bank/cash account is not mapped to a Xero account — map it on the integration settings page, then retry`,+ warning: true,+ metadata: { bankAccountId: context.bankAccountId }+ });+ }++ // Xero /Payments rejects a payment whose Account is not a BANK-type account+ // with payments enabled. Resolve the mapped code against the chart and+ // refuse early with a fixable Warning.+ const bankAccount = (await this.getChartOfAccounts()).find(+ (account) => account.Code === bankCode+ );+ // Xero /Payments requires the Account to be Type BANK. `EnablePaymentsToAccount`+ // is NOT the gate here — it enables NON-bank accounts as payment targets; a+ // BANK account always accepts payments even with the flag false (verified on+ // the Xero sandbox 2026-08-14: a payment posted to a BANK account with+ // EnablePaymentsToAccount=false).+ if (!bankAccount || bankAccount.Type !== "BANK") {+ throw new JournalEntrySyncError({+ errorCode: "UNMAPPED_ACCOUNTS",+ message: `The payment's bank/cash account must map to a Xero BANK-type account (mapped code ${bankCode}). Map it to a Xero bank account on the integration settings page, then retry.`,+ warning: true,+ metadata: { bankAccountId: context.bankAccountId, bankCode }+ });+ }++ const payload = {+ Invoice: { InvoiceID: documentRemoteId },+ Account: { Code: bankCode },+ Amount: context.amount,+ Date: context.paidDate+ };++ const remoteId = await this.xeroProvider.createPayment(payload);++ const compositeEntityId =+ context.family === "ar"+ ? getXeroPaymentSyncEntityId(documentRemoteId, remoteId)+ : getXeroBillPaymentSyncEntityId(documentRemoteId, remoteId);++ return { remoteId, compositeEntityId };+ }+}diff --git a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts b/packages/ee/src/accounting/providers/xero/entities/purchase-order.tsindex 3b08246a36..0ed989eea9 100644--- a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts+++ b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts@@ -8,12 +8,6 @@ import {import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";import type { XeroProvider } from "../provider";-import {- xeroCurrencyRate,- xeroMoney,- xeroQuantity,- xeroUnitAmount-} from "../serialize";// Note: This syncer uses the default ID mapping from BaseEntitySyncer// which uses the externalIntegrationMapping table with entityType "purchaseOrder"@@ -92,6 +86,10 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<Xero.PurchaseOrder,"UpdatedDateUTC"> {+ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }+// =================================================================// 1. ID MAPPING - Uses default implementation from BaseEntitySyncer// The entityType "purchaseOrder" maps to the purchaseOrder table@@ -259,7 +257,7 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<// =================================================================async fetchRemote(id: string): Promise<Xero.PurchaseOrder | null> {- const result = await this.provider.request<{+ const result = await this.xeroProvider.request<{PurchaseOrders: Xero.PurchaseOrder[];}>("GET", `/PurchaseOrders/${id}`);@@ -277,7 +275,7 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<const result = new Map<string, Xero.PurchaseOrder>();if (ids.length === 0) return result;- const response = await this.provider.request<{+ const response = await this.xeroProvider.request<{PurchaseOrders: Xero.PurchaseOrder[];}>("GET", `/PurchaseOrders?IDs=${ids.join(",")}`);@@ -316,11 +314,6 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<);}- // Get default account code from provider settings- const xeroProvider = this.provider as XeroProvider;- const defaultAccountCode =- xeroProvider.settings?.defaultPurchaseAccountCode;-// Map line itemsconst lineItems: Xero.PurchaseOrderLineItem[] = await Promise.all(local.lines.map(async (line) => {@@ -347,14 +340,15 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<return {Description: line.description ?? undefined,- Quantity: xeroQuantity(line.quantity),- UnitAmount: xeroUnitAmount(line.unitPrice),+ Quantity: line.quantity,+ UnitAmount: line.unitPrice,ItemCode: itemCode?.slice(0, 30) ?? undefined,- // Use line's account number if specified, otherwise use default from settings- AccountCode: line.accountNumber ?? defaultAccountCode,- TaxAmount:- line.taxAmount != null ? xeroMoney(line.taxAmount) : undefined,- LineAmount: xeroMoney(line.totalAmount),+ // PO is non-posting — Xero accepts PO lines without AccountCode, so+ // only send one when the line actually carries an account number+ // (no blunt default-account-code fallback).+ AccountCode: line.accountNumber ?? undefined,+ TaxAmount: line.taxAmount ?? undefined,+ LineAmount: line.totalAmount,// TaxType is required by Xero: INPUT for purchase tax, NONE for zero taxTaxType: hasTax ? "INPUT" : "NONE"};@@ -374,12 +368,12 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<CurrencyCode: local.currencyCode ?? undefined,CurrencyRate:local.exchangeRate && local.exchangeRate !== 1- ? xeroCurrencyRate(local.exchangeRate)+ ? local.exchangeRate: undefined,LineItems: lineItems,- SubTotal: xeroMoney(local.subtotal),- TotalTax: xeroMoney(local.totalTax),- Total: xeroMoney(local.totalAmount)+ SubTotal: local.subtotal,+ TotalTax: local.totalTax,+ Total: local.totalAmount};}@@ -593,7 +587,7 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<? [{ ...data, PurchaseOrderID: existingRemoteId }]: [data];- const result = await this.provider.request<{+ const result = await this.xeroProvider.request<{PurchaseOrders: Xero.PurchaseOrder[];}>("POST", "/PurchaseOrders", {body: JSON.stringify({ PurchaseOrders: purchaseOrders })@@ -645,7 +639,7 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<localIdOrder.push(localId);}- const response = await this.provider.request<{+ const response = await this.xeroProvider.request<{PurchaseOrders: Xero.PurchaseOrder[];}>("POST", "/PurchaseOrders", {body: JSON.stringify({ PurchaseOrders: purchaseOrders })diff --git a/packages/ee/src/accounting/providers/xero/entities/sales-order.ts b/packages/ee/src/accounting/providers/xero/entities/sales-order.tsindex 1cdc5fc5a6..8c728c4ef2 100644--- a/packages/ee/src/accounting/providers/xero/entities/sales-order.ts+++ b/packages/ee/src/accounting/providers/xero/entities/sales-order.ts@@ -6,12 +6,7 @@ import {} from "../../../core/types";import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";-import {- xeroCurrencyRate,- xeroMoney,- xeroQuantity,- xeroUnitAmount-} from "../serialize";+import type { XeroProvider } from "../provider";// Note: This is a push-only syncer (Carbon -> Xero).// Carbon sales orders are pushed as Xero Quotes since Xero@@ -90,6 +85,10 @@ export class SalesOrderSyncer extends BaseEntitySyncer<Xero.Quote,"UpdatedDateUTC"> {+ private get xeroProvider(): XeroProvider {+ return this.provider as XeroProvider;+ }+// =================================================================// 1. ID MAPPING - Uses default implementation from BaseEntitySyncer// =================================================================@@ -222,7 +221,7 @@ export class SalesOrderSyncer extends BaseEntitySyncer<// =================================================================async fetchRemote(id: string): Promise<Xero.Quote | null> {- const result = await this.provider.request<{ Quotes: Xero.Quote[] }>(+ const result = await this.xeroProvider.request<{ Quotes: Xero.Quote[] }>("GET",`/Quotes/${id}`);@@ -235,7 +234,7 @@ export class SalesOrderSyncer extends BaseEntitySyncer<const result = new Map<string, Xero.Quote>();if (ids.length === 0) return result;- const response = await this.provider.request<{ Quotes: Xero.Quote[] }>(+ const response = await this.xeroProvider.request<{ Quotes: Xero.Quote[] }>("GET",`/Quotes?IDs=${ids.join(",")}`);@@ -276,13 +275,12 @@ export class SalesOrderSyncer extends BaseEntitySyncer<continue;}- const quantity = xeroQuantity(line.quantity);const lineItem: Xero.QuoteLineItem = {Description: line.description ?? undefined,- Quantity: quantity,- UnitAmount: xeroUnitAmount(line.unitPrice),+ Quantity: line.quantity,+ UnitAmount: line.unitPrice,AccountCode: line.accountNumber ?? undefined,- LineAmount: xeroMoney(line.lineAmount)+ LineAmount: line.lineAmount};// If line has an item, ensure it's synced and set ItemCode@@ -308,10 +306,7 @@ export class SalesOrderSyncer extends BaseEntitySyncer<LineAmountTypes: "Exclusive",LineItems: lineItems,CurrencyCode: local.currencyCode,- CurrencyRate:- local.exchangeRate !== 1- ? xeroCurrencyRate(local.exchangeRate)- : undefined,+ CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined,Title: `Sales Order ${local.salesOrderId}`};}@@ -358,7 +353,7 @@ export class SalesOrderSyncer extends BaseEntitySyncer<? [{ ...data, QuoteID: existingRemoteId }]: [data];- const result = await this.provider.request<{ Quotes: Xero.Quote[] }>(+ const result = await this.xeroProvider.request<{ Quotes: Xero.Quote[] }>(method,"/Quotes",{ body: JSON.stringify({ Quotes: quotes }) }@@ -402,7 +397,7 @@ export class SalesOrderSyncer extends BaseEntitySyncer<localIdOrder.push(localId);}- const response = await this.provider.request<{ Quotes: Xero.Quote[] }>(+ const response = await this.xeroProvider.request<{ Quotes: Xero.Quote[] }>("POST","/Quotes",{ body: JSON.stringify({ Quotes: quotes }) }diff --git a/packages/ee/src/accounting/providers/xero/index.ts b/packages/ee/src/accounting/providers/xero/index.tsindex 2c61194c8a..7358d6d1b1 100644--- a/packages/ee/src/accounting/providers/xero/index.ts+++ b/packages/ee/src/accounting/providers/xero/index.ts@@ -1,7 +1,59 @@+import { ProviderID } from "../../core/models";+import { type SyncerRegistry, SyncFactory } from "../../core/sync";+import { BillSyncer } from "./entities/bill";+import { ContactSyncer } from "./entities/contact";+import { InventoryAdjustmentSyncer } from "./entities/inventory-adjustment";+import { SalesInvoiceSyncer } from "./entities/invoice";+import { ItemSyncer } from "./entities/item";+import { JournalEntrySyncer } from "./entities/journal-entry";+import { XeroPaymentSyncer } from "./entities/payment";+import { PurchaseOrderSyncer } from "./entities/purchase-order";+import { SalesOrderSyncer } from "./entities/sales-order";+export * from "./entities/bill";export * from "./entities/contact";export * from "./entities/invoice";export * from "./entities/item";+// journal-entry exports mapJournalEntryToManualJournal + JournalEntrySyncer+// for the daily-consolidation cron (@carbon/jobs), per its doc contract+export * from "./entities/journal-entry";+// payment exports the composite entity-id helpers the inbound Invoice-update+// webhook accelerator uses to enqueue payment operations+export * from "./entities/payment";export * from "./entities/purchase-order";export * from "./models";export * from "./provider";++/**+ * Every syncer Xero implements, keyed by entity type. The module-scope+ * SyncFactory.register call below runs whenever this barrel is imported —+ * every consumer path evaluates it before SyncFactory.getSyncer can be+ * called with a Xero context (`@carbon/ee/accounting` re-exports+ * ./providers, and building a SyncContext requires a provider class from+ * here).+ */+export const xeroSyncerRegistry: SyncerRegistry = {+ // Master Data+ customer: ContactSyncer,+ vendor: ContactSyncer,+ item: ItemSyncer,++ // Transaction Data+ bill: BillSyncer,+ invoice: SalesInvoiceSyncer,+ purchaseOrder: PurchaseOrderSyncer,+ salesOrder: SalesOrderSyncer,+ inventoryAdjustment: InventoryAdjustmentSyncer,++ // Posting sync (push-only journal entries -> Xero Manual Journals)+ journalEntry: JournalEntrySyncer,++ // Pull-only: Xero payments (ACCREC → AR, ACCPAY → AP) settle Carbon+ // sales/purchase invoices. Forced pull-only/enabled by buildXeroSyncConfig.+ payment: XeroPaymentSyncer++ // Not yet implemented:+ // - employee: Xero no longer supports the Employees API+};++SyncFactory.register(ProviderID.XERO, xeroSyncerRegistry);diff --git a/packages/ee/src/accounting/providers/xero/models.ts b/packages/ee/src/accounting/providers/xero/models.tsindex fd0cb5f6f1..a80ab78ad7 100644--- a/packages/ee/src/accounting/providers/xero/models.ts+++ b/packages/ee/src/accounting/providers/xero/models.ts@@ -197,6 +197,42 @@ export namespace Xero {export type InvoiceLineItem = z.infer<typeof InvoiceLineItemSchema>;export type InvoiceContact = z.infer<typeof InvoiceContactSchema>;+ // Payment schemas for the Xero Accounting API /Payments endpoint.+ // A Payment settles exactly ONE invoice — `Invoice.Type` (ACCPAY = bill /+ // AP, ACCREC = sales invoice / AR) is the family discriminator; the settled+ // document is `Invoice.InvoiceID`. `PaymentType` is ACCPAYPAYMENT /+ // ACCRECPAYMENT. `Status` is AUTHORISED (settled) or DELETED (voided).+ // Kept lenient (passthrough + string enums) — Xero adds fields freely and+ // the syncer only reads the ids/amount/date/status it needs.+ export const PaymentInvoiceSchema = z+ .object({+ InvoiceID: z.string(),+ // ACCPAY = Bill (AP), ACCREC = Sales Invoice (AR)+ Type: z.enum(["ACCPAY", "ACCREC"]).optional(),+ InvoiceNumber: z.string().optional(),+ CurrencyCode: z.string().optional()+ })+ .passthrough();++ export const PaymentSchema = z+ .object({+ PaymentID: z.string(),+ Date: z.string().optional(), // YYYY-MM-DD (or serialized /Date(...)/)+ Amount: z.number().optional(),+ Reference: z.string().optional(),+ CurrencyRate: z.number().optional(),+ // ACCRECPAYMENT (AR) | ACCPAYPAYMENT (AP) | ... — lenient+ PaymentType: z.string().optional(),+ // AUTHORISED (settled) | DELETED (void) — lenient+ Status: z.string().optional(),+ Invoice: PaymentInvoiceSchema.optional(),+ UpdatedDateUTC: z.string() // serialized /Date(...)/+ })+ .passthrough();++ export type PaymentInvoice = z.infer<typeof PaymentInvoiceSchema>;+ export type Payment = z.infer<typeof PaymentSchema>;+// Purchase Order schemas for Xero Accounting APIexport const PurchaseOrderLineItemSchema = z.object({LineItemID: z.string().uuid().optional(),@@ -245,6 +281,35 @@ export namespace Xero {>;export type PurchaseOrderContact = z.infer<typeof PurchaseOrderContactSchema>;+ // Tracking category schemas for the Xero TrackingCategories endpoint —+ // Xero's journal analytics (org-wide limit: 2 active categories)+ export const TrackingOptionSchema = z.object({+ TrackingOptionID: z.string().uuid(),+ Name: z.string(),+ Status: z.enum(["ACTIVE", "ARCHIVED", "DELETED"]).optional()+ });++ export type TrackingOption = z.infer<typeof TrackingOptionSchema>;++ export const TrackingCategorySchema = z.object({+ TrackingCategoryID: z.string().uuid(),+ Name: z.string(),+ Status: z.enum(["ACTIVE", "ARCHIVED", "DELETED"]).optional(),+ Options: z.array(TrackingOptionSchema).optional()+ });++ export type TrackingCategory = z.infer<typeof TrackingCategorySchema>;++ /** Tracking assignment on a manual-journal line (ids, never names). */+ export const ManualJournalTrackingSchema = z.object({+ TrackingCategoryID: z.string(),+ TrackingOptionID: z.string()+ });++ export type ManualJournalTracking = z.infer<+ typeof ManualJournalTrackingSchema+ >;+// Manual Journal schemas for Xero Accounting API ManualJournals endpointexport const ManualJournalLineSchema = z.object({LineAmount: z.number(),@@ -252,6 +317,8 @@ export namespace Xero {Description: z.string().optional(),TaxType: z.string().optional(),TaxAmount: z.number().optional(),+ /** Max 2 entries (one per active tracking category). */+ Tracking: z.array(ManualJournalTrackingSchema).optional(),IsBlank: z.boolean().optional()});@@ -338,6 +405,11 @@ export namespace Xero {FinancialYearEndMonth: z.number().optional(),DefaultSalesTax: z.string().optional(),DefaultPurchasesTax: z.string().optional(),+ // Lock dates (serialized /Date(...)/): transactions dated on or before+ // these are locked. PeriodLockDate stops non-advisors; EndOfYearLockDate+ // stops everyone. Posting sync treats the max of both as THE lock date.+ PeriodLockDate: z.string().optional(),+ EndOfYearLockDate: z.string().optional(),ShortCode: z.string().optional(),Edition: z.string().optional(),Class: z.string().optional(),diff --git a/packages/ee/src/accounting/providers/xero/provider.test.ts b/packages/ee/src/accounting/providers/xero/provider.test.tsnew file mode 100644index 0000000000..3cf9dd4bcd--- /dev/null+++ b/packages/ee/src/accounting/providers/xero/provider.test.ts@@ -0,0 +1,344 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_SYNC_CONFIG } from "../../core/models";+import { AccountingApiError } from "../../core/utils";+import { buildXeroSyncConfig, XeroProvider } from "./provider";++const TENANT_ID = "tenant-1";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" }+ });+}++function makeProvider() {+ return new XeroProvider({+ companyId: "company-1",+ clientId: "client-id",+ clientSecret: "client-secret",+ accessToken: "token",+ refreshToken: "refresh",+ tenantId: TENANT_ID,+ syncConfig: DEFAULT_SYNC_CONFIG+ });+}++const fetchMock = vi.fn<typeof fetch>();++beforeEach(() => {+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++const REGION_CATEGORY = {+ TrackingCategoryID: "11111111-1111-1111-1111-111111111111",+ Name: "Region",+ Status: "ACTIVE" as const,+ Options: [+ {+ TrackingOptionID: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",+ Name: "Atlanta",+ Status: "ACTIVE" as const+ }+ ]+};++const ARCHIVED_CATEGORY = {+ TrackingCategoryID: "33333333-3333-3333-3333-333333333333",+ Name: "Old",+ Status: "ARCHIVED" as const,+ Options: []+};++describe("XeroProvider tracking categories (dimensions)", () => {+ it("lists ACTIVE tracking categories with their options", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ TrackingCategories: [REGION_CATEGORY, ARCHIVED_CATEGORY] })+ );++ const categories = await makeProvider().listTrackingCategories();++ expect(String(fetchMock.mock.calls[0]?.[0])).toBe(+ "https://api.xero.com/api.xro/2.0/TrackingCategories"+ );+ const headers = fetchMock.mock.calls[0]?.[1]?.headers as Record<+ string,+ string+ >;+ expect(headers["xero-tenant-id"]).toBe(TENANT_ID);+ expect(categories).toEqual([REGION_CATEGORY]);+ });++ it("returns [] on failure (forgiving settings-surface contract)", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ Message: "boom" }, 500));+ await expect(makeProvider().listTrackingCategories()).resolves.toEqual([]);+ });++ it("creates a tracking option by NAME under a category (autoCreate)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Options: [+ {+ TrackingOptionID: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",+ Name: "Boston",+ Status: "ACTIVE"+ }+ ]+ })+ );++ const created = await makeProvider().createTrackingOption(+ REGION_CATEGORY.TrackingCategoryID,+ "Boston"+ );++ expect(created.TrackingOptionID).toBe(+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"+ );+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe(+ `https://api.xero.com/api.xro/2.0/TrackingCategories/${REGION_CATEGORY.TrackingCategoryID}/Options`+ );+ expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("PUT");+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({+ Name: "Boston"+ });+ });++ it("throws a structured error when Xero rejects the option create", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ Message: "option cap reached" }, 400)+ );++ await expect(+ makeProvider().createTrackingOption(+ REGION_CATEGORY.TrackingCategoryID,+ "Boston"+ )+ ).rejects.toBeInstanceOf(AccountingApiError);+ });++ it("declares one tracking:<categoryId> target per active category", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ TrackingCategories: [REGION_CATEGORY, ARCHIVED_CATEGORY] })+ );++ const targets = await makeProvider().journalDimensionTargets();+ expect(targets).toEqual([+ {+ id: `tracking:${REGION_CATEGORY.TrackingCategoryID}`,+ label: "Region",+ capacity: 1+ }+ ]);+ });+});++describe("XeroProvider.listChanges (SupportsIncrementalPull — payments)", () => {+ const SINCE = "2026-08-01T10:15:30.500Z";++ it("emits payment ProviderChanges (AP + AR) with composite ids and deps", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Payments: [+ {+ PaymentID: "pay-ap-1",+ Amount: 500,+ Status: "AUTHORISED",+ PaymentType: "ACCPAYPAYMENT",+ Invoice: { InvoiceID: "bill-remote-1", Type: "ACCPAY" },+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ },+ {+ PaymentID: "pay-ar-1",+ Amount: 125,+ Status: "AUTHORISED",+ PaymentType: "ACCRECPAYMENT",+ Invoice: { InvoiceID: "inv-remote-1", Type: "ACCREC" },+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ }+ ]+ })+ );++ const { changes } = await makeProvider().listChanges({ since: SINCE });++ // Single page (fewer than 100) → one request.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const url = String(fetchMock.mock.calls[0]?.[0]);+ expect(url).toContain("/Payments?");+ expect(url).toContain("page=1");+ // No status filter — the poll must surface DELETED payments so the void+ // path fires; AUTHORISED-only would make deletes unreachable.+ expect(decodeURIComponent(url)).not.toContain("where=Status");+ const headers = fetchMock.mock.calls[0]?.[1]?.headers as Record<+ string,+ string+ >;+ // Whole-second UTC (milliseconds dropped) sent as If-Modified-Since.+ expect(headers["If-Modified-Since"]).toBe(+ new Date("2026-08-01T10:15:30Z").toUTCString()+ );++ expect(changes).toEqual([+ {+ entityType: "payment",+ remoteId: "bill:bill-remote-1:pay-ap-1",+ updatedAt: new Date(1785542400000).toISOString(),+ dependsOnMapping: { entityType: "bill", remoteId: "bill-remote-1" }+ },+ {+ entityType: "payment",+ remoteId: "inv-remote-1:pay-ar-1",+ updatedAt: new Date(1785542400000).toISOString(),+ dependsOnMapping: { entityType: "invoice", remoteId: "inv-remote-1" }+ }+ ]);+ });++ it("skips a payment with no settled invoice", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Payments: [+ {+ PaymentID: "orphan-1",+ Amount: 10,+ Status: "AUTHORISED",+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ }+ ]+ })+ );++ const { changes } = await makeProvider().listChanges({ since: SINCE });+ expect(changes).toEqual([]);+ });++ it("surfaces both AUTHORISED and DELETED payments as changes (void reachable)", async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({+ Payments: [+ {+ PaymentID: "pay-live-1",+ Amount: 500,+ Status: "AUTHORISED",+ PaymentType: "ACCPAYPAYMENT",+ Invoice: { InvoiceID: "bill-remote-1", Type: "ACCPAY" },+ UpdatedDateUTC: "/Date(1785542400000+0000)/"+ },+ {+ PaymentID: "pay-deleted-1",+ Amount: 125,+ Status: "DELETED",+ PaymentType: "ACCRECPAYMENT",+ Invoice: { InvoiceID: "inv-remote-1", Type: "ACCREC" },+ UpdatedDateUTC: "/Date(1785628800000+0000)/"+ }+ ]+ })+ );++ const { changes } = await makeProvider().listChanges({ since: SINCE });++ // Both statuses become payment changes; the DELETED one still carries its+ // invoice dependency so the sweep can resolve the local document mapping.+ expect(changes).toEqual([+ {+ entityType: "payment",+ remoteId: "bill:bill-remote-1:pay-live-1",+ updatedAt: new Date(1785542400000).toISOString(),+ dependsOnMapping: { entityType: "bill", remoteId: "bill-remote-1" }+ },+ {+ entityType: "payment",+ remoteId: "inv-remote-1:pay-deleted-1",+ updatedAt: new Date(1785628800000).toISOString(),+ dependsOnMapping: { entityType: "invoice", remoteId: "inv-remote-1" }+ }+ ]);+ });+});++describe("buildXeroSyncConfig — payment force-enable (two-way)", () => {+ it("force-enables `payment` as two-way even when the stored config disables it", () => {+ // DEFAULT_SYNC_CONFIG ships `payment` disabled — the provider must override+ // it so two-way payment sync (Phase G push + inbound pull) works as soon as the+ // integration connects.+ expect(DEFAULT_SYNC_CONFIG.entities.payment.enabled).toBe(false);++ const stored = structuredClone(DEFAULT_SYNC_CONFIG);+ stored.entities.payment = {+ enabled: false,+ direction: "two-way",+ owner: "carbon"+ };++ expect(buildXeroSyncConfig(stored).entities.payment).toEqual({+ enabled: true,+ direction: "two-way",+ owner: "accounting"+ });+ });++ it("exposes the forced payment config through a constructed provider's getSyncConfig", () => {+ expect(makeProvider().getSyncConfig("payment")).toEqual({+ enabled: true,+ direction: "two-way",+ owner: "accounting"+ });+ });+});++describe("buildXeroSyncConfig — Carbon-owned master + documents", () => {+ it.each([+ "customer",+ "vendor",+ "item",+ "invoice",+ "bill"+ ] as const)("forces `%s` to push-only + owner carbon regardless of the stored config", (entityType) => {+ const stored = structuredClone(DEFAULT_SYNC_CONFIG);+ // Pretend the company had previously set this entity accounting-owned+ // two-way (the old Source of Truth default) — the force must override it.+ stored.entities[entityType] = {+ enabled: true,+ direction: "two-way",+ owner: "accounting"+ };++ expect(buildXeroSyncConfig(stored).entities[entityType]).toEqual({+ enabled: true,+ direction: "push-to-accounting",+ owner: "carbon"+ });+ });++ it("preserves the per-company `enabled` flag while forcing ownership", () => {+ const stored = structuredClone(DEFAULT_SYNC_CONFIG);+ stored.entities.bill = {+ enabled: false,+ direction: "two-way",+ owner: "accounting"+ };++ expect(buildXeroSyncConfig(stored).entities.bill).toEqual({+ enabled: false,+ direction: "push-to-accounting",+ owner: "carbon"+ });+ });++ it("leaves payment accounting-owned and does not touch unforced entities", () => {+ const applied = buildXeroSyncConfig(structuredClone(DEFAULT_SYNC_CONFIG));+ // payment stays the accounting-owned pull-only exception+ expect(applied.entities.payment.owner).toBe("accounting");+ // purchaseOrder is neither Carbon-owned-forced nor payment — passes through+ expect(applied.entities.purchaseOrder).toEqual(+ DEFAULT_SYNC_CONFIG.entities.purchaseOrder+ );+ });+});diff --git a/packages/ee/src/accounting/providers/xero/provider.ts b/packages/ee/src/accounting/providers/xero/provider.tsindex 502100150c..e8f40eddb3 100644--- a/packages/ee/src/accounting/providers/xero/provider.ts+++ b/packages/ee/src/accounting/providers/xero/provider.ts@@ -4,16 +4,26 @@ import type {AccountingEntityType,AuthProvider,BaseProvider,+ DimensionTarget,GlobalSyncConfig,+ ListChangesResult,+ ProviderCapabilities,+ ProviderChange,ProviderConfig,- ProviderCredentials+ ProviderCredentials,+ SupportsIncrementalPull} from "../../core/types";import {createOAuthClient,HTTPClient,- type HttpResponse+ type HttpResponse,+ throwXeroApiError} from "../../core/utils";-import type { Xero } from "./models";+import {+ getXeroBillPaymentSyncEntityId,+ getXeroPaymentSyncEntityId+} from "./entities/payment";+import { parseDotnetDate, type Xero } from "./models";const logger = getLogger("ee", "accounting", "xero");@@ -41,9 +51,144 @@ export interface ListItemsResponse {page: number;}-export interface XeroSettings {- defaultSalesAccountCode?: string;- defaultPurchaseAccountCode?: string;+/**+ * Xero's org-wide limit: at most 2 ACTIVE tracking categories, so at most+ * 2 dimension slots. Kept as an exported constant (not on `capabilities`)+ * because XeroProvider deliberately leaves `capabilities` undeclared —+ * absent capabilities = legacy REST provider for the drain.+ */+export const XERO_MAX_JOURNAL_DIMENSION_SLOTS = 2;++/** Dimension slot target prefix: `tracking:<TrackingCategoryID>`. */+const XERO_TRACKING_TARGET_PREFIX = "tracking:";++export function buildXeroTrackingTarget(trackingCategoryId: string): string {+ return `${XERO_TRACKING_TARGET_PREFIX}${trackingCategoryId}`;+}++/** The TrackingCategoryID inside a `tracking:<id>` target; null otherwise. */+export function parseXeroTrackingTarget(target: string): string | null {+ if (!target.startsWith(XERO_TRACKING_TARGET_PREFIX)) return null;+ const categoryId = target.slice(XERO_TRACKING_TARGET_PREFIX.length);+ return categoryId.length > 0 ? categoryId : null;+}++// /********************************************************\+// * Sync-config constraints *+// \********************************************************/++/**+ * Entities Xero syncs TWO-WAY: `payment`. Inbound (pull) — Xero payments (both+ * AR ACCREC and AP ACCPAY) settle Carbon invoices/bills (Phase F). Outbound+ * (push) — Carbon-born Posted payments are written to Xero as `/Payments`+ * documents so the settled ACCREC/ACCPAY invoice closes (Phase G). Which+ * direction fires per record is decided by origin: a payment already carrying a+ * `payment` mapping is provider-known and skips push; a mapping-less Carbon+ * payment is pushed. Forced two-way AND enabled — both halves must work as soon+ * as the integration is connected (there is no per-company toggle for it; the+ * documents-mode families gate governs whether it actually runs). Mirrors+ * Rillet's RILLET_TWO_WAY_ENTITIES.+ */+export const XERO_TWO_WAY_ENTITIES = [+ "payment"+] as const satisfies readonly AccountingEntityType[];++/**+ * Master + document entities for which Carbon is the system of record:+ * customers, vendors, items, sales invoices, and bills. Forced+ * `push-to-accounting` / `owner: "carbon"` so Xero is a downstream mirror —+ * Carbon's edits always win, and an inbound Xero change to a linked record is+ * skipped by BaseEntitySyncer's owner guard. This is the standardized "Carbon+ * owns everything" stance that replaced the per-entity Source of Truth setting;+ * it mirrors Rillet's RILLET_PUSH_ONLY_ENTITIES. Their per-company `enabled`+ * flag survives — this constrains ownership, not whether they sync. `payment`+ * is deliberately excluded: the accounting system owns payments (see+ * XERO_TWO_WAY_ENTITIES).+ */+export const XERO_CARBON_OWNED_ENTITIES = [+ "customer",+ "vendor",+ "item",+ "invoice",+ "bill"+] as const satisfies readonly AccountingEntityType[];++/**+ * Constrain a resolved sync config to Xero's capabilities and Carbon's+ * ownership stance: customers/vendors/items/invoices/bills forced push-only ++ * owner "carbon" (Carbon owns them); `payment` forced two-way + enabled (the+ * accounting system owns it; Carbon-born payments push back out — Phase G).+ * Everything else passes through as resolved.+ */+export function buildXeroSyncConfig(+ resolved: GlobalSyncConfig+): GlobalSyncConfig {+ const entities = Object.fromEntries(+ Object.entries(resolved.entities).map(([entityType, entityConfig]) => [+ entityType,+ { ...entityConfig }+ ])+ ) as GlobalSyncConfig["entities"];++ for (const entityType of XERO_CARBON_OWNED_ENTITIES) {+ entities[entityType] = {+ ...entities[entityType],+ direction: "push-to-accounting",+ owner: "carbon"+ };+ }++ for (const entityType of XERO_TWO_WAY_ENTITIES) {+ entities[entityType] = {+ ...entities[entityType],+ direction: "two-way",+ owner: "accounting",+ enabled: true+ };+ }++ // Always-on: automated postings sync whenever the integration is connected.+ // Forced here (defense-in-depth over the DEFAULT_SYNC_CONFIG default) so a+ // stale stored `enabled: false` override can't silently turn journals off.+ entities.journalEntry = { ...entities.journalEntry, enabled: true };++ return { entities };+}++function getOAuth2Credentials(+ credentials: ProviderCredentials+): Extract<ProviderCredentials, { type: "oauth2" }> {+ if (credentials.type !== "oauth2") {+ throw new Error(+ `Xero requires oauth2 credentials, received "${credentials.type}"`+ );+ }+ return credentials;+}++/**+ * Xero stores its tenant under `providerMetadata.tenantId`. Throws when the+ * tenant is missing — every Xero API call requires the `xero-tenant-id`+ * header, and a descriptive error beats an opaque Xero 401/403.+ */+function getXeroTenantId(+ credentials: ProviderCredentials,+ fallbackTenantId?: string+): string {+ const { providerMetadata } = getOAuth2Credentials(credentials);+ const metadataTenantId = providerMetadata?.tenantId;+ const tenantId =+ typeof metadataTenantId === "string" && metadataTenantId.length > 0+ ? metadataTenantId+ : fallbackTenantId;++ if (!tenantId) {+ throw new Error(+ "Xero credentials are missing tenantId (providerMetadata.tenantId). Reconnect the Xero integration to select an organisation."+ );+ }++ return tenantId;}type XeroProviderConfig = ProviderConfig<{@@ -51,26 +196,36 @@ type XeroProviderConfig = ProviderConfig<{clientSecret: string;redirectUri?: string;tenantId?: string;- settings?: XeroSettings;}> & {id: ProviderID.XERO;accessToken?: string;refreshToken?: string;};-export class XeroProvider implements BaseProvider {+export class XeroProvider implements BaseProvider, SupportsIncrementalPull {static id = ProviderID.XERO;+ /**+ * Undeclared on purpose: absent capabilities = legacy REST provider (the+ * documented default in core/types.ts) — the drain treats Xero exactly+ * as before the field existed.+ */+ readonly capabilities?: ProviderCapabilities;++ /**+ * No cap: `/Payments` with `If-Modified-Since` reaches arbitrarily far back,+ * so the pull-sweep cursor is never clamped.+ */+ readonly pullLookbackDays?: number;+http: HTTPClient;auth: AuthProvider;private readonly syncConfig!: GlobalSyncConfig;- private readonly _settings: XeroSettings;constructor(public config: Omit<XeroProviderConfig, "id">) {- this.syncConfig = config.syncConfig;- this._settings = config.settings ?? {};- logger.info("XeroProvider initialized", { settings: this._settings });+ this.syncConfig = buildXeroSyncConfig(config.syncConfig);+ logger.info("XeroProvider initialized", { companyId: config.companyId });this.http = new HTTPClient("https://api.xero.com/api.xro/2.0");this.auth = createOAuthClient({clientId: config.clientId,@@ -99,13 +254,6 @@ export class XeroProvider implements BaseProvider {return this.constructor.id;}- /**- * Get integration settings (e.g., default account codes).- */- get settings(): XeroSettings {- return this._settings;- }-getSyncConfig(entity: AccountingEntityType) {return this.syncConfig.entities[entity];}@@ -122,21 +270,18 @@ export class XeroProvider implements BaseProvider {url: string,options?: RequestInit): Promise<HttpResponse<T>> {- const { accessToken, ...creds } = this.auth.getCredentials();-- const tenantId = creds.tenantId || this.config.tenantId;+ const credentials = this.auth.getCredentials();+ const { accessToken } = getOAuth2Credentials(credentials);+ const tenantId = getXeroTenantId(credentials, this.config.tenantId);const headers: Record<string, string> = {Authorization: `Bearer ${accessToken}`,Accept: "application/json","Content-Type": "application/json",- ...((options?.headers ?? {}) as Record<string, string>)+ ...((options?.headers ?? {}) as Record<string, string>),+ "xero-tenant-id": tenantId};- if (tenantId) {- headers["xero-tenant-id"] = tenantId;- }-const response = await this.http.request<T>(method, url, {...options,headers: headers@@ -145,17 +290,15 @@ export class XeroProvider implements BaseProvider {if (response.code === 401) {await this.auth.refresh();- const c = this.auth.getCredentials();+ const { accessToken: refreshedAccessToken } = getOAuth2Credentials(+ this.auth.getCredentials()+ );const retryHeaders: Record<string, string> = {...headers,- Authorization: `Bearer ${c.accessToken}`+ Authorization: `Bearer ${refreshedAccessToken}`};- if (tenantId) {- retryHeaders["xero-tenant-id"] = tenantId;- }-return this.http.request<T>(method, url, {...options,headers: retryHeaders@@ -229,6 +372,152 @@ export class XeroProvider implements BaseProvider {);}+ /**+ * Fetch the Xero tracking categories with their options (the journal+ * analytics surface; org-wide limit of 2 active categories). Returns+ * ACTIVE categories only, [] on failure — a settings-surface read, same+ * forgiving contract as listChartOfAccounts.+ */+ async listTrackingCategories(): Promise<Xero.TrackingCategory[]> {+ const response = await this.request<{+ TrackingCategories: Xero.TrackingCategory[];+ }>("GET", "/TrackingCategories");++ if (response.error) {+ logger.error("Failed to fetch Xero tracking categories", { response });+ return [];+ }++ return (response.data?.TrackingCategories ?? []).filter(+ (category) =>+ category.Status === "ACTIVE" || category.Status === undefined+ );+ }++ /**+ * Create a tracking option under a category by NAME (dimension+ * autoCreate: PUT /TrackingCategories/{id}/Options). Throws an+ * AccountingApiError when Xero rejects it (e.g. option cap reached).+ */+ async createTrackingOption(+ trackingCategoryId: string,+ name: string+ ): Promise<Xero.TrackingOption> {+ const response = await this.request<{+ Options: Xero.TrackingOption[];+ }>("PUT", `/TrackingCategories/${trackingCategoryId}/Options`, {+ body: JSON.stringify({ Name: name })+ });++ if (response.error) {+ throwXeroApiError("create tracking option", response);+ }++ const created = response.data?.Options?.[0];+ if (!created?.TrackingOptionID) {+ throw new Error(+ "Xero API returned success but no TrackingOptionID was returned"+ );+ }++ return created;+ }++ /**+ * The journal dimension targets this org supports: one+ * `tracking:<categoryId>` target per active tracking category (at most+ * XERO_MAX_JOURNAL_DIMENSION_SLOTS org-wide).+ */+ async journalDimensionTargets(): Promise<DimensionTarget[]> {+ const categories = await this.listTrackingCategories();+ return categories.map((category) => ({+ id: buildXeroTrackingTarget(category.TrackingCategoryID),+ label: category.Name,+ capacity: 1+ }));+ }++ /**+ * Create a manual journal (POST /ManualJournals). Throws an+ * AccountingApiError when Xero rejects the payload. Pass ManualJournalID+ * to update an existing manual journal instead of creating one.+ */+ async createManualJournal(+ journal: Omit<Xero.ManualJournal, "UpdatedDateUTC" | "ManualJournalID"> & {+ ManualJournalID?: string;+ }+ ): Promise<Xero.ManualJournal> {+ const response = await this.request<{+ ManualJournals: Xero.ManualJournal[];+ }>("POST", "/ManualJournals", {+ body: JSON.stringify({ ManualJournals: [journal] })+ });++ if (response.error) {+ throwXeroApiError("create manual journal", response);+ }++ const created = response.data?.ManualJournals?.[0];+ if (!created?.ManualJournalID) {+ throw new Error(+ "Xero API returned success but no ManualJournalID was returned"+ );+ }++ return created;+ }++ /**+ * Fetch one manual journal by id (GET /ManualJournals/{id}).+ * Returns null when it does not exist or the request fails.+ */+ async getManualJournal(id: string): Promise<Xero.ManualJournal | null> {+ const response = await this.request<{+ ManualJournals: Xero.ManualJournal[];+ }>("GET", `/ManualJournals/${id}`);++ if (response.error) {+ return null;+ }++ return response.data?.ManualJournals?.[0] ?? null;+ }++ /**+ * Create a payment (PUT /Payments) applying an amount to a Xero invoice.+ * Xero's single /Payments endpoint settles BOTH families — an ACCREC (sales+ * invoice / AR) and an ACCPAY (bill / AP) invoice — so one method covers the+ * Phase G outbound write-back for both. The `Account.Code` must map to a Xero+ * BANK-type account (the caller pre-checks this against the chart). Throws an+ * AccountingApiError when Xero rejects the payload; returns the created+ * PaymentID.+ */+ async createPayment(payment: {+ Invoice: { InvoiceID: string };+ Account: { Code: string };+ Amount: number;+ Date: string;+ }): Promise<string> {+ const response = await this.request<{ Payments: Xero.Payment[] }>(+ "PUT",+ "/Payments",+ { body: JSON.stringify({ Payments: [payment] }) }+ );++ if (response.error) {+ throwXeroApiError("create payment", response);+ }++ const created = response.data?.Payments?.[0];+ if (!created?.PaymentID) {+ throw new Error(+ "Xero API returned success but no PaymentID was returned"+ );+ }++ return created.PaymentID;+ }+/*** List all contacts from Xero with pagination support.* Xero returns 100 contacts per page by default.@@ -304,4 +593,105 @@ export class XeroProvider implements BaseProvider {return { items, hasMore, page };}++ // =================================================================+ // SupportsIncrementalPull — the pull-sweep entry point+ // =================================================================++ /**+ * SupportsIncrementalPull: payments (AR ACCREC + AP ACCPAY) changed since+ * `since`, for the generic accounting-pull-sweep cron. Xero has no payment+ * webhook, so the sweep is the correctness guarantee (the Invoice-update+ * webhook accelerator only shortens latency). Each change carries a+ * `dependsOnMapping` on its settled invoice (entityType "bill" for ACCPAY,+ * "invoice" for ACCREC) — the sweep drops changes whose document has no local+ * mapping (another instance's, or a document created directly in Xero)+ * without ledger noise. Composite ids match the syncer's entity-id contract.+ *+ * No status filter: Xero payments are only ever AUTHORISED or DELETED, and a+ * DELETED payment must reach the syncer so the void path fires — so the poll+ * returns both. A DELETED payment maps to `status: 'void'` in+ * entities/payment.ts.+ *+ * VERIFY: `GET /Payments` with `If-Modified-Since` (whole-second UTC, RFC 1123+ * via toUTCString — the same header the Contacts/Items reads use) is assumed+ * to return AP + AR payments changed since the cursor. Confirm the exact+ * If-Modified-Since format against the Xero sandbox before relying on this in+ * production.+ */+ async listChanges(args: { since: string }): Promise<ListChangesResult> {+ const paymentConfig = this.getSyncConfig("payment");+ if (!paymentConfig.enabled) {+ return { changes: [] };+ }++ // Whole-second UTC — Xero's If-Modified-Since has second resolution.+ const sinceMs = new Date(args.since).getTime();+ const modifiedSince = new Date(+ Number.isNaN(sinceMs) ? Date.now() : Math.floor(sinceMs / 1000) * 1000+ );++ const changes: ProviderChange[] = [];+ let page = 1;++ for (;;) {+ const params = new URLSearchParams();+ params.set("page", String(page));+ // No status filter: Xero payments are only ever AUTHORISED or DELETED,+ // and DELETED (a deletion/void) is exactly what the void path needs — an+ // AUTHORISED-only filter would make the payment/entities void case+ // unreachable (deleted payments are absent from the refetched invoice+ // Payments[] too). Both statuses flow to the syncer, which maps DELETED+ // → status 'void'.++ const response = await this.request<{ Payments: Xero.Payment[] }>(+ "GET",+ `/Payments?${params.toString()}`,+ { headers: { "If-Modified-Since": modifiedSince.toUTCString() } }+ );++ if (response.error || !response.data?.Payments) {+ break;+ }++ const payments = response.data.Payments;+ for (const payment of payments) {+ const invoice = payment.Invoice;+ if (!invoice?.InvoiceID || !invoice.Type) {+ logger.warning(+ "Ignoring Xero payment with no settled invoice id/type",+ { paymentId: payment.PaymentID }+ );+ continue;+ }++ const family = invoice.Type === "ACCPAY" ? "ap" : "ar";+ const remoteId =+ family === "ap"+ ? getXeroBillPaymentSyncEntityId(+ invoice.InvoiceID,+ payment.PaymentID+ )+ : getXeroPaymentSyncEntityId(invoice.InvoiceID, payment.PaymentID);++ changes.push({+ entityType: "payment",+ remoteId,+ updatedAt: payment.UpdatedDateUTC+ ? parseDotnetDate(payment.UpdatedDateUTC).toISOString()+ : null,+ dependsOnMapping: {+ entityType: family === "ap" ? "bill" : "invoice",+ remoteId: invoice.InvoiceID+ }+ });+ }++ // Xero returns 100 payments per page — a full page means there may be more.+ if (payments.length < 100) break;+ page++;+ }++ return { changes };+ }}diff --git a/packages/ee/src/hooks.server.ts b/packages/ee/src/hooks.server.tsindex d0b9fae815..0db1b9d135 100644--- a/packages/ee/src/hooks.server.ts+++ b/packages/ee/src/hooks.server.ts@@ -2,6 +2,15 @@ import { emailHealthcheck } from "./email/hooks.server";import { jiraHealthcheck } from "./jira/hooks.server";import { linearHealthcheck } from "./linear/hooks.server";import { onshapeOnUninstall } from "./onshape/hooks.server";+import {+ quickbooksOnInstall,+ quickbooksOnUninstall+} from "./quickbooks/hooks.server";+import {+ rilletHealthcheck,+ rilletOnInstall,+ rilletOnUninstall+} from "./rillet/hooks.server";import type { IntegrationServerHooks } from "./types";// Onshape keeps its release webhook subscription in lockstep with the asset-sync@@ -39,9 +48,25 @@ const serverHooks: Record<string, IntegrationServerHooks> = {onshape: {onUninstall: onshapeOnUninstall},+ // The accounting providers' onUpdate re-runs the same subscription+ // convergence as onInstall: a settings save on an existing install+ // self-heals the company's `${provider}-sync` subscription rows whenever+ // REQUIRED_SYNC_SUBSCRIPTIONS grows.+ quickbooks: {+ onInstall: quickbooksOnInstall,+ onUpdate: quickbooksOnInstall,+ onUninstall: quickbooksOnUninstall+ },+ rillet: {+ onHealthcheck: rilletHealthcheck,+ onInstall: rilletOnInstall,+ onUpdate: rilletOnInstall,+ onUninstall: rilletOnUninstall+ },xero: {onHealthcheck: xeroHealthcheck,onInstall: xeroOnInstall,+ onUpdate: xeroOnInstall,onUninstall: xeroOnUninstall}};diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.tsindex 8586d5fcea..11d48b7f11 100644--- a/packages/ee/src/index.ts+++ b/packages/ee/src/index.ts@@ -6,11 +6,11 @@ import { Onshape } from "./onshape/config";import { PaperlessParts } from "./paperless-parts/config";import { QuickBooks } from "./quickbooks/config";// import { Radan } from "./radan/config";+import { Rillet } from "./rillet/config";import { Sage } from "./sage/config";import { Slack } from "./slack/config";import type { QuickInstallConnector } from "./types";import { Xero } from "./xero/config";-import { Zapier } from "./zapier/config";export { Email } from "./email/config";export { defineIntegration } from "./fns";@@ -37,10 +37,10 @@ export const integrations = [Onshape,PaperlessParts,QuickBooks,+ Rillet,Sage,Slack,- Xero,- Zapier+ Xero];export type IntegrationID = (typeof integrations)[number]["id"];@@ -50,6 +50,7 @@ export { Logo as OnshapeLogo, Onshape } from "./onshape/config";// TODO: export as @carbon/ee/paperlessexport { PaperlessPartsClient } from "./paperless-parts/lib/client";export { QuickBooks } from "./quickbooks/config";+export { Rillet } from "./rillet/config";export { Slack } from "./slack/config";export * from "./slack/lib/messages";export { Xero } from "./xero/config";diff --git a/packages/ee/src/jira/config.tsx b/packages/ee/src/jira/config.tsxindex d008379990..8db0b8572f 100644--- a/packages/ee/src/jira/config.tsx+++ b/packages/ee/src/jira/config.tsx@@ -12,8 +12,9 @@ export const Jira = defineIntegration({category: "Project Management",logo: Logo,description:- "Jira is a project management and issue tracking tool by Atlassian. With this integration, you can link quality issues from Carbon to Jira for tracking and collaboration.",- shortDescription: "Sync quality issues from Carbon to Jira.",+ "Jira is a project management and issue tracking tool by Atlassian. With this integration, you can link quality issues and change notices from Carbon to Jira for tracking and collaboration.",+ shortDescription:+ "Sync quality issues and change notices from Carbon to Jira.",setupInstructions: SetupInstructions,images: [],settings: [],diff --git a/packages/ee/src/linear/config.tsx b/packages/ee/src/linear/config.tsxindex 21128f313c..aa56177994 100644--- a/packages/ee/src/linear/config.tsx+++ b/packages/ee/src/linear/config.tsx@@ -10,8 +10,8 @@ export const Linear = defineIntegration({category: "Project Management",logo: Logo,description:- "Linear is a project management software that allows you to create issues and track project progress seamlessly. With this integration, you can link issues from Carbon to Linear.",- shortDescription: "Sync issues from Carbon to Linear.",+ "Linear is a project management software that allows you to create issues and track project progress seamlessly. With this integration, you can link issues and change notices from Carbon to Linear.",+ shortDescription: "Sync issues and change notices from Carbon to Linear.",setupInstructions: SetupInstructions,images: [],settings: [diff --git a/packages/ee/src/quickbooks/config.tsx b/packages/ee/src/quickbooks/config.tsxindex cfde7d942f..d49ff1dabf 100644--- a/packages/ee/src/quickbooks/config.tsx+++ b/packages/ee/src/quickbooks/config.tsx@@ -4,15 +4,15 @@ import { z } from "zod";import { defineIntegration } from "../fns";export const QuickBooks = defineIntegration({- name: "QuickBooks",+ name: "QuickBooks Online",id: "quickbooks",active: false,category: "Accounting",logo: Logo,description:- "Integrating Carbon with QuickBooks enables you to post transactions from sales invoices and purchase invoices into your existing accounting software, neatly organizing everything in your bookkeeping software.",+ "Integrating Carbon with QuickBooks Online keeps your books in sync: customers, vendors, items, invoices and bills flow between both systems, and Carbon's inventory and production postings are pushed as journal entries into your QuickBooks Online ledger.",shortDescription:- "Automatically post transactions from sales and purchase invoices.",+ "Sync customers, vendors, items and invoices, and post journal entries.",images: [],settings: [],schema: z.object({}),@@ -20,15 +20,15 @@ export const QuickBooks = defineIntegration({authUrl: "https://appcenter.intuit.com/connect/oauth2",clientId: QUICKBOOKS_CLIENT_ID ?? "",redirectUri: "/api/integrations/quickbooks/oauth",- scopes: [- "com.intuit.quickbooks.accounting",- "com.intuit.quickbooks.payment"- ],+ scopes: ["com.intuit.quickbooks.accounting"],tokenUrl: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"}});-function Logo(props: ComponentProps<"svg">) {+/**+ * QuickBooks logo. Exported like Onshape's Logo.+ */+export function Logo(props: ComponentProps<"svg">) {return (<svg{...props}diff --git a/packages/ee/src/quickbooks/hooks.server.ts b/packages/ee/src/quickbooks/hooks.server.tsnew file mode 100644index 0000000000..4c6c23d6b9--- /dev/null+++ b/packages/ee/src/quickbooks/hooks.server.ts@@ -0,0 +1,28 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { deleteEventSystemSubscriptionsByName } from "@carbon/database/event";+import {+ ensureProviderSubscriptions,+ getSyncSubscriptionName,+ ProviderID+} from "@carbon/ee/accounting";++/**+ * Install/settings-save hook: converge this company's `quickbooks-sync`+ * event subscriptions onto REQUIRED_SYNC_SUBSCRIPTIONS (the code-derived+ * list — see @carbon/ee/accounting core/subscriptions). The QBO entity+ * syncers have shipped, so the old no-op here left QBO outbound event sync+ * entirely dead — every subscribed table routes to a registered syncer.+ */+export async function quickbooksOnInstall(companyId: string) {+ const client = getCarbonServiceRole();+ await ensureProviderSubscriptions(client, companyId, ProviderID.QUICKBOOKS);+}++export async function quickbooksOnUninstall(companyId: string) {+ const client = getCarbonServiceRole();+ await deleteEventSystemSubscriptionsByName(+ client,+ companyId,+ getSyncSubscriptionName(ProviderID.QUICKBOOKS)+ );+}diff --git a/packages/ee/src/rillet/config.tsx b/packages/ee/src/rillet/config.tsxnew file mode 100644index 0000000000..cef03189bf--- /dev/null+++ b/packages/ee/src/rillet/config.tsx@@ -0,0 +1,152 @@+import { Copy, Input, InputGroup, InputRightElement } from "@carbon/react";+import { isBrowser } from "@carbon/utils";+import type { ComponentProps } from "react";+import { z } from "zod";+import { defineIntegration } from "../fns";++const RilletSettingsSchema = z.object({+ apiKey: z.string().min(1, { message: "API key is required" }),+ environment: z.enum(["production", "sandbox"]).default("production"),+ subsidiaryId: z.string().optional(),+ webhookToken: z.string().optional()+});++export const Rillet = defineIntegration({+ name: "Rillet",+ id: "rillet",+ active: true,+ category: "Accounting",+ logo: Logo,+ setupInstructions: SetupInstructions,+ description:+ "Integrating Carbon with Rillet posts your production and inventory journal entries, sales invoices, and bills into Rillet's multi-entity general ledger, keeps customers and vendors in sync, and applies invoice payments recorded in Rillet back to Carbon.",+ shortDescription:+ "Post journals, invoices, and bills to Rillet; pull payments back.",+ images: [],+ settingGroups: [+ {+ name: "Connection",+ description: "API access to your Rillet organization"+ },+ {+ name: "Webhooks",+ description:+ "Lets Rillet notify Carbon when invoice payments are recorded"+ }+ ],+ settings: [+ {+ name: "apiKey",+ label: "API key",+ description:+ "Create one in Rillet under Organization Settings → API access. Keys are environment-specific.",+ group: "Connection",+ type: "secret" as const,+ required: true,+ value: ""+ },+ {+ name: "environment",+ label: "Environment",+ group: "Connection",+ type: "options" as const,+ listOptions: [+ {+ value: "production",+ label: "Production",+ description: "api.rillet.com"+ },+ {+ value: "sandbox",+ label: "Sandbox",+ description: "sandbox.api.rillet.com"+ }+ ],+ required: true,+ value: "production"+ },+ {+ name: "subsidiaryId",+ label: "Subsidiary ID",+ description:+ "Optional Rillet subsidiary (UUID) that journal entries, invoices, and bills post into. Leave blank for single-entity organizations.",+ group: "Connection",+ type: "text" as const,+ required: false,+ value: ""+ },+ {+ name: "webhookToken",+ label: "Webhook token",+ description:+ "The per-webhook token from step 3. Inbound payments stay off until this is set.",+ group: "Webhooks",+ type: "secret" as const,+ required: false,+ value: ""+ }+ ],+ schema: RilletSettingsSchema+});++function SetupInstructions({ companyId }: { companyId: string }) {+ const webhookUrl = isBrowser+ ? `${window.location.origin}/api/webhook/rillet/${companyId}`+ : "";+ return (+ <>+ <p className="text-sm text-muted-foreground">+ 1. Create an API key in Rillet under Organization Settings → API access+ (keys are environment-specific) and paste it below.+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ 2. In Rillet under Settings → External References, add two reference+ types with the slugs <span className="font-mono">carbon</span> and{" "}+ <span className="font-mono">carbon-company</span>. Rillet has no API for+ this step. It is required before invoices can post (Rillet mandates+ external references on AR-only invoices); without it, customers,+ vendors, products, and bills still sync but are not tagged with their+ Carbon ids.+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ 3. To pull invoice payments back into Carbon, create a webhook in Rillet+ under Organization Settings → Webhooks pointed at the URL below,+ subscribed to invoice payment events, and paste its Webhook Token into+ the field at the bottom of this form.+ </p>+ <InputGroup className="mb-8">+ <Input value={webhookUrl} />+ <InputRightElement>+ <Copy text={webhookUrl} />+ </InputRightElement>+ </InputGroup>+ </>+ );+}++function Logo(props: ComponentProps<"svg">) {+ return (+ <svg+ {...props}+ viewBox="0 0 124 27"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ // Rillet's wordmark is a wide 124x27 (~4.6:1). The shared render+ // sites size logos by height (h-10 / h-full), which is right for the+ // square Xero/QBO marks but blows this one out horizontally. Size it+ // by a modest height and clamp width to the container so it stays a+ // balanced wordmark and never overflows the drawer's icon box.+ style={{+ ...props.style,+ height: "1.25rem",+ width: "auto",+ maxWidth: "100%"+ }}+ >+ <path+ d="M0.69312 26.5771V1.44136H8.91611C10.8791 1.44136 12.495 1.7765 13.7637 2.44679C15.0564 3.11708 16.014 4.02675 16.6364 5.17582C17.2827 6.30095 17.6059 7.58167 17.6059 9.018C17.6059 10.6458 17.187 12.0941 16.3491 13.3629C15.5352 14.6077 14.2784 15.5174 12.5788 16.0919L17.8573 26.5771H13.4406L8.62885 16.6306H4.4994V26.5771H0.69312ZM4.4994 13.1834H8.70066C10.4243 13.1834 11.6811 12.8003 12.471 12.0343C13.285 11.2683 13.6919 10.2628 13.6919 9.018C13.6919 7.74925 13.2969 6.74381 12.5069 6.00171C11.717 5.23567 10.4362 4.85265 8.66476 4.85265H4.4994V13.1834ZM29.9443 6.03762C29.1065 6.03762 28.4003 5.77429 27.8257 5.24764C27.2752 4.69704 26.9999 4.02675 26.9999 3.23677C26.9999 2.44679 27.2752 1.78847 27.8257 1.26182C28.4003 0.735163 29.1065 0.471836 29.9443 0.471836C30.8061 0.471836 31.5123 0.735163 32.0629 1.26182C32.6375 1.78847 32.9247 2.44679 32.9247 3.23677C32.9247 4.02675 32.6375 4.69704 32.0629 5.24764C31.5123 5.77429 30.8061 6.03762 29.9443 6.03762ZM22.7986 26.5771V23.2736H28.4003V13.2552C28.4003 12.4652 28.0173 12.0702 27.2512 12.0702H23.3013V8.76665H27.9335C29.4177 8.76665 30.4949 9.11376 31.1652 9.80799C31.8594 10.4783 32.2066 11.5555 32.2066 13.0397V23.2736H37.8082V26.5771H22.7986ZM43.5036 26.5771V23.2736H49.4644V5.21173C49.4644 4.42175 49.0814 4.02676 48.3153 4.02676H44.0063V0.723194H48.9976C50.386 0.723194 51.4394 1.09425 52.1575 1.83635C52.8996 2.55452 53.2707 3.60783 53.2707 4.99628V23.2736H59.2674V26.5771H43.5036ZM65.0346 26.5771V23.2736H70.9953V5.21173C70.9953 4.42175 70.6123 4.02676 69.8463 4.02676H65.5373V0.723194H70.5285C71.917 0.723194 72.9703 1.09425 73.6885 1.83635C74.4306 2.55452 74.8016 3.60783 74.8016 4.99628V23.2736H80.7983V26.5771H65.0346ZM95.1117 27.008C93.3881 27.008 91.868 26.625 90.5513 25.859C89.2347 25.069 88.2053 23.9798 87.4632 22.5913C86.7211 21.2029 86.35 19.587 86.35 17.7437C86.35 15.8765 86.7091 14.2367 87.4273 12.8243C88.1694 11.4119 89.1988 10.3107 90.5154 9.52072C91.856 8.73074 93.4 8.33575 95.1476 8.33575C96.8712 8.33575 98.3554 8.73074 99.6002 9.52072C100.845 10.2868 101.803 11.3161 102.473 12.6088C103.167 13.9015 103.514 15.3259 103.514 16.8819C103.514 17.1213 103.514 17.3846 103.514 17.6719C103.514 17.9352 103.502 18.2345 103.478 18.5696H90.0845C90.2042 20.2214 90.7428 21.4782 91.7004 22.34C92.6579 23.1778 93.7831 23.5968 95.0758 23.5968C96.2009 23.5968 97.0866 23.3693 97.733 22.9145C98.4033 22.4357 98.894 21.7894 99.2052 20.9755H103.047C102.616 22.6751 101.719 24.1114 100.354 25.2845C98.9898 26.4335 97.2422 27.008 95.1117 27.008ZM95.1117 11.6393C93.9387 11.6393 92.8973 11.9984 91.9876 12.7166C91.078 13.4108 90.4915 14.3923 90.2281 15.661H99.7079C99.6122 14.4641 99.1454 13.4946 98.3075 12.7525C97.4696 12.0104 96.4044 11.6393 95.1117 11.6393ZM118.366 26.5771C116.619 26.5771 115.23 26.1582 114.201 25.3204C113.171 24.4586 112.657 22.9384 112.657 20.76V11.9984H108.168V8.76665H110.825C112.046 8.76665 112.765 8.16818 112.98 6.97123L113.519 4.09857H116.463V8.76665H123.501V11.9984H116.463V20.6882C116.463 21.6218 116.667 22.2801 117.073 22.6631C117.504 23.0222 118.235 23.2018 119.264 23.2018H123.429V26.5771H118.366Z"+ fill="currentColor"+ ></path>+ </svg>+ );+}diff --git a/packages/ee/src/rillet/hooks.server.ts b/packages/ee/src/rillet/hooks.server.tsnew file mode 100644index 0000000000..cbe4db0ee6--- /dev/null+++ b/packages/ee/src/rillet/hooks.server.ts@@ -0,0 +1,44 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { deleteEventSystemSubscriptionsByName } from "@carbon/database/event";+import {+ ensureProviderSubscriptions,+ getProviderIntegration,+ getSyncSubscriptionName,+ ProviderID,+ type ProviderIntegrationMetadata+} from "@carbon/ee/accounting";++export async function rilletHealthcheck(+ companyId: string,+ metadata: Record<string, unknown>+) {+ const provider = getProviderIntegration(+ getCarbonServiceRole(),+ companyId,+ ProviderID.RILLET,+ metadata as ProviderIntegrationMetadata+ );++ return await provider.validate();+}++/**+ * Install/settings-save hook: converge this company's `rillet-sync` event+ * subscriptions onto REQUIRED_SYNC_SUBSCRIPTIONS (the code-derived list —+ * see @carbon/ee/accounting core/subscriptions). Runs on install AND on+ * every settings save (onUpdate), so an existing install self-heals when+ * the required set grows.+ */+export async function rilletOnInstall(companyId: string) {+ const client = getCarbonServiceRole();+ await ensureProviderSubscriptions(client, companyId, ProviderID.RILLET);+}++export async function rilletOnUninstall(companyId: string) {+ const client = getCarbonServiceRole();+ await deleteEventSystemSubscriptionsByName(+ client,+ companyId,+ getSyncSubscriptionName(ProviderID.RILLET)+ );+}diff --git a/packages/ee/src/types.ts b/packages/ee/src/types.tsindex e0ff66af55..a789162433 100644--- a/packages/ee/src/types.ts+++ b/packages/ee/src/types.ts@@ -55,6 +55,7 @@ export type IntegrationSetting = {| "text"| "number"| "password"+ | "secret"| "switch"| "processes"| "options"@@ -127,6 +128,14 @@ export type IntegrationServerHooks = {* Use this for creating database subscriptions, webhooks, or other server setup.*/onInstall?: (companyId: string) => void | Promise<void>;+ /**+ * Server-side hook called after the settings of an ALREADY-installed+ * integration are saved. Use this to re-converge derived server state+ * (e.g. event-system subscriptions) so existing installs self-heal when+ * the required set changes. Best-effort: a failure is logged, never+ * rolls back the save.+ */+ onUpdate?: (companyId: string) => void | Promise<void>;/*** Server-side hook called after the integration is deactivated/uninstalled.* Use this for cleaning up server resources, webhooks, etc.diff --git a/packages/ee/src/xero/config.tsx b/packages/ee/src/xero/config.tsxindex 8627046cf3..7306ccc36d 100644--- a/packages/ee/src/xero/config.tsx+++ b/packages/ee/src/xero/config.tsx@@ -9,21 +9,10 @@ const coerceBoolean = z.preprocess(z.boolean());-const SystemOfRecordSchema = z.enum(["carbon", "accounting"]);-const XeroSettingsSchema = z.object({backfillCustomers: coerceBoolean.optional().default(true),backfillVendors: coerceBoolean.optional().default(true),- backfillItems: coerceBoolean.optional().default(true),- // Per-entity system of record settings- customerOwner: SystemOfRecordSchema.optional().default("accounting"),- vendorOwner: SystemOfRecordSchema.optional().default("accounting"),- itemOwner: SystemOfRecordSchema.optional().default("carbon"),- invoiceOwner: SystemOfRecordSchema.optional().default("accounting"),- billOwner: SystemOfRecordSchema.optional().default("accounting"),- // Default account codes for line items- defaultSalesAccountCode: z.string().optional(),- defaultPurchaseAccountCode: z.string().optional()+ backfillItems: coerceBoolean.optional().default(true)});export const Xero = defineIntegration({@@ -37,16 +26,6 @@ export const Xero = defineIntegration({shortDescription:"Automatically post transactions from sales and purchase invoices.",images: [],- settingGroups: [- {- name: "Source of Truth",- description: "Which system's data takes priority when there are conflicts"- },- {- name: "Account Mapping",- description: "Default accounts for syncing transactions to Xero"- }- ],settings: [{name: "backfillCustomers",@@ -74,126 +53,6 @@ export const Xero = defineIntegration({type: "switch" as const,required: false,value: true- },- {- name: "customerOwner",- label: "Customers",- group: "Source of Truth",- type: "options" as const,- listOptions: [- {- value: "accounting",- label: "Xero",- description: "Xero data overwrites Carbon data"- },- {- value: "carbon",- label: "Carbon",- description: "Carbon data overwrites Xero data"- }- ],- required: false,- value: "accounting"- },- {- name: "vendorOwner",- label: "Vendors",- group: "Source of Truth",- type: "options" as const,- listOptions: [- {- value: "accounting",- label: "Xero",- description: "Xero data overwrites Carbon data"- },- {- value: "carbon",- label: "Carbon",- description: "Carbon data overwrites Xero data"- }- ],- required: false,- value: "accounting"- },- {- name: "itemOwner",- label: "Items",- group: "Source of Truth",- type: "options" as const,- listOptions: [- {- value: "carbon",- label: "Carbon",- description: "Carbon data overwrites Xero data"- },- {- value: "accounting",- label: "Xero",- description: "Xero data overwrites Carbon data"- }- ],- required: false,- value: "carbon"- },- {- name: "invoiceOwner",- label: "Invoices",- group: "Source of Truth",- type: "options" as const,- listOptions: [- {- value: "accounting",- label: "Xero",- description: "Xero data overwrites Carbon data"- },- {- value: "carbon",- label: "Carbon",- description: "Carbon data overwrites Xero data"- }- ],- required: false,- value: "accounting"- },- {- name: "billOwner",- label: "Bills",- group: "Source of Truth",- type: "options" as const,- listOptions: [- {- value: "accounting",- label: "Xero",- description: "Xero data overwrites Carbon data"- },- {- value: "carbon",- label: "Carbon",- description: "Carbon data overwrites Xero data"- }- ],- required: false,- value: "accounting"- },- {- name: "defaultSalesAccountCode",- label: "Default Sales Account",- description: "Account code to use for sales invoice line items",- group: "Account Mapping",- type: "options" as const,- listOptions: [], // Populated dynamically from Xero- required: true,- value: ""- },- {- name: "defaultPurchaseAccountCode",- label: "Default Purchase Account",- description: "Account code to use for purchase order and bill line items",- group: "Account Mapping",- type: "options" as const,- listOptions: [], // Populated dynamically from Xero- required: true,- value: ""}],schema: XeroSettingsSchema,@@ -201,11 +60,19 @@ export const Xero = defineIntegration({authUrl: "https://login.xero.com/identity/connect/authorize",clientId: XERO_CLIENT_ID!,redirectUri: "/api/integrations/xero/oauth",+ // Granular scopes (Xero retired the broad `accounting.transactions` scope for+ // apps created after 2026-03-02; the granular set also works on older apps).+ // Overshoot the accounting-transaction family so no synced entity 403s:+ // invoices+bills → invoices, payments → payments, journal entries →+ // manualjournals, POs/quotes → invoices, chart/tax/items → settings.scopes: ["offline_access","accounting.contacts",- "accounting.transactions",- "accounting.settings"+ "accounting.settings",+ "accounting.invoices",+ "accounting.payments",+ "accounting.banktransactions",+ "accounting.manualjournals"],tokenUrl: "https://login.xero.com/identity/connect/token"},diff --git a/packages/ee/src/xero/hooks.server.ts b/packages/ee/src/xero/hooks.server.tsindex 65699aa723..6ec03650b3 100644--- a/packages/ee/src/xero/hooks.server.ts+++ b/packages/ee/src/xero/hooks.server.ts@@ -1,11 +1,9 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";-import type { CreateSubscriptionParams } from "@carbon/database/event";-import {- createEventSystemSubscription,- deleteEventSystemSubscriptionsByName-} from "@carbon/database/event";+import { deleteEventSystemSubscriptionsByName } from "@carbon/database/event";import {+ ensureProviderSubscriptions,getProviderIntegration,+ getSyncSubscriptionName,ProviderID,type ProviderIntegrationMetadata} from "@carbon/ee/accounting";@@ -24,35 +22,23 @@ export async function xeroHealthcheck(return await provider.validate();}+/**+ * Install/settings-save hook: converge this company's `xero-sync` event+ * subscriptions onto REQUIRED_SYNC_SUBSCRIPTIONS (the code-derived list —+ * see @carbon/ee/accounting core/subscriptions). Runs on install AND on+ * every settings save (onUpdate), so an existing install self-heals when+ * the required set grows.+ */export async function xeroOnInstall(companyId: string) {const client = getCarbonServiceRole();-- const tables: CreateSubscriptionParams["table"][] = [- "address",- "customer",- "supplier",- "item",- "salesInvoice",- "purchaseInvoice",- "purchaseOrder",- "salesOrder"- ];-- for (const table of tables) {- await createEventSystemSubscription(client, {- table,- companyId,- name: "xero-sync",- operations: ["INSERT", "UPDATE", "DELETE"],- type: "SYNC",- config: {- provider: ProviderID.XERO- }- });- }+ await ensureProviderSubscriptions(client, companyId, ProviderID.XERO);}export async function xeroOnUninstall(companyId: string) {const client = getCarbonServiceRole();- await deleteEventSystemSubscriptionsByName(client, companyId, "xero-sync");+ await deleteEventSystemSubscriptionsByName(+ client,+ companyId,+ getSyncSubscriptionName(ProviderID.XERO)+ );}diff --git a/packages/ee/src/zapier/config.tsx b/packages/ee/src/zapier/config.tsxdeleted file mode 100644index e78b5a03d0..0000000000--- a/packages/ee/src/zapier/config.tsx+++ /dev/null@@ -1,39 +0,0 @@-import type { ComponentProps } from "react";-import { z } from "zod";-import { defineIntegration } from "../fns";--export const Zapier = defineIntegration({- name: "Zapier",- id: "zapier",- active: false,- category: "Automation",- logo: Logo,- description:- "Integrating with Zapier enables you to automate tasks and workflows in your business by connecting Carbon to other apps.",- shortDescription: "Automate tasks and workflows in your business.",- images: [],- settings: [],- schema: z.object({})-});--function Logo(props: ComponentProps<"svg">) {- return (- <svg- {...props}- width="79"- height="22"- viewBox="0 0 79 22"- fill="none"- xmlns="http://www.w3.org/2000/svg"- >- <path- d="M18.4996 14.6282L18.4865 14.5888L25.4845 8.18165V5.09623H14.2588V8.18165H20.9679L20.9811 8.20791L14.0487 14.6282V17.7136H25.6158V14.6282H18.4996ZM32.5087 4.79426C31.2089 4.79426 30.1585 4.9912 29.3445 5.38508C28.583 5.72645 27.9397 6.29101 27.5064 7C27.0862 7.70899 26.8237 8.50989 26.7318 9.33704L30.1454 9.8097C30.2636 9.08758 30.513 8.56241 30.8807 8.26043C31.3008 7.94532 31.826 7.78777 32.3512 7.8009C33.047 7.8009 33.5459 7.98471 33.861 8.35233C34.1761 8.71996 34.3337 9.23201 34.3337 9.91474V10.2561H31.0513C29.3839 10.2561 28.1891 10.6237 27.4539 11.3721C26.7186 12.1074 26.3641 13.0921 26.3641 14.3C26.3641 15.5473 26.7318 16.4663 27.4539 17.0703C28.176 17.6742 29.0951 17.9762 30.1979 17.9762C31.5634 17.9762 32.6137 17.5036 33.349 16.5582C33.7823 15.9805 34.0974 15.3241 34.2549 14.6151H34.3731L34.8457 17.7005H37.9312V9.88848C37.9312 8.27356 37.511 7.01313 36.6576 6.13346C35.8042 5.25379 34.4125 4.79426 32.5087 4.79426ZM33.5853 14.4444C33.0995 14.8514 32.4562 15.0615 31.6553 15.0615C30.9988 15.0615 30.5393 14.9433 30.2767 14.7201C30.1454 14.6151 30.0535 14.4707 29.9879 14.3262C29.9222 14.1687 29.8828 14.0111 29.896 13.8404C29.8828 13.6829 29.9091 13.5253 29.9747 13.3809C30.0404 13.2365 30.1192 13.1052 30.2242 12.987C30.3424 12.882 30.4736 12.7901 30.6312 12.7376C30.7888 12.685 30.9463 12.6588 31.1039 12.6719H34.3337V12.882C34.3337 13.184 34.2812 13.4859 34.1499 13.7485C34.0055 14.0111 33.8217 14.2606 33.5853 14.4444ZM56.6144 5.09623H52.9644V17.7268H56.6144V5.09623ZM78.1598 5.09623C77.1226 5.09623 76.3217 5.46386 75.7177 6.18597C75.2976 6.71115 74.9693 7.48579 74.7461 8.50989H74.6411L74.1684 5.09623H71.0568V17.7268H74.7068V11.2539C74.7068 10.4399 74.9037 9.8097 75.2844 9.37643C75.6652 8.94316 76.3742 8.71996 77.3983 8.71996H78.79V5.09623H78.1598ZM67.433 5.50325C66.5796 4.9912 65.503 4.74174 64.2032 4.74174C62.155 4.74174 60.5663 5.31943 59.4109 6.48795C58.2556 7.65647 57.6779 9.25827 57.6779 11.2933C57.6516 12.5275 57.9142 13.7485 58.4656 14.8645C58.9645 15.8492 59.7392 16.6764 60.6976 17.2278C61.6692 17.7924 62.8115 18.0681 64.1507 18.0681C65.3061 18.0681 66.2645 17.8843 67.0392 17.5298C67.7613 17.2147 68.4046 16.7158 68.8773 16.0724C69.3368 15.4554 69.6782 14.7464 69.8751 14.0111L66.724 13.1315C66.5928 13.6172 66.3302 14.0505 65.9888 14.4181C65.6343 14.7726 65.0435 14.9564 64.2032 14.9564C63.2054 14.9564 62.4701 14.6676 61.9843 14.103C61.6298 13.696 61.4066 13.1052 61.3147 12.3437H69.9276C69.967 11.9892 69.9802 11.6872 69.9802 11.4509V10.6631C70.0064 9.61276 69.7832 8.56241 69.3368 7.60396C68.9298 6.72428 68.2602 5.98904 67.433 5.50325ZM64.0982 7.76151C65.5818 7.76151 66.4221 8.48363 66.619 9.94099H61.3804C61.4591 9.45521 61.6692 8.99568 61.9712 8.60179C62.4438 8.03723 63.1528 7.76151 64.0982 7.76151ZM54.8288 0.00201066C54.5531 -0.0111188 54.2773 0.041399 54.0279 0.133305C53.7653 0.238341 53.5421 0.382765 53.3451 0.566577C53.1482 0.763518 53.0038 0.986719 52.8987 1.24931C52.7937 1.49877 52.7543 1.77449 52.7674 2.0502C52.7543 2.32592 52.8068 2.60164 52.9119 2.8511C53.0169 3.11369 53.1613 3.33689 53.3583 3.53383C53.5552 3.73077 53.7915 3.8752 54.041 3.98023C54.2905 4.08527 54.5662 4.12465 54.8419 4.11153C55.1176 4.12465 55.3933 4.07214 55.6428 3.98023C55.8923 3.8752 56.1286 3.73077 56.3255 3.53383C56.5225 3.33689 56.6669 3.10056 56.7588 2.8511C56.8507 2.58851 56.9032 2.32592 56.8901 2.0502C56.9032 1.77449 56.8638 1.49877 56.7588 1.24931C56.6538 0.999848 56.5093 0.763518 56.3124 0.566577C56.1155 0.369635 55.8923 0.225212 55.6297 0.120177C55.3802 0.0414002 55.1045 -0.0111188 54.8288 0.00201066ZM47.2925 4.74174C46.0452 4.74174 45.0473 5.13562 44.299 5.91026C43.7344 6.48796 43.3274 7.3545 43.0648 8.49676H42.9466L42.474 5.0831H39.3623V21.3374H43.0123V14.6413H43.1436C43.2486 15.0877 43.4062 15.521 43.6031 15.9411C43.9182 16.6108 44.4171 17.1884 45.0605 17.5692C45.7169 17.9237 46.4653 18.1075 47.2137 18.0944C48.7367 18.0944 49.9052 17.5036 50.7061 16.3088C51.507 15.114 51.9009 13.4597 51.9009 11.3327C51.9009 9.27139 51.5201 7.65648 50.7455 6.50108C49.9709 5.33256 48.8155 4.74174 47.2925 4.74174ZM47.6601 13.893C47.2399 14.51 46.5703 14.812 45.6644 14.812C45.2968 14.8251 44.916 14.7595 44.5747 14.6019C44.2333 14.4444 43.9313 14.2081 43.7081 13.9192C43.2355 13.3284 42.9991 12.5144 42.9991 11.4771V11.2408C42.9991 10.1905 43.2355 9.38956 43.7081 8.83812C44.1808 8.28669 44.8373 8.01097 45.6644 8.01097C46.5835 8.01097 47.2531 8.29982 47.6732 8.89064C48.0934 9.48146 48.3034 10.2955 48.3034 11.3458C48.3034 12.4356 48.0934 13.289 47.6601 13.893Z"- fill="currentColor"- />- <path- d="M12.6305 14.6282H0V17.7268H12.6305V14.6282Z"- fill="currentColor"- />- </svg>- );-}diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex 31dfa4a037..9c1462d1da 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -50,6 +50,7 @@ declare global {POSTHOG_API_HOST: string;POSTHOG_PROJECT_PUBLIC_KEY: string;QUICKBOOKS_CLIENT_SECRET: string;+ QUICKBOOKS_ENVIRONMENT: string;QUICKBOOKS_WEBHOOK_SECRET: string;RESEND_API_KEY: string;RESEND_DOMAIN: string;@@ -275,6 +276,13 @@ export const QUICKBOOKS_CLIENT_SECRET = getEnv("QUICKBOOKS_CLIENT_SECRET", {isSecret: true});+/** Intuit environment: "sandbox" or "production" (default). */+export const QUICKBOOKS_ENVIRONMENT =+ getEnv("QUICKBOOKS_ENVIRONMENT", {+ isRequired: false,+ isSecret: false+ }) ?? "production";+export const QUICKBOOKS_WEBHOOK_SECRET = getEnv("QUICKBOOKS_WEBHOOK_SECRET", {isRequired: false,isSecret: truediff --git a/packages/form/src/components/Select.tsx b/packages/form/src/components/Select.tsxindex db42ff4543..0104ecbfb5 100644--- a/packages/form/src/components/Select.tsx+++ b/packages/form/src/components/Select.tsx@@ -215,7 +215,7 @@ export const SelectBase = forwardRef<HTMLButtonElement, SelectBaseProps>()}</span>) : (- <div>+ <div className="min-w-0 flex-1 truncate text-left"><SelectValue placeholder={placeholder} />{isLoading && (<div className="absolute top-3 right-2">diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.mdindex 30c915c407..bd5013a14d 100644--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@ -1,6 +1,6 @@# @carbon/jobs-Background job system built on Inngest. Handles event system processing (webhooks, sync, search, audit, embeddings), integrations (Jira, Linear, Xero, Slack, Onshape), notifications, scheduled tasks, and async workflows.+Background job system built on Inngest. Handles event system processing (webhooks, sync, search, audit, embeddings), integrations (Jira, Linear, accounting sync — Xero/QBO/Rillet, Slack, Onshape), notifications, scheduled tasks, and async workflows.## Always@@ -50,12 +50,29 @@ pnpm --filter @carbon/jobs dev:jobs # Start local Inngest dev server| Handler | Event | Purpose ||---------|-------|---------|| WEBHOOK | `carbon/event-webhook` | POST to configured URL. Backs the user-facing Settings → Webhooks feature; its body `{type, record, old?, companyId, table}` is a public contract — change `toWebhookBody` only with the docs and `webhook.test.ts` |-| SYNC | `carbon/event-sync` | Accounting sync (Xero) |+| SYNC | `carbon/event-sync` | Accounting sync for all three providers (Xero, QBO, Rillet) — v5: events are hints; refs go to the shared `reconcileEntities` executor (`integrations/reconcile.ts` decides from state), then the `accountingSyncOperation` ledger drains; table→entity map in `events/sync-tables.ts` (see `.claude/rules/accounting-sync-handlers.md`) || SEARCH | `carbon/event-search` | Upsert/delete search index || AUDIT | `carbon/event-audit` | Per-company audit log || EMBEDDING | `carbon/event-embedding` | AI embeddings for items/customers/suppliers || WORKFLOW | `carbon/event-workflow` | Customer-workflow matcher: announcement → catalog event ids → subscribed workflows → one `workflowRun` each |+The queue drainer (`events/queue.ts`) archives messages with an unknown `handlerType` to pgmq's+dead-letter table (`pgmq.a_event_system`) instead of crash-looping — a poison message can no+longer wedge all event processing.++## Accounting sync functions (`src/inngest/functions/integrations/`)++Full architecture in `.claude/rules/accounting-sync-handlers.md`; the ones to know:++| Function | Trigger | Purpose |+|----------|---------|---------|+| `sync-external-accounting` | `carbon/sync-external-accounting` | Webhook-fired entry point; enqueues + drains the `accountingSyncOperation` ledger |+| `accounting-pull-sweep` | cron `*/30 * * * *` | INBOUND correctness: incremental pull (`listChanges`) for every active integration |+| `accounting-outbound-sweep` | cron `15,45 * * * *` | OUTBOUND correctness backstop (v4/v5): subscription convergence, then pages the window's candidate refs into the shared `reconcileEntities` executor (same brain as the event path), then a drain (Xero's only periodic drain). Fires `NotificationEvent.IntegrationSync` (in-app) to the integration's configurer when the drain leaves failed ops |+| `accounting-reconciliation` | cron `0 3 * * 1` | Provider-agnostic (all three) presence drift check + `accountingSyncTieOut` writer — one cell per (integration × period × account) |+| `accounting-consolidation` | cron `0 2 * * *` | Daily-consolidation journal push (one aggregated provider journal per posting date) |+| `accounting-backfill` | `carbon/accounting-backfill` | Explicit history backfill |+## Workflow functions (`src/inngest/functions/workflows/`)| Function | Event | Purpose |diff --git a/packages/jobs/src/inngest/functions/events/queue.ts b/packages/jobs/src/inngest/functions/events/queue.tsindex 496a1c0a96..fb11b23631 100644--- a/packages/jobs/src/inngest/functions/events/queue.ts+++ b/packages/jobs/src/inngest/functions/events/queue.ts@@ -47,6 +47,7 @@ export const eventQueueFunction = inngest.createFunction({ event: "carbon/event-queue.process" },async ({ step }) => {let routed = 0;+ let poisonedTotal = 0;let lastPassFull = false;for (let pass = 0; pass < MAX_PASSES; pass++) {@@ -54,9 +55,10 @@ export const eventQueueFunction = inngest.createFunction(type ReadQueueResult = {grouped: Record<HandlerType, QueueJob[]>;allIds: number[];+ poisoned: number[];};- const { grouped, allIds } = (await step.run(+ const { grouped, allIds, poisoned } = (await step.run(`read-queue-${pass}`,async () => {const pg = getJobDatabaseClient();@@ -74,22 +76,51 @@ export const eventQueueFunction = inngest.createFunction(EMBEDDING: []};+ // Unknown handler types are poison: pushing into a missing bucket+ // would throw, crash-loop the drainer, and wedge ALL event+ // processing. Collect them for archival to pgmq's dead-letter+ // (pgmq.a_event_system) instead.+ const poisoned: number[] = [];+ const allIds: number[] = [];for (const job of jobs) {- grouped[job.message.handlerType].push(job);+ const bucket = grouped[job.message.handlerType];+ if (bucket) {+ bucket.push(job);+ allIds.push(job.msg_id);+ } else {+ console.error(+ `event-queue: unknown handlerType "${job.message?.handlerType}" on msg_id ${job.msg_id}; archiving to dead-letter`+ );+ poisoned.push(job.msg_id);+ }}return {grouped,- allIds: jobs.map((j) => j.msg_id)+ allIds,+ poisoned};})) as ReadQueueResult;- if (allIds.length === 0) {+ if (allIds.length === 0 && poisoned.length === 0) {lastPassFull = false;break;}+ // 2. Archive poisoned messages to pgmq's built-in dead-letter table+ // (pgmq.a_event_system). Archiving dequeues, so these ids are already+ // excluded from the delete-processed list below.+ if (poisoned.length > 0) {+ await step.run(`archive-poisoned-${pass}`, async () => {+ const pg = getJobDatabaseClient();+ await sql`SELECT pgmq.archive(${QUEUE_NAME}, ${poisoned}::bigint[])`.execute(+ pg+ );+ });+ poisonedTotal += poisoned.length;+ }+// 3. Dispatch webhooksif (grouped.WEBHOOK.length > 0) {const events = grouped.WEBHOOK.map((job) => ({@@ -195,16 +226,19 @@ export const eventQueueFunction = inngest.createFunction(}}- // 9. Delete processed messages from PGMQ- await step.run(`delete-processed-${pass}`, async () => {- const pg = getJobDatabaseClient();- await sql`SELECT pgmq.delete(${QUEUE_NAME}, id::bigint) FROM unnest(${allIds}::bigint[]) AS id`.execute(- pg- );- });+ // 9. Delete processed messages from PGMQ (archived poison ids are+ // excluded — archive already dequeued them)+ if (allIds.length > 0) {+ await step.run(`delete-processed-${pass}`, async () => {+ const pg = getJobDatabaseClient();+ await sql`SELECT pgmq.delete(${QUEUE_NAME}, id::bigint) FROM unnest(${allIds}::bigint[]) AS id`.execute(+ pg+ );+ });+ }routed += allIds.length;- lastPassFull = allIds.length === BATCH_SIZE;+ lastPassFull = allIds.length + poisoned.length === BATCH_SIZE;if (!lastPassFull) {break;}@@ -219,6 +253,6 @@ export const eventQueueFunction = inngest.createFunction(});}- return { routed };+ return { routed, poisoned: poisonedTotal };});diff --git a/packages/jobs/src/inngest/functions/events/subscriptions-mapping.test.ts b/packages/jobs/src/inngest/functions/events/subscriptions-mapping.test.tsnew file mode 100644index 0000000000..d383f0f8b1--- /dev/null+++ b/packages/jobs/src/inngest/functions/events/subscriptions-mapping.test.ts@@ -0,0 +1,50 @@+import {+ ProviderID,+ qboSyncerRegistry,+ REQUIRED_SYNC_SUBSCRIPTIONS,+ rilletSyncerRegistry,+ xeroSyncerRegistry+} from "@carbon/ee/accounting";+import { describe, expect, it } from "vitest";+import { TABLE_TO_ENTITY_MAP } from "./sync-tables";++/**+ * Pillar A invariant (v4 spec): every table a provider subscribes to must+ * route somewhere real — a TABLE_TO_ENTITY_MAP entry AND a registered+ * syncer for the mapped entity type. Without this, a subscription is a+ * dead letter: `dispatch_event_batch()` enqueues events the SYNC handler+ * silently drops, which reads as "sync is on" while nothing ever pushes.+ *+ * If this test fails you either added a table to+ * REQUIRED_SYNC_SUBSCRIPTIONS without wiring the handler/syncer, or+ * removed a mapping a subscription still relies on.+ */++const SYNCER_REGISTRIES = {+ [ProviderID.XERO]: xeroSyncerRegistry,+ [ProviderID.QUICKBOOKS]: qboSyncerRegistry,+ [ProviderID.RILLET]: rilletSyncerRegistry+} as const;++describe("REQUIRED_SYNC_SUBSCRIPTIONS ↔ TABLE_TO_ENTITY_MAP ↔ syncer registries", () => {+ for (const providerId of Object.values(ProviderID)) {+ describe(providerId, () => {+ const registry = SYNCER_REGISTRIES[providerId];++ for (const subscription of REQUIRED_SYNC_SUBSCRIPTIONS[providerId]) {+ it(`routes '${subscription.table}' to a registered syncer`, () => {+ const entityType = TABLE_TO_ENTITY_MAP[subscription.table];+ expect(+ entityType,+ `table '${subscription.table}' has no TABLE_TO_ENTITY_MAP entry`+ ).toBeDefined();++ expect(+ registry[entityType!],+ `${providerId} registers no syncer for '${entityType}'`+ ).toBeDefined();+ });+ }+ });+ }+});diff --git a/packages/jobs/src/inngest/functions/events/sync-tables.ts b/packages/jobs/src/inngest/functions/events/sync-tables.tsnew file mode 100644index 0000000000..e0004668e2--- /dev/null+++ b/packages/jobs/src/inngest/functions/events/sync-tables.ts@@ -0,0 +1,31 @@+import type { AccountingEntityType } from "@carbon/ee/accounting";++/**+ * Map database table names to accounting entity types. Every table in+ * REQUIRED_SYNC_SUBSCRIPTIONS (@carbon/ee/accounting core/subscriptions)+ * must have an entry here — pinned by subscriptions-mapping.test.ts — or+ * its subscription is a dead letter (events dispatch, the handler drops+ * them as "no entity mapping").+ *+ * Import-light on purpose (no @carbon/auth / Inngest): the invariant test+ * imports this without booting env config.+ */+export const TABLE_TO_ENTITY_MAP: Partial<+ Record<string, AccountingEntityType>+> = {+ customer: "customer",+ supplier: "vendor",+ item: "item",+ purchaseOrder: "purchaseOrder",+ purchaseInvoice: "bill",+ salesInvoice: "invoice",+ salesOrder: "salesOrder",+ journal: "journalEntry",+ payment: "payment"+};++export function getEntityTypeFromTable(+ table: string+): AccountingEntityType | null {+ return TABLE_TO_ENTITY_MAP[table] ?? null;+}diff --git a/packages/jobs/src/inngest/functions/events/sync.ts b/packages/jobs/src/inngest/functions/events/sync.tsindex 44e5c08b47..48e887fe59 100644--- a/packages/jobs/src/inngest/functions/events/sync.ts+++ b/packages/jobs/src/inngest/functions/events/sync.ts@@ -1,3 +1,24 @@+/**+ * SYNC event handler — v5 reconciler shape+ * (.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md, D3).+ *+ * Events are HINTS, not decisions: a DB write on a subscribed table means+ * "reconcile this entity now". The handler maps table → entity type,+ * dedupes the batch into refs, and hands them to the SAME+ * `reconcileEntities` executor the outbound sweep uses — the decision of+ * whether anything should happen lives in ONE place+ * (computeReconcileDecision), derived from current state, never from the+ * event's old/new delta.+ *+ * Deleted with v5 (their failure classes are unrepresentable now):+ * - the completed-row cooldown on this path (an unchanged entity reconciles+ * to nothing by state; a changed one enqueues immediately);+ * - `isStatusTransitionEvent` routing (no cooldown to bypass);+ * - the per-table journal/payment decision branches (state-shaped in D1).+ *+ * DELETEs remain logged-and-skipped (DELETE sync is unimplemented; a+ * deleted row also reconciles to nothing by construction).+ */import { getCarbonServiceRole } from "@carbon/auth/client.server";import {getPostgresClient,@@ -5,18 +26,25 @@ import {} from "@carbon/database/client";import { EventSchema } from "@carbon/database/event";import {- type AccountingEntityType,- type BatchSyncResult,getAccountingIntegration,getProviderIntegration,- ProviderID,- RatelimitError,- SyncFactory+ ProviderID} from "@carbon/ee/accounting";-import { groupBy, pluckUnique } from "@carbon/utils";+import { groupBy } from "@carbon/utils";import { PostgresDriver } from "kysely";import { z } from "zod";import { inngest } from "../../client";+import {+ type DrainSummary,+ drainSyncOperations,+ getSyncOperationActor+} from "../integrations/accounting-sync-operations";+import type { ReconcileRef } from "../integrations/reconcile";+import {+ type ReconcileSummary,+ reconcileEntities+} from "../integrations/reconcile-executor";+import { getEntityTypeFromTable } from "./sync-tables";const SyncRecordSchema = z.object({event: EventSchema,@@ -32,33 +60,30 @@ const SyncPayloadSchema = z.object({export type SyncPayload = z.infer<typeof SyncPayloadSchema>;-// Map database table names to accounting entity types-const TABLE_TO_ENTITY_MAP: Partial<Record<string, AccountingEntityType>> = {- customer: "customer",- supplier: "vendor",- item: "item",- purchaseOrder: "purchaseOrder",- purchaseInvoice: "bill",- salesInvoice: "invoice"-};--function getEntityTypeFromTable(table: string): AccountingEntityType | null {- return TABLE_TO_ENTITY_MAP[table] ?? null;-}-export const syncFunction = inngest.createFunction({id: "event-handler-sync",retries: 3},{ event: "carbon/event-sync" },- async ({ event, step, logger }) => {+ async ({ event, step, runId, logger }) => {const payload = SyncPayloadSchema.parse(event.data);logger.info(`Processing ${payload.records.length} sync events`);+ // Scopes the ledger idempotency keys to this delivery: Inngest retries+ // reuse the same event id (absorbed), later deliveries get fresh keys+ const reconcileScope = event.id ?? runId;+const results = {- success: [] as BatchSyncResult[],+ reconciled: [] as Array<+ { companyId: string; provider: string } & ReconcileSummary+ >,+ drains: [] as Array<{+ companyId: string;+ provider: string;+ drain: DrainSummary["groups"];+ }>,failed: [] as { recordId: string; error: string }[],skipped: [] as { recordId: string; reason: string }[]};@@ -74,6 +99,8 @@ export const syncFunction = inngest.createFunction(const kysely = getPostgresClient(pool, PostgresDriver);const client = getCarbonServiceRole();+ // NOTE: the pool from getPostgresConnectionPool is a process-lifetime+ // singleton (see lib/postgres) — do NOT end it per invocation.for (const [key, records] of Object.entries(byCompanyProvider)) {const [companyId, provider] = key.split(":");@@ -87,135 +114,156 @@ export const syncFunction = inngest.createFunction(continue;}- // Process each company-provider group as a step for checkpointing- type GroupResults = {- success: BatchSyncResult[];+ // Step 1: reconcile the hinted entities (checkpointed so a retry+ // replays the outcome; enqueue/terminal writes are idempotent by+ // ledger key, so re-runs cannot duplicate work)+ type ReconcileStepSummary = {+ aborted: boolean;+ summary: ReconcileSummary | null;failed: { recordId: string; error: string }[];skipped: { recordId: string; reason: string }[];};- const groupResult = (await step.run(- `sync-${companyId}-${provider}`,+ const reconcileSummary = (await step.run(+ `reconcile-${companyId}-${provider}`,async () => {- const groupResults: GroupResults = {- success: [],+ const stepSummary: ReconcileStepSummary = {+ aborted: false,+ summary: null,failed: [],skipped: []};try {- // Get integration and provider instanceconst integration = await getAccountingIntegration(client,companyId,provider as ProviderID);- const providerInstance = getProviderIntegration(- client,- companyId,- provider as ProviderID,- integration.metadata- );-- // Group by entity type- const byEntityType = groupBy(records, (r) => {+ const seen = new Set<string>();+ const refs: ReconcileRef[] = [];+ for (const r of records) {const entityType = getEntityTypeFromTable(r.event.table);- return entityType ?? "unknown";- });-- for (const [entityType, entityRecords] of Object.entries(- byEntityType- )) {- if (entityType === "unknown") {- for (const r of entityRecords) {- groupResults.skipped.push({- recordId: r.event.recordId,- reason: `Table '${r.event.table}' has no entity mapping`- });- }+ if (!entityType) {+ stepSummary.skipped.push({+ recordId: r.event.recordId,+ reason: `Table '${r.event.table}' has no entity mapping`+ });continue;}-- // Separate by operation- const inserts = entityRecords.filter(- (r) => r.event.operation === "INSERT"- );- const updates = entityRecords.filter(- (r) => r.event.operation === "UPDATE"- );- const deletes = entityRecords.filter(- (r) => r.event.operation === "DELETE"- );-- const syncer = SyncFactory.getSyncer({- database: kysely,- companyId,- provider: providerInstance,- config: providerInstance.getSyncConfig(- entityType as AccountingEntityType- ),- entityType: entityType as AccountingEntityType- });-- // Process INSERTs and UPDATEs (push to accounting)- const toSync = [...inserts, ...updates];- if (toSync.length > 0) {- const entityIds = pluckUnique(toSync, (r) => r.event.recordId);-- logger.info(- `Pushing ${entityIds.length} ${entityType} entities to accounting`- );-- // Handle rate limiting with retry- let result: BatchSyncResult;- try {- result = await syncer.pushBatchToAccounting(entityIds);- } catch (error) {- if (error instanceof RatelimitError) {- const { retryAfterSeconds } = error.rateLimitInfo;- logger.warn(- `Hit rate limit, will retry after ${retryAfterSeconds}s`- );- // Let inngest handle the retry by throwing- throw error;- }- throw error;- }-- logger.info("Sync result", { entityType, result });- groupResults.success.push(result);- }-- // Handle DELETEs (log for now, not yet implemented in syncers)- for (const del of deletes) {- groupResults.skipped.push({- recordId: del.event.recordId,+ if (r.event.operation === "DELETE") {+ stepSummary.skipped.push({+ recordId: r.event.recordId,reason: "DELETE operations not yet implemented"});+ continue;}+ if (+ r.event.operation !== "INSERT" &&+ r.event.operation !== "UPDATE"+ ) {+ continue;+ }+ const refKey = `${entityType}:${r.event.recordId}`;+ if (seen.has(refKey)) continue;+ seen.add(refKey);+ refs.push({+ entityType: entityType as ReconcileRef["entityType"],+ entityId: r.event.recordId+ });}++ stepSummary.summary = await reconcileEntities({+ client,+ database: kysely,+ companyId,+ providerId: provider,+ integrationMetadata: integration.metadata,+ createdBy: getSyncOperationActor(integration),+ scope: reconcileScope,+ refs+ });} catch (error) {- logger.error(`Failed to process sync for ${key}`, { error });+ logger.error(`Failed to reconcile sync events for ${key}`, {+ error+ });+ stepSummary.aborted = true;for (const r of records) {- groupResults.failed.push({+ stepSummary.failed.push({recordId: r.event.recordId,error: error instanceof Error ? error.message : "Unknown error"});}}- return groupResults;+ return stepSummary;}- )) as GroupResults;+ )) as ReconcileStepSummary;++ results.failed.push(...reconcileSummary.failed);+ results.skipped.push(...reconcileSummary.skipped);+ if (reconcileSummary.summary) {+ results.reconciled.push({+ companyId,+ provider,+ ...reconcileSummary.summary+ });+ }++ // The integration could not be resolved — there is nothing to drain+ // for this group (matches the pre-ledger behavior of recording the+ // failure without failing the run)+ if (reconcileSummary.aborted) continue;++ // Step 2: drain — claim Pending operations (including UI retries and+ // stale In Flight rows) and run the entity syncers. A throw re-runs+ // the step; claim/complete are idempotent so retries cannot+ // duplicate work.+ const drainSummary = (await step.run(+ `drain-${companyId}-${provider}`,+ async () => {+ const integration = await getAccountingIntegration(+ client,+ companyId,+ provider as ProviderID+ );++ const providerInstance = getProviderIntegration(+ client,+ companyId,+ provider as ProviderID,+ integration.metadata+ );++ return drainSyncOperations({+ client,+ database: kysely,+ companyId,+ integration: provider,+ provider: providerInstance,+ integrationMetadata: integration.metadata+ });+ }+ )) as DrainSummary;++ for (const group of drainSummary.groups) {+ logger.info("Sync result", {+ entityType: group.entityType,+ direction: group.direction,+ result: group.result+ });+ }- results.success.push(...groupResult.success);- results.failed.push(...groupResult.failed);- results.skipped.push(...groupResult.skipped);+ results.drains.push({+ companyId,+ provider,+ drain: drainSummary.groups+ });}logger.info("Sync function completed", {- successCount: results.success.reduce((acc, r) => acc + r.successCount, 0),+ reconciled: results.reconciled.length,failedCount: results.failed.length,skippedCount: results.skipped.length});diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-backfill.ts b/packages/jobs/src/inngest/functions/integrations/accounting-backfill.tsindex 885b206fda..9a27cb31c1 100644--- a/packages/jobs/src/inngest/functions/integrations/accounting-backfill.ts+++ b/packages/jobs/src/inngest/functions/integrations/accounting-backfill.ts@@ -8,6 +8,11 @@** This prevents unnecessary syncing (e.g., items configured as push-only* won't be pulled from Xero, and POs configured as push-only won't try to pull).+ *+ * Each page/batch routes through the "accountingSyncOperation" ledger with+ * trigger "backfill": operations are enqueued with keys scoped to this run+ * (retried steps are absorbed; completed rows from earlier runs never block+ * a new backfill) and drained in the same step.*/import { getCarbonServiceRole } from "@carbon/auth/client.server";import {@@ -20,14 +25,24 @@ import {getProviderIntegration,ProviderID,RatelimitError,+ resolvePostingSyncSettings,type SyncDirection,- SyncFactory,type XeroProvider} from "@carbon/ee/accounting";import { getLogger } from "@carbon/logger";import { PostgresDriver } from "kysely";import z from "zod";import { inngest } from "../../client";+import {+ drainSyncOperations,+ enqueueSyncOperations,+ getSyncOperationActor,+ insertTerminalSyncOperations,+ isJournalEntryPostingEnabled,+ planJournalPostingOperation,+ type SyncOperationRequest,+ type TerminalSyncOperationRequest+} from "./accounting-sync-operations";const log = getLogger("jobs", "accounting-backfill");@@ -51,7 +66,7 @@ async function withRateLimitRetry<T>(} catch (error) {if (error instanceof RatelimitError) {const { retryAfterSeconds, limitType, details } = error.rateLimitInfo;- log.warning(`${operationName} hit rate limit`, {+ log.warning(`[RATE LIMIT] ${operationName} hit rate limit`, {limitType,retryAfterSeconds,...details@@ -60,7 +75,9 @@ async function withRateLimitRetry<T>(`rate-limit-wait-${operationName}`,`${retryAfterSeconds}s`);- log.info(`Retrying ${operationName} after ${retryAfterSeconds}s wait`);+ log.info(+ `[RATE LIMIT] Retrying ${operationName} after ${retryAfterSeconds}s wait`+ );return await operation();}throw error;@@ -104,12 +121,17 @@ type ParsedBackfillPayload = z.output<typeof BackfillPayloadSchema>;export const accountingBackfillFunction = inngest.createFunction({ id: "accounting-backfill", retries: 3 },{ event: "carbon/accounting-backfill" },- async ({ event, step, logger }) => {+ async ({ event, step, runId }) => {const payload: ParsedBackfillPayload = BackfillPayloadSchema.parse(event.data);const client = getCarbonServiceRole();+ // Scopes the ledger idempotency keys to this backfill run: retried steps+ // re-enqueue with the same keys (absorbed), a fresh backfill run gets new+ // keys so previously Completed rows never block it+ const backfillRunId = event.id ?? runId;+const integration = await getAccountingIntegration(client,payload.companyId,@@ -137,7 +159,7 @@ export const accountingBackfillFunction = inngest.createFunction(};// Log the sync directions for visibility- logger.info("Starting with entity sync directions", {+ log.info("[BACKFILL] Starting with entity sync directions:", {customer: {enabled: customerConfig?.enabled,direction: customerConfig?.direction,@@ -160,6 +182,187 @@ export const accountingBackfillFunction = inngest.createFunction(}});+ // ============================================================+ // PHASE 0: Journal posting dispositions (spec I1 missed-event repair)+ //+ // Every posted journal since postingSync.syncFromDate must have an+ // operation row — pushable journals whose event was missed enqueue,+ // policy-excluded ones get their terminal disposition recorded. Runs+ // only when posting sync is enabled AND an explicit syncFromDate is+ // set (no silent mass-push of a company's whole history).+ // ============================================================++ await step.run("backfill-journal-dispositions", async () => {+ const phaseClient = getCarbonServiceRole();+ const phaseIntegration = await getAccountingIntegration(+ phaseClient,+ payload.companyId,+ payload.provider+ );++ const summary = {+ enqueued: 0,+ recorded: 0,+ alreadyCovered: 0,+ pages: 0,+ truncated: false,+ skippedReason: null as string | null+ };++ if (!isJournalEntryPostingEnabled(phaseIntegration.metadata)) {+ summary.skippedReason = "posting sync (journalEntry) disabled";+ return summary;+ }++ const settings = resolvePostingSyncSettings(phaseIntegration.metadata);+ const syncFromDate = settings.syncFromDate?.slice(0, 10);+ if (!syncFromDate) {+ summary.skippedReason =+ "postingSync.syncFromDate is not set — journal backfill requires an explicit start date";+ return summary;+ }++ const createdBy = getSyncOperationActor(phaseIntegration);+ const pageSize = 200;+ const maxPages = 50; // bound the step; re-run the backfill for more+ let offset = 0;++ for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {+ const journals = await phaseClient+ .from("journal")+ .select("id, sourceType, status, reversalOfId")+ .eq("companyId", payload.companyId)+ .in("status", ["Posted", "Reversed"])+ .is("reversalOfId", null)+ .gte("postingDate", syncFromDate)+ .order("id", { ascending: true })+ .range(offset, offset + pageSize - 1);++ if (journals.error) {+ throw new Error(+ `Failed to page journals for disposition backfill: ${journals.error.message}`+ );+ }++ const rows = journals.data ?? [];+ if (rows.length === 0) break;+ summary.pages++;++ const candidateEntityIds = rows.flatMap((row) =>+ row.status === "Reversed" ? [row.id, `${row.id}:reversal`] : [row.id]+ );++ const existing = await phaseClient+ .from("accountingSyncOperation")+ .select("entityId")+ .eq("companyId", payload.companyId)+ .eq("integration", payload.provider)+ .eq("entityType", "journalEntry")+ .in("entityId", candidateEntityIds);++ if (existing.error) {+ throw new Error(+ `Failed to load existing journal operations: ${existing.error.message}`+ );+ }++ const covered = new Set(+ (existing.data ?? []).map((row) => row.entityId)+ );++ const pushRequests: SyncOperationRequest[] = [];+ const terminalRequests: TerminalSyncOperationRequest[] = [];++ for (const row of rows) {+ if (covered.has(row.id)) {+ summary.alreadyCovered++;+ } else {+ const plan = await planJournalPostingOperation({+ client: phaseClient,+ companyId: payload.companyId,+ event: {+ operation: "INSERT",+ recordId: row.id,+ new: {+ status: "Posted",+ reversalOfId: null,+ sourceType: row.sourceType+ },+ old: null+ },+ integrationMetadata: phaseIntegration.metadata+ });++ if (plan.action === "push") {+ pushRequests.push(plan.request);+ } else if (plan.action === "terminal") {+ terminalRequests.push(plan.request);+ }+ }++ // A Reversed journal's reversal push rides the original's policy+ // decision (same source type); record it when missing too+ if (row.status === "Reversed" && !covered.has(`${row.id}:reversal`)) {+ const reversalPlan = await planJournalPostingOperation({+ client: phaseClient,+ companyId: payload.companyId,+ event: {+ operation: "UPDATE",+ recordId: row.id,+ new: {+ status: "Reversed",+ reversalOfId: null,+ sourceType: row.sourceType+ },+ old: { status: "Posted" }+ },+ integrationMetadata: phaseIntegration.metadata+ });++ if (reversalPlan.action === "push") {+ pushRequests.push(reversalPlan.request);+ } else if (reversalPlan.action === "terminal") {+ terminalRequests.push(reversalPlan.request);+ }+ }+ }++ const enqueueOutcomes = await enqueueSyncOperations(phaseClient, {+ companyId: payload.companyId,+ integration: payload.provider,+ trigger: "backfill",+ createdBy,+ scope: backfillRunId,+ requests: pushRequests+ });+ summary.enqueued += enqueueOutcomes.filter(+ (outcome) => outcome.outcome === "enqueued"+ ).length;++ const terminalOutcomes = await insertTerminalSyncOperations(+ phaseClient,+ {+ companyId: payload.companyId,+ integration: payload.provider,+ trigger: "backfill",+ createdBy,+ scope: backfillRunId,+ requests: terminalRequests+ }+ );+ summary.recorded += terminalOutcomes.filter(+ (outcome) => outcome.outcome === "enqueued"+ ).length;++ if (rows.length < pageSize) break;+ offset += pageSize;+ if (pageIndex === maxPages - 1) summary.truncated = true;+ }++ log.info("[BACKFILL] Journal disposition phase complete", summary);+ return summary;+ });+// ============================================================// PHASE 1: Pull contacts from accounting (respecting direction config)// ============================================================@@ -178,7 +381,7 @@ export const accountingBackfillFunction = inngest.createFunction(let page = 1;let hasMore = true;- logger.info("Starting contact pull phase", {+ log.info("[PULL] Starting contact pull phase", {pullCustomers,pullVendors});@@ -204,7 +407,7 @@ export const accountingBackfillFunction = inngest.createFunction(const pool = getPostgresConnectionPool(5);const kysely = getPostgresClient(pool, PostgresDriver);- logger.info(`Fetching contacts page ${currentPage}`);+ log.info(`[PULL] Fetching contacts page ${currentPage}`);const response = await withRateLimitRetry(() =>pullProvider.listContacts({@@ -215,7 +418,7 @@ export const accountingBackfillFunction = inngest.createFunction(step);- logger.info(`Contacts page ${currentPage} response`, {+ log.info(`[PULL] Contacts page ${currentPage} response`, {count: response.contacts.length,hasMore: response.hasMore,contacts: response.contacts.map((c) => ({@@ -236,70 +439,89 @@ export const accountingBackfillFunction = inngest.createFunction(let customersPulled = 0;let vendorsPulled = 0;- // Pull customers+ const requests: SyncOperationRequest[] = [];+if (pullCustomers) {- const customers = response.contacts.filter((c) => c.IsCustomer);- if (customers.length > 0) {- const syncer = SyncFactory.getSyncer({- database: kysely,- companyId: payload.companyId,- provider: pullProvider,- config: pullProvider.getSyncConfig("customer"),- entityType: "customer"+ for (const contact of response.contacts.filter(+ (c) => c.IsCustomer+ )) {+ requests.push({+ entityType: "customer",+ entityId: contact.ContactID,+ direction: "pull-from-accounting"});- const ids = customers.map((c) => c.ContactID);- const syncResult = await withRateLimitRetry(- () => syncer.pullBatchFromAccounting(ids),- `pullBatchFromAccounting customers page ${currentPage}`,- step- );- customersPulled = syncResult.successCount;- logger.info(- `Page ${currentPage}: pulled ${customersPulled} customers`,- {- results: syncResult.results.map((r) => ({- status: r.status,- action: r.action,- localId: r.localId,- remoteId: r.remoteId,- error: r.error- }))- }- );}}- // Pull vendorsif (pullVendors) {- const vendors = response.contacts.filter((c) => c.IsSupplier);- if (vendors.length > 0) {- const syncer = SyncFactory.getSyncer({- database: kysely,- companyId: payload.companyId,- provider: pullProvider,- config: pullProvider.getSyncConfig("vendor"),- entityType: "vendor"+ for (const contact of response.contacts.filter(+ (c) => c.IsSupplier+ )) {+ requests.push({+ entityType: "vendor",+ entityId: contact.ContactID,+ direction: "pull-from-accounting"});- const ids = vendors.map((c) => c.ContactID);- const syncResult = await withRateLimitRetry(- () => syncer.pullBatchFromAccounting(ids),- `pullBatchFromAccounting vendors page ${currentPage}`,- step+ }+ }++ if (requests.length > 0) {+ const outcomes = await enqueueSyncOperations(pullClient, {+ companyId: payload.companyId,+ integration: payload.provider,+ trigger: "backfill",+ createdBy: getSyncOperationActor(pullIntegration),+ scope: backfillRunId,+ requests+ });++ const enqueueErrors = outcomes.filter(+ (o) => o.outcome === "error"+ );+ if (enqueueErrors.length > 0) {+ log.error(+ `[PULL] Failed to enqueue ${enqueueErrors.length} contact operations`);- vendorsPulled = syncResult.successCount;- logger.info(- `Page ${currentPage}: pulled ${vendorsPulled} vendors`,- {- results: syncResult.results.map((r) => ({+ }++ const drained = await withRateLimitRetry(+ () =>+ drainSyncOperations({+ client: pullClient,+ database: kysely,+ companyId: payload.companyId,+ integration: payload.provider,+ provider: pullProvider,+ integrationMetadata: pullIntegration.metadata+ }),+ `drain contacts page ${currentPage}`,+ step+ );++ for (const group of drained.groups) {+ if (group.direction !== "pull-from-accounting") continue;+ if (group.entityType === "customer") {+ customersPulled += group.result.successCount;+ }+ if (group.entityType === "vendor") {+ vendorsPulled += group.result.successCount;+ }+ }++ log.info(+ `[PULL] Page ${currentPage}: pulled ${customersPulled} customers, ${vendorsPulled} vendors`,+ {+ results: drained.groups.flatMap((g) =>+ g.result.results.map((r) => ({status: r.status,action: r.action,localId: r.localId,remoteId: r.remoteId,error: r.error}))- }- );- }+ )+ }+ );}return {@@ -324,8 +546,8 @@ export const accountingBackfillFunction = inngest.createFunction(}}} else {- logger.info(- "Skipping contact pull - not enabled or direction is push-only"+ log.info(+ "[PULL] Skipping contact pull - not enabled or direction is push-only");}@@ -342,7 +564,7 @@ export const accountingBackfillFunction = inngest.createFunction(let page = 1;let hasMore = true;- logger.info("Starting items pull phase");+ log.info("[PULL] Starting items pull phase");while (hasMore) {const currentPage = page;@@ -365,14 +587,14 @@ export const accountingBackfillFunction = inngest.createFunction(const pool = getPostgresConnectionPool(5);const kysely = getPostgresClient(pool, PostgresDriver);- logger.info(`Fetching items page ${currentPage}`);+ log.info(`[PULL] Fetching items page ${currentPage}`);const response = await withRateLimitRetry(() => pullProvider.listItems({ page: currentPage }),`listItems page ${currentPage}`,step);- logger.info(`Items page ${currentPage} response`, {+ log.info(`[PULL] Items page ${currentPage} response`, {count: response.items.length,hasMore: response.hasMore,items: response.items.map((i) => ({@@ -386,36 +608,70 @@ export const accountingBackfillFunction = inngest.createFunction(return { hasMore: false, pulled: { items: 0 } };}- const syncer = SyncFactory.getSyncer({- database: kysely,+ const requests: SyncOperationRequest[] = response.items.map(+ (item) => ({+ entityType: "item",+ entityId: item.ItemID,+ direction: "pull-from-accounting"+ })+ );++ const outcomes = await enqueueSyncOperations(pullClient, {companyId: payload.companyId,- provider: pullProvider,- config: pullProvider.getSyncConfig("item"),- entityType: "item"+ integration: payload.provider,+ trigger: "backfill",+ createdBy: getSyncOperationActor(pullIntegration),+ scope: backfillRunId,+ requests});- const ids = response.items.map((item) => item.ItemID);- const syncResult = await withRateLimitRetry(- () => syncer.pullBatchFromAccounting(ids),- `pullBatchFromAccounting items page ${currentPage}`,++ const enqueueErrors = outcomes.filter((o) => o.outcome === "error");+ if (enqueueErrors.length > 0) {+ log.error(+ `[PULL] Failed to enqueue ${enqueueErrors.length} item operations`+ );+ }++ const drained = await withRateLimitRetry(+ () =>+ drainSyncOperations({+ client: pullClient,+ database: kysely,+ companyId: payload.companyId,+ integration: payload.provider,+ provider: pullProvider,+ integrationMetadata: pullIntegration.metadata+ }),+ `drain items page ${currentPage}`,step);- logger.info(- `Page ${currentPage}: pulled ${syncResult.successCount} items`,+ const itemsPulled = drained.groups+ .filter(+ (g) =>+ g.entityType === "item" &&+ g.direction === "pull-from-accounting"+ )+ .reduce((acc, g) => acc + g.result.successCount, 0);++ log.info(+ `[PULL] Page ${currentPage}: pulled ${itemsPulled} items`,{- results: syncResult.results.map((r) => ({- status: r.status,- action: r.action,- localId: r.localId,- remoteId: r.remoteId,- error: r.error- }))+ results: drained.groups.flatMap((g) =>+ g.result.results.map((r) => ({+ status: r.status,+ action: r.action,+ localId: r.localId,+ remoteId: r.remoteId,+ error: r.error+ }))+ )});return {hasMore: response.hasMore,- pulled: { items: syncResult.successCount }+ pulled: { items: itemsPulled }};});@@ -430,8 +686,8 @@ export const accountingBackfillFunction = inngest.createFunction(}}} else {- logger.info(- "Skipping items pull - not enabled or direction is push-only"+ log.info(+ "[PULL] Skipping items pull - not enabled or direction is push-only");}@@ -449,7 +705,7 @@ export const accountingBackfillFunction = inngest.createFunction(let hasMore = true;let batchIndex = 0;- logger.info("Starting customers push phase");+ log.info("[PUSH] Starting customers push phase");while (hasMore) {const currentBatchIndex = batchIndex;@@ -491,37 +747,72 @@ export const accountingBackfillFunction = inngest.createFunction(};}- const syncer = SyncFactory.getSyncer({- database: kysely,+ const outcomes = await enqueueSyncOperations(pushClient, {companyId: payload.companyId,- provider: pushProvider,- config: pushProvider.getSyncConfig("customer"),- entityType: "customer"+ integration: payload.provider,+ trigger: "backfill",+ createdBy: getSyncOperationActor(pushIntegration),+ scope: backfillRunId,+ requests: unsyncedIds.map((id) => ({+ entityType: "customer",+ entityId: id,+ direction: "push-to-accounting"+ }))});- const syncResult = await withRateLimitRetry(- () => syncer.pushBatchToAccounting(unsyncedIds),- `pushBatchToAccounting customers`,+ const enqueueErrors = outcomes.filter((o) => o.outcome === "error");+ if (enqueueErrors.length > 0) {+ log.error(+ `[PUSH] Failed to enqueue ${enqueueErrors.length} customer operations`+ );+ }++ const drained = await withRateLimitRetry(+ () =>+ drainSyncOperations({+ client: pushClient,+ database: kysely,+ companyId: payload.companyId,+ integration: payload.provider,+ provider: pushProvider,+ integrationMetadata: pushIntegration.metadata+ }),+ `drain customers push batch ${currentBatchIndex}`,step);- logger.info(- `Pushed ${syncResult.successCount}/${unsyncedIds.length} customer entities`,+ const successCount = drained.groups+ .filter(+ (g) =>+ g.entityType === "customer" &&+ g.direction === "push-to-accounting"+ )+ .reduce((acc, g) => acc + g.result.successCount, 0);++ log.info(+ `[PUSH] Pushed ${successCount}/${unsyncedIds.length} customer entities`,{entityIds: unsyncedIds,- results: syncResult.results.map((r) => ({- status: r.status,- action: r.action,- localId: r.localId,- remoteId: r.remoteId,- error: r.error- }))+ results: drained.groups.flatMap((g) =>+ g.result.results.map((r) => ({+ status: r.status,+ action: r.action,+ localId: r.localId,+ remoteId: r.remoteId,+ error: r.error+ }))+ )});return {- successCount: syncResult.successCount,- hasMore: unsyncedIds.length >= payload.batchSize+ successCount,+ // Failed pushes stay unmapped and come straight back from+ // getUnsyncedEntityIds, but their idempotency key (same+ // backfill run) absorbs the re-enqueue — stop when the drain+ // claimed nothing so the loop cannot spin without progress+ hasMore:+ unsyncedIds.length >= payload.batchSize && drained.claimed > 0};});@@ -536,8 +827,8 @@ export const accountingBackfillFunction = inngest.createFunction(}}} else {- logger.info(- "Skipping customers push - not enabled or direction is pull-only"+ log.info(+ "[PUSH] Skipping customers push - not enabled or direction is pull-only");}@@ -551,7 +842,7 @@ export const accountingBackfillFunction = inngest.createFunction(let hasMore = true;let batchIndex = 0;- logger.info("Starting vendors push phase");+ log.info("[PUSH] Starting vendors push phase");while (hasMore) {const currentBatchIndex = batchIndex;@@ -593,37 +884,69 @@ export const accountingBackfillFunction = inngest.createFunction(};}- const syncer = SyncFactory.getSyncer({- database: kysely,+ const outcomes = await enqueueSyncOperations(pushClient, {companyId: payload.companyId,- provider: pushProvider,- config: pushProvider.getSyncConfig("vendor"),- entityType: "vendor"+ integration: payload.provider,+ trigger: "backfill",+ createdBy: getSyncOperationActor(pushIntegration),+ scope: backfillRunId,+ requests: unsyncedIds.map((id) => ({+ entityType: "vendor",+ entityId: id,+ direction: "push-to-accounting"+ }))});- const syncResult = await withRateLimitRetry(- () => syncer.pushBatchToAccounting(unsyncedIds),- `pushBatchToAccounting vendors`,+ const enqueueErrors = outcomes.filter((o) => o.outcome === "error");+ if (enqueueErrors.length > 0) {+ log.error(+ `[PUSH] Failed to enqueue ${enqueueErrors.length} vendor operations`+ );+ }++ const drained = await withRateLimitRetry(+ () =>+ drainSyncOperations({+ client: pushClient,+ database: kysely,+ companyId: payload.companyId,+ integration: payload.provider,+ provider: pushProvider,+ integrationMetadata: pushIntegration.metadata+ }),+ `drain vendors push batch ${currentBatchIndex}`,step);- logger.info(- `Pushed ${syncResult.successCount}/${unsyncedIds.length} vendor entities`,+ const successCount = drained.groups+ .filter(+ (g) =>+ g.entityType === "vendor" &&+ g.direction === "push-to-accounting"+ )+ .reduce((acc, g) => acc + g.result.successCount, 0);++ log.info(+ `[PUSH] Pushed ${successCount}/${unsyncedIds.length} vendor entities`,{entityIds: unsyncedIds,- results: syncResult.results.map((r) => ({- status: r.status,- action: r.action,- localId: r.localId,- remoteId: r.remoteId,- error: r.error- }))+ results: drained.groups.flatMap((g) =>+ g.result.results.map((r) => ({+ status: r.status,+ action: r.action,+ localId: r.localId,+ remoteId: r.remoteId,+ error: r.error+ }))+ )});return {- successCount: syncResult.successCount,- hasMore: unsyncedIds.length >= payload.batchSize+ successCount,+ // Same progress guard as the customer push loop+ hasMore:+ unsyncedIds.length >= payload.batchSize && drained.claimed > 0};});@@ -637,8 +960,8 @@ export const accountingBackfillFunction = inngest.createFunction(}}} else {- logger.info(- "Skipping vendors push - not enabled or direction is pull-only"+ log.info(+ "[PUSH] Skipping vendors push - not enabled or direction is pull-only");}@@ -652,7 +975,7 @@ export const accountingBackfillFunction = inngest.createFunction(let hasMore = true;let batchIndex = 0;- logger.info("Starting items push phase");+ log.info("[PUSH] Starting items push phase");while (hasMore) {const currentBatchIndex = batchIndex;@@ -694,37 +1017,69 @@ export const accountingBackfillFunction = inngest.createFunction(};}- const syncer = SyncFactory.getSyncer({- database: kysely,+ const outcomes = await enqueueSyncOperations(pushClient, {companyId: payload.companyId,- provider: pushProvider,- config: pushProvider.getSyncConfig("item"),- entityType: "item"+ integration: payload.provider,+ trigger: "backfill",+ createdBy: getSyncOperationActor(pushIntegration),+ scope: backfillRunId,+ requests: unsyncedIds.map((id) => ({+ entityType: "item",+ entityId: id,+ direction: "push-to-accounting"+ }))});- const syncResult = await withRateLimitRetry(- () => syncer.pushBatchToAccounting(unsyncedIds),- `pushBatchToAccounting items`,+ const enqueueErrors = outcomes.filter((o) => o.outcome === "error");+ if (enqueueErrors.length > 0) {+ log.error(+ `[PUSH] Failed to enqueue ${enqueueErrors.length} item operations`+ );+ }++ const drained = await withRateLimitRetry(+ () =>+ drainSyncOperations({+ client: pushClient,+ database: kysely,+ companyId: payload.companyId,+ integration: payload.provider,+ provider: pushProvider,+ integrationMetadata: pushIntegration.metadata+ }),+ `drain items push batch ${currentBatchIndex}`,step);- logger.info(- `Pushed ${syncResult.successCount}/${unsyncedIds.length} item entities`,+ const successCount = drained.groups+ .filter(+ (g) =>+ g.entityType === "item" &&+ g.direction === "push-to-accounting"+ )+ .reduce((acc, g) => acc + g.result.successCount, 0);++ log.info(+ `[PUSH] Pushed ${successCount}/${unsyncedIds.length} item entities`,{entityIds: unsyncedIds,- results: syncResult.results.map((r) => ({- status: r.status,- action: r.action,- localId: r.localId,- remoteId: r.remoteId,- error: r.error- }))+ results: drained.groups.flatMap((g) =>+ g.result.results.map((r) => ({+ status: r.status,+ action: r.action,+ localId: r.localId,+ remoteId: r.remoteId,+ error: r.error+ }))+ )});return {- successCount: syncResult.successCount,- hasMore: unsyncedIds.length >= payload.batchSize+ successCount,+ // Same progress guard as the customer push loop+ hasMore:+ unsyncedIds.length >= payload.batchSize && drained.claimed > 0};});@@ -738,8 +1093,8 @@ export const accountingBackfillFunction = inngest.createFunction(}}} else {- logger.info(- "Skipping items push - not enabled or direction is pull-only"+ log.info(+ "[PUSH] Skipping items push - not enabled or direction is pull-only");}@@ -749,8 +1104,8 @@ export const accountingBackfillFunction = inngest.createFunction(result.totalPushed =result.customers.pushed + result.vendors.pushed + result.items.pushed;- logger.info(- `Backfill finished. Pulled: ${result.totalPulled}, Pushed: ${result.totalPushed}`+ log.info(+ `[COMPLETE] Backfill finished. Pulled: ${result.totalPulled}, Pushed: ${result.totalPushed}`);return result;diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts b/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.tsnew file mode 100644index 0000000000..3bf4e6a4c8--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/accounting-consolidation.ts@@ -0,0 +1,778 @@+/**+ * Daily-consolidation cron (posting sync, spec Phase B §6).+ *+ * Companies whose posting-sync settings resolve to consolidation "daily"+ * have their journalEntry operations HELD at drain time (the drain excludes+ * the entity type at claim time — see accounting-sync-operations.ts). This+ * cron (02:00 UTC) is the only consumer of those held operations:+ *+ * 1. Pre-scan the claimable journalEntry operations (Pending + stale+ * In Flight) and resolve each journal's posting date.+ * 2. For every candidate date (strictly before today, UTC) reserve a batch+ * MARKER operation with idempotencyKey `daily:<integration>:<date>`.+ * enqueueSyncOperation's return-existing semantics make this the re-run+ * guard: a marker that is already Completed means that date's summary+ * was pushed — late (backdated) members for such a date are pushed+ * INDIVIDUALLY through the normal syncer path instead of silently+ * re-consolidating or stranding.+ * 3. Claim the journalEntry operations (include-only claim), partition them+ * (markers / reversals / by-date members / held / missing), and per date+ * build ONE aggregated journal (aggregateJournalEntriesForDate), run the+ * SAME pre-flights as individual pushes (runJournalEntryPreflight with+ * the syncer's cached account-code map, control accounts and lock date),+ * and push it via createManualJournal.+ * 4. On success every member operation is Completed with+ * `metadata.consolidatedInto = <batch key>` and externalId = the created+ * ManualJournalID; the marker is completed LAST (commit point). On a+ * pre-flight failure the whole batch lands Warning/Failed on every+ * member (errorCode from the pre-flight, metadata listing the member+ * journal ids) and the marker records the same failure.+ *+ * Reversal operations (metadata.reversal) are never consolidated — they are+ * pushed individually through JournalEntrySyncer.pushToAccounting in the+ * same run (the overridden single push preserves structured pre-flight+ * failures; the base BATCH workflow would flatten them to strings).+ *+ * Operations dated today or later stay unpushed: they are left In Flight+ * and recovered by the stale-claim rule on a later run once their date has+ * passed (attemptCount ticks once per held day; journals post-dated far+ * into the future will show a growing attempt count until their date+ * arrives). A RatelimitError aborts the company's step so Inngest retries;+ * claimed rows stay In Flight and become re-claimable once stale.+ */+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ getPostgresClient,+ getPostgresConnectionPool+} from "@carbon/database/client";+import {+ aggregateJournalEntriesForDate,+ claimPendingOperations,+ completeOperation,+ createMappingService,+ enqueueSyncOperation,+ failOperation,+ getAccountingIntegration,+ getPostingSyncSourceTypeSkipReason,+ getProviderIntegration,+ getSyncOperations,+ JournalEntrySyncError,+ type JournalEntrySyncer,+ mapJournalEntryToManualJournal,+ type PostingSyncSettings,+ ProviderID,+ parseJournalEntrySyncEntityId,+ RatelimitError,+ resolvePostingSyncSettings,+ runJournalEntryPreflight,+ type SyncContext,+ SyncFactory,+ type SyncOperation,+ type XeroProvider+} from "@carbon/ee/accounting";+import { PostgresDriver } from "kysely";+import { inngest } from "../../client";+import {+ type ConsolidationGroup,+ getSyncOperationActor,+ getSyncOperationFailureRecord,+ getUtcDateString,+ hasDailySummarySourceTypes,+ isClaimableConsolidationOperation,+ isDailyConsolidationMarker,+ partitionConsolidationOperations,+ toIsoDateString+} from "./accounting-sync-operations";++/** Same bound as the drain: 25 iterations × claim batch of 20 = 500 ops. */+const MAX_CLAIM_ITERATIONS = 25;++/** Pre-scan page size (aligned with the claim bound above). */+const PRESCAN_LIMIT = 500;++const JOURNAL_ID_CHUNK_SIZE = 300;++type ConsolidationSummary = {+ claimed: number;+ batchesPushed: number;+ batchesEmpty: number;+ batchesFailed: number;+ membersCompleted: number;+ membersSkipped: number;+ membersFailed: number;+ individualCompleted: number;+ individualSkipped: number;+ individualFailed: number;+ held: number;+};++const emptySummary = (): ConsolidationSummary => ({+ claimed: 0,+ batchesPushed: 0,+ batchesEmpty: 0,+ batchesFailed: 0,+ membersCompleted: 0,+ membersSkipped: 0,+ membersFailed: 0,+ individualCompleted: 0,+ individualSkipped: 0,+ individualFailed: 0,+ held: 0+});++async function getJournalPostingDates(+ database: SyncContext["database"],+ companyId: string,+ journalIds: string[]+): Promise<Map<string, string>> {+ const postingDateByJournalId = new Map<string, string>();++ for (let i = 0; i < journalIds.length; i += JOURNAL_ID_CHUNK_SIZE) {+ const chunk = journalIds.slice(i, i + JOURNAL_ID_CHUNK_SIZE);+ if (chunk.length === 0) continue;++ const rows = await database+ .selectFrom("journal")+ .select(["id", "postingDate"])+ .where("companyId", "=", companyId)+ .where("id", "in", chunk)+ .execute();++ for (const row of rows) {+ const isoDate = toIsoDateString(row.postingDate);+ if (isoDate) postingDateByJournalId.set(row.id, isoDate);+ }+ }++ return postingDateByJournalId;+}++async function consolidateCompany(args: {+ companyId: string;+ providerId: ProviderID;+ database: SyncContext["database"];+}): Promise<ConsolidationSummary & { skippedReason?: string }> {+ const { companyId, providerId, database } = args;+ const client = getCarbonServiceRole();+ const summary = emptySummary();++ const integration = await getAccountingIntegration(+ client,+ companyId,+ providerId+ );++ // Re-check the gate inside the step: settings may have changed between+ // enumeration and execution. The cron runs for pure-daily configs+ // (transitional v2 shims) AND for any config with daily-summary source+ // types (v3 per-source-type granularity).+ const settings: PostingSyncSettings = resolvePostingSyncSettings(+ integration.metadata+ );+ if (+ settings.consolidation !== "daily" &&+ !hasDailySummarySourceTypes(settings)+ ) {+ return {+ ...summary,+ skippedReason: "posting sync has no daily-summary work"+ };+ }++ const provider = getProviderIntegration(+ client,+ companyId,+ integration.id,+ integration.metadata+ ) as XeroProvider;++ const createdBy = getSyncOperationActor(integration);+ const today = getUtcDateString();+ const now = new Date();++ // ── 1. Pre-scan claimable journalEntry operations ────────────────────────+ const prescan = await getSyncOperations(client, {+ companyId,+ integration: providerId,+ status: ["Pending", "In Flight"],+ entityType: "journalEntry",+ limit: PRESCAN_LIMIT+ });+ if (prescan.error) {+ throw new Error(`Failed to pre-scan sync operations: ${prescan.error}`);+ }++ const claimable = prescan.data.filter((operation) =>+ isClaimableConsolidationOperation(operation, now)+ );+ if (claimable.length === 0) {+ return summary;+ }++ const prescanJournalIds = [+ ...new Set(+ claimable+ .filter((operation) => !isDailyConsolidationMarker(operation.entityId))+ .map(+ (operation) =>+ parseJournalEntrySyncEntityId(operation.entityId).journalId+ )+ )+ ];+ const postingDateByJournalId = await getJournalPostingDates(+ database,+ companyId,+ prescanJournalIds+ );++ const planned = partitionConsolidationOperations({+ operations: claimable,+ postingDateByJournalId,+ today,+ integration: providerId,+ consolidatedBatchKeys: new Set()+ });++ const candidateGroups = [...planned.byGroup.values()].sort((a, b) =>+ a.batchKey.localeCompare(b.batchKey)+ );+ const hasWork =+ candidateGroups.length > 0 ||+ planned.reversals.length > 0 ||+ planned.individual.length > 0 ||+ planned.missing.length > 0 ||+ planned.markers.length > 0;++ if (!hasWork) {+ // Everything claimable is dated today or later — do not claim, so the+ // rows stay Pending instead of churning through In Flight+ summary.held = planned.held.length;+ return summary;+ }++ // ── 2. Reserve/check the batch marker per candidate group BEFORE claiming ─+ const enqueueMarker = async (+ group: Pick<+ ConsolidationGroup<SyncOperation>,+ "batchKey" | "postingDate" | "sourceType"+ >+ ) => {+ return enqueueSyncOperation(client, {+ companyId,+ integration: providerId,+ entityType: "journalEntry",+ entityId: group.batchKey,+ direction: "push-to-accounting",+ trigger: "posting",+ idempotencyKey: group.batchKey,+ createdBy,+ metadata: {+ consolidation: true,+ postingDate: group.postingDate,+ ...(group.sourceType ? { sourceType: group.sourceType } : {})+ }+ });+ };++ // Batches whose summary already went out (marker Completed): members push+ // individually instead+ const consolidatedBatchKeys = new Set<string>();+ const markersByBatchKey = new Map<string, SyncOperation>();++ for (const group of candidateGroups) {+ const marker = await enqueueMarker(group);+ if (marker.error || !marker.data) {+ throw new Error(+ `Failed to reserve consolidation marker for ${group.batchKey}: ${+ marker.error ?? "no row returned"+ }`+ );+ }+ if (marker.data.status === "Completed") {+ consolidatedBatchKeys.add(group.batchKey);+ } else {+ markersByBatchKey.set(group.batchKey, marker.data);+ }+ }++ // ── 3. Claim (include-only journalEntry) ─────────────────────────────────+ const claimedOperations: SyncOperation[] = [];+ for (let iteration = 0; iteration < MAX_CLAIM_ITERATIONS; iteration++) {+ const claimed = await claimPendingOperations(client, {+ companyId,+ integration: providerId,+ entityTypes: ["journalEntry"]+ });+ if (claimed.error) {+ throw new Error(`Failed to claim sync operations: ${claimed.error}`);+ }+ if (claimed.data.length === 0) break;+ claimedOperations.push(...claimed.data);+ }++ summary.claimed = claimedOperations.length;+ if (claimedOperations.length === 0) {+ return summary;+ }++ // Posting dates for anything the claim surfaced that the pre-scan missed+ // (operations enqueued between the two calls)+ const unresolvedJournalIds = [+ ...new Set(+ claimedOperations+ .filter((operation) => !isDailyConsolidationMarker(operation.entityId))+ .map(+ (operation) =>+ parseJournalEntrySyncEntityId(operation.entityId).journalId+ )+ .filter((journalId) => !postingDateByJournalId.has(journalId))+ )+ ];+ if (unresolvedJournalIds.length > 0) {+ const lateDates = await getJournalPostingDates(+ database,+ companyId,+ unresolvedJournalIds+ );+ for (const [journalId, date] of lateDates) {+ postingDateByJournalId.set(journalId, date);+ }+ }++ const partition = partitionConsolidationOperations({+ operations: claimedOperations,+ postingDateByJournalId,+ today,+ integration: providerId,+ consolidatedBatchKeys+ });++ summary.held = partition.held.length;+ if (partition.held.length > 0) {+ console.info(+ `[CONSOLIDATION] Holding ${partition.held.length} journal operation(s) dated ${today} or later for ${companyId}/${providerId}; they become claimable again once stale`+ );+ }++ // ── 4. Shared machinery: syncer + close-out helpers ──────────────────────+ const syncer = SyncFactory.getSyncer({+ database,+ companyId,+ provider,+ config: provider.getSyncConfig("journalEntry"),+ entityType: "journalEntry"+ }) as JournalEntrySyncer;++ const mappingService = createMappingService(database, companyId);++ /**+ * Normal-syncer path for reversals and late backdated members. Uses the+ * overridden single-entity pushToAccounting so pre-flight failures keep+ * their structured errorCode/warning/metadata (the base BATCH workflow+ * flattens them to strings).+ */+ const pushIndividually = async (operations: SyncOperation[]) => {+ for (const operation of operations) {+ const syncResult = await syncer.pushToAccounting(operation.entityId);++ if (syncResult.status === "error") {+ summary.individualFailed++;+ await failOperation(client, {+ id: operation.id,+ companyId: operation.companyId,+ ...getSyncOperationFailureRecord(operation, syncResult)+ });+ continue;+ }++ if (syncResult.status === "skipped") {+ summary.individualSkipped++;+ } else {+ summary.individualCompleted++;+ }+ await completeOperation(client, {+ id: operation.id,+ companyId: operation.companyId,+ ...(syncResult.remoteId ? { externalId: syncResult.remoteId } : {})+ });+ }+ };++ // ── 5. Journals that no longer exist ─────────────────────────────────────+ for (const operation of partition.missing) {+ summary.membersFailed++;+ await failOperation(client, {+ id: operation.id,+ companyId: operation.companyId,+ errorMessage: `Journal ${operation.entityId} not found in Carbon`+ });+ }++ // ── 6. Individual pushes: reversals + late backdated members ─────────────+ await pushIndividually(partition.reversals);+ await pushIndividually(partition.individual);++ // ── 7. One aggregated push per candidate (source type, date) group ───────+ const processedMarkerIds = new Set<string>();++ for (const group of [...partition.byGroup.values()].sort((a, b) =>+ a.batchKey.localeCompare(b.batchKey)+ )) {+ const { batchKey, postingDate: date, operations } = group;++ let marker = markersByBatchKey.get(batchKey);+ if (!marker) {+ // Group surfaced by the claim race (enqueued between pre-scan and+ // claim) — reserve its marker now+ const lateMarker = await enqueueMarker(group);+ if (lateMarker.error || !lateMarker.data) {+ console.error(+ `[CONSOLIDATION] Could not reserve marker for late batch ${batchKey}; leaving ${operations.length} operation(s) In Flight for the next run`+ );+ continue;+ }+ if (lateMarker.data.status === "Completed") {+ await pushIndividually(operations);+ continue;+ }+ marker = lateMarker.data;+ }+ processedMarkerIds.add(marker.id);++ // Fetch + gate each member exactly like the syncer's shouldSync would+ const members: Array<{+ operation: SyncOperation;+ journal: NonNullable<+ Awaited<ReturnType<JournalEntrySyncer["fetchLocal"]>>+ >;+ }> = [];++ for (const operation of operations) {+ const journal = await syncer.fetchLocal(operation.entityId);+ if (!journal) {+ summary.membersFailed++;+ await failOperation(client, {+ id: operation.id,+ companyId: operation.companyId,+ errorMessage: `Journal ${operation.entityId} not found in Carbon`+ });+ continue;+ }++ const skipReason =+ journal.status !== "Posted"+ ? `Journal must be Posted before syncing (current status: ${journal.status})`+ : getPostingSyncSourceTypeSkipReason(journal.sourceType, settings, {+ inventoryAdjustmentEntitySyncEnabled:+ provider.getSyncConfig("inventoryAdjustment")?.enabled ?? false+ });++ if (skipReason) {+ // Terminal for this attempt, same as the drain's handling of+ // shouldSync skips+ console.info(+ `[CONSOLIDATION] Skipping journal ${journal.id} for ${date}: ${skipReason}`+ );+ summary.membersSkipped++;+ await completeOperation(client, {+ id: operation.id,+ companyId: operation.companyId+ });+ continue;+ }++ // Idempotency: a journal that already has a provider mapping was+ // pushed before (e.g. while the company was in individual mode) —+ // consolidating it again would double-post+ const mapping = await mappingService.getByEntity(+ "journalEntry",+ journal.id,+ provider.id+ );+ if (mapping?.externalId) {+ summary.membersSkipped++;+ await completeOperation(client, {+ id: operation.id,+ companyId: operation.companyId,+ externalId: mapping.externalId+ });+ continue;+ }++ members.push({ operation, journal });+ }++ // The SAME pre-flight inputs the individual pushes use (cached on the+ // syncer instance across groups)+ const accountCodesById = await syncer.getAccountCodesById();+ const controlAccountIds = await syncer.getControlAccountIds();+ const lockDate = await syncer.getLockDate(settings);++ // Per-member pre-flight ejection (v3): a member that fails (unmapped+ // accounts, control-account line, unbalanced) parks on its OWN+ // operation with the structured failure, and the batch proceeds with+ // the survivors — one bad journal no longer blocks the whole day.+ const survivors: typeof members = [];+ for (const member of members) {+ const memberPreflight = runJournalEntryPreflight({+ journal: member.journal,+ accountCodesById,+ controlAccountIds,+ lockDate,+ settings+ });+ if (memberPreflight.failure) {+ summary.membersFailed++;+ await failOperation(client, {+ id: member.operation.id,+ companyId: member.operation.companyId,+ errorMessage: memberPreflight.failure.message,+ errorCode: memberPreflight.failure.errorCode,+ warning: memberPreflight.failure.warning,+ metadata: {+ ...(member.operation.metadata ?? {}),+ ...(memberPreflight.failure.metadata ?? {}),+ ejectedFromBatch: batchKey+ }+ });+ continue;+ }+ survivors.push(member);+ }+ members.length = 0;+ members.push(...survivors);++ if (members.length === 0) {+ // Nothing pushable — close the marker so the batch is settled; any+ // future backdated member pushes individually+ await completeOperation(client, {+ id: marker.id,+ companyId: marker.companyId,+ metadata: {+ ...(marker.metadata ?? {}),+ consolidation: true,+ postingDate: date,+ ...(group.sourceType ? { sourceType: group.sourceType } : {}),+ journalCount: 0+ }+ });+ summary.batchesEmpty++;+ continue;+ }++ const memberJournalIds = members.map(({ journal }) => journal.id);++ try {+ const aggregate = aggregateJournalEntriesForDate({+ batchId: batchKey,+ companyId,+ postingDate: date,+ sourceType: group.sourceType,+ journals: members.map(({ journal }) => journal)+ });++ const preflight = runJournalEntryPreflight({+ journal: aggregate.journal,+ accountCodesById,+ controlAccountIds,+ lockDate,+ settings+ });+ if (preflight.failure) {+ throw new JournalEntrySyncError(preflight.failure);+ }++ let externalId: string | undefined;++ if (aggregate.journal.lines.length > 0) {+ const payload = mapJournalEntryToManualJournal({+ journal: aggregate.journal,+ accountCodesById,+ pushDate: preflight.pushDate,+ redatedFromDate: preflight.redatedFromDate+ });+ const narration = preflight.redatedFromDate+ ? `${aggregate.narration} | original date ${preflight.redatedFromDate}`+ : aggregate.narration;++ const created = await provider.createManualJournal({+ ...payload,+ Narration: narration+ });+ externalId = created.ManualJournalID;+ summary.batchesPushed++;+ } else {+ // Net-zero day: every account cancelled out — nothing to book+ summary.batchesEmpty++;+ }++ for (const { operation } of members) {+ summary.membersCompleted++;+ await completeOperation(client, {+ id: operation.id,+ companyId: operation.companyId,+ ...(externalId ? { externalId } : {}),+ metadata: {+ ...(operation.metadata ?? {}),+ consolidatedInto: batchKey+ }+ });+ }++ // Marker completes LAST: it is the commit point re-runs dedupe on+ await completeOperation(client, {+ id: marker.id,+ companyId: marker.companyId,+ ...(externalId ? { externalId } : {}),+ metadata: {+ ...(marker.metadata ?? {}),+ consolidation: true,+ postingDate: date,+ journalIds: memberJournalIds,+ journalCount: memberJournalIds.length+ }+ });+ } catch (error) {+ if (error instanceof RatelimitError) {+ // Propagate so Inngest retries; claimed rows stay In Flight and+ // become re-claimable once stale+ throw error;+ }++ const failure =+ error instanceof JournalEntrySyncError ? error.failure : null;+ const errorMessage =+ failure?.message ??+ (error instanceof Error ? error.message : String(error));++ summary.batchesFailed++;++ // Whole-batch failure: every member records the pre-flight errorCode+ // (Warning when user-fixable) plus the full member list+ for (const { operation } of members) {+ summary.membersFailed++;+ await failOperation(client, {+ id: operation.id,+ companyId: operation.companyId,+ errorMessage,+ ...(failure+ ? { errorCode: failure.errorCode, warning: failure.warning }+ : {}),+ metadata: {+ ...(operation.metadata ?? {}),+ ...(failure?.metadata ?? {}),+ consolidationBatch: batchKey,+ memberJournalIds+ }+ });+ }++ await failOperation(client, {+ id: marker.id,+ companyId: marker.companyId,+ errorMessage: `Daily consolidation for ${date} failed: ${errorMessage}`,+ ...(failure+ ? { errorCode: failure.errorCode, warning: failure.warning }+ : {}),+ metadata: {+ ...(marker.metadata ?? {}),+ postingDate: date,+ memberJournalIds+ }+ });+ }+ }++ // ── 8. Stray markers (claimed, but their date had no members this run —+ // e.g. a user retried an old marker row). Close them: the date is+ // settled and future arrivals push individually. ──────────────────────────+ for (const operation of partition.markers) {+ if (processedMarkerIds.has(operation.id)) continue;+ await completeOperation(client, {+ id: operation.id,+ companyId: operation.companyId,+ metadata: {+ ...(operation.metadata ?? {}),+ note: "Marker closed without members by the consolidation cron"+ }+ });+ }++ return summary;+}++export const accountingConsolidationFunction = inngest.createFunction(+ { id: "accounting-consolidation", retries: 3 },+ { cron: "0 2 * * *" }, // 02:00 UTC daily+ async ({ step }) => {+ const client = getCarbonServiceRole();++ // Companies with an ACTIVE accounting integration whose posting-sync+ // settings resolve to enabled + daily consolidation+ const targets = await step.run(+ "find-daily-consolidation-targets",+ async () => {+ // Xero-only: the consolidation path calls Xero-specific provider+ // methods (createManualJournal). QBO/Rillet posting sync supports+ // "individual" mode only; widening this filter requires a+ // per-provider consolidation push.+ const integrations = await client+ .from("companyIntegration")+ .select("id, companyId, metadata")+ .eq("id", ProviderID.XERO)+ .eq("active", true);++ if (integrations.error) {+ throw new Error(+ `Failed to list accounting integrations: ${integrations.error.message}`+ );+ }++ return (integrations.data ?? [])+ .filter((row) => {+ const settings = resolvePostingSyncSettings(row.metadata);+ return (+ settings.consolidation === "daily" ||+ hasDailySummarySourceTypes(settings)+ );+ })+ .map((row) => ({ companyId: row.companyId, providerId: row.id }));+ }+ );++ if (targets.length === 0) {+ return { targets: 0, results: [] };+ }++ const results: Array<+ { companyId: string; providerId: string } & ConsolidationSummary+ > = [];++ for (const target of targets) {+ const result = await step.run(+ `consolidate-${target.companyId}-${target.providerId}`,+ async () => {+ const pool = getPostgresConnectionPool(5);+ const database = getPostgresClient(pool, PostgresDriver);+ try {+ return await consolidateCompany({+ companyId: target.companyId,+ providerId: target.providerId as ProviderID,+ database+ });+ } finally {+ await pool.end();+ }+ }+ );++ results.push({+ companyId: target.companyId,+ providerId: target.providerId,+ ...result+ });+ }++ return { targets: targets.length, results };+ }+);diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.tsnew file mode 100644index 0000000000..e63dd3a076--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts@@ -0,0 +1,436 @@+/**+ * Outbound accounting reconciliation sweep — the correctness guarantee+ * behind OUTBOUND push sync (v4 Pillar B, transport unified under the v5+ * reconciler). DB events make push sync fast; this sweep makes it correct:+ * any lost event (missing subscription, queue loss, phantom Completed)+ * becomes bounded staleness (≤ the cron interval) instead of permanent+ * loss.+ *+ * v5 (.ai/specs/2026-08-12-accounting-sync-reconciler-unification.md): the+ * sweep no longer carries its own diff rules. It converges subscriptions,+ * PAGES the candidate refs for its window (posted journals, posted+ * documents, posted payments, plus parked UNMAPPED_ACCOUNTS bills outside+ * the window), and hands every ref to the SAME `reconcileEntities` executor+ * the event path uses — one brain deciding, two callers waking it. Then it+ * drains (Xero's only periodic drain) and alerts on failures.+ *+ * The window is deliberately short (SWEEP_LOOKBACK_DAYS) — history beyond+ * it is the explicit backfill's job, never a silent mass-push.+ */+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ getPostgresClient,+ getPostgresConnectionPool+} from "@carbon/database/client";+import {+ ensureProviderSubscriptions,+ getAccountingIntegration,+ getProviderIntegration,+ PAYMENT_PUSH_PROVIDERS,+ ProviderID,+ resolvePostingSyncSettings,+ type SyncContext+} from "@carbon/ee/accounting";+import { trigger } from "@carbon/lib/trigger";+import { NotificationEvent } from "@carbon/notifications";+import { today } from "@internationalized/date";+import { PostgresDriver } from "kysely";+import { inngest } from "../../client";+import {+ drainSyncOperations,+ getSweepFloorDate,+ getSyncOperationActor,+ isJournalEntryPostingEnabled,+ MAX_REDRIVE_ATTEMPTS,+ SWEPT_BILL_STATUSES,+ SWEPT_INVOICE_STATUSES,+ SWEPT_PAYMENT_STATUSES+} from "./accounting-sync-operations";+import type { ReconcileRef } from "./reconcile";+import { type ReconcileSummary, reconcileEntities } from "./reconcile-executor";++const PAGE_SIZE = 200;+const MAX_PAGES = 25;+/** Refs per reconcileEntities call — bounds the executor's .in() lists. */+const RECONCILE_BATCH_SIZE = 200;++type SweepSummary = {+ subscriptions: { ensured: number; removed: string[] };+ scanned: {+ journals: number;+ bills: number;+ invoices: number;+ payments: number;+ parkedBills: number;+ };+ skippedReasons: string[];+ reconcile: ReconcileSummary;+ drain: {+ claimed: number;+ completed: number;+ failed: number;+ skipped: number;+ } | null;+};++type SweepContext = {+ client: ReturnType<typeof getCarbonServiceRole>;+ companyId: string;+ providerId: ProviderID;+ todayIso: string;+};++async function pageIds(args: {+ ctx: SweepContext;+ table: "journal" | "purchaseInvoice" | "salesInvoice" | "payment";+ statuses: readonly string[];+ dateColumn: string;+ floor: string;+ extraFilter?: (query: any) => any;+}): Promise<string[]> {+ const ids: string[] = [];+ let offset = 0;+ for (let page = 0; page < MAX_PAGES; page++) {+ let query = args.ctx.client+ .from(args.table)+ .select("id")+ .eq("companyId", args.ctx.companyId)+ .in("status", args.statuses as unknown as ("Posted" | "Reversed")[])+ .gte(args.dateColumn, args.floor);+ if (args.extraFilter) query = args.extraFilter(query);++ const result = await query+ .order("id", { ascending: true })+ .range(offset, offset + PAGE_SIZE - 1);++ if (result.error) {+ throw new Error(+ `Failed to page ${args.table} for sweep: ${result.error.message}`+ );+ }+ const rows = result.data ?? [];+ ids.push(...rows.map((row: { id: string }) => row.id));+ if (rows.length < PAGE_SIZE) break;+ offset += PAGE_SIZE;+ }+ return ids;+}++/**+ * Bills parked Warning UNMAPPED_ACCOUNTS are re-drive candidates even when+ * their postingDate has aged out of the sweep window — the ops ledger, not+ * the document date, is the source for these.+ */+async function parkedBillIds(ctx: SweepContext): Promise<string[]> {+ const parked = await ctx.client+ .from("accountingSyncOperation")+ .select("entityId")+ .eq("companyId", ctx.companyId)+ .eq("integration", ctx.providerId)+ .eq("entityType", "bill")+ .eq("status", "Warning")+ .eq("errorCode", "UNMAPPED_ACCOUNTS")+ .lt("attemptCount", MAX_REDRIVE_ATTEMPTS)+ .limit(PAGE_SIZE);++ if (parked.error) {+ throw new Error(+ `Failed to load parked bill operations: ${parked.error.message}`+ );+ }+ return (parked.data ?? []).map((row) => row.entityId);+}++async function sweepCompanyProvider(args: {+ companyId: string;+ providerId: ProviderID;+ database: SyncContext["database"];+ scope: string;+}): Promise<SweepSummary> {+ const { companyId, providerId, database, scope } = args;+ const client = getCarbonServiceRole();++ const integration = await getAccountingIntegration(+ client,+ companyId,+ providerId+ );+ const provider = getProviderIntegration(+ client,+ companyId,+ integration.id,+ integration.metadata+ );++ // 1. Subscription convergence — the invariant self-heal. Runs before the+ // window walk so a repaired install's next events flow normally.+ const converged = await ensureProviderSubscriptions(+ client,+ companyId,+ providerId+ );+ if (converged.removed.length > 0) {+ console.info(+ `[OUTBOUND SWEEP] ${companyId}/${providerId}: removed stale subscription(s): ${converged.removed.join(", ")}`+ );+ }++ const ctx: SweepContext = {+ client,+ companyId,+ providerId,+ todayIso: today("UTC").toString()+ };++ const settings = resolvePostingSyncSettings(integration.metadata);+ const skippedReasons: string[] = [];+ const refs: ReconcileRef[] = [];+ const scanned = {+ journals: 0,+ bills: 0,+ invoices: 0,+ payments: 0,+ parkedBills: 0+ };++ // 2. Candidate refs. Paging filters are SCOPE (which rows are worth+ // asking about); every decision belongs to the reconciler. Journal posting+ // is always-on; the entity flag is a legacy escape hatch forced on by the+ // provider configs.+ if (isJournalEntryPostingEnabled(integration.metadata)) {+ const floor = getSweepFloorDate({+ todayIso: ctx.todayIso,+ syncFromDate: settings.syncFromDate+ });+ const journalIds = await pageIds({+ ctx,+ table: "journal",+ statuses: ["Posted", "Reversed"],+ dateColumn: "postingDate",+ floor,+ extraFilter: (query) => query.is("reversalOfId", null)+ });+ scanned.journals = journalIds.length;+ refs.push(+ ...journalIds.map(+ (id): ReconcileRef => ({ entityType: "journalEntry", entityId: id })+ )+ );+ } else {+ skippedReasons.push("journals: posting sync disabled");+ }++ const billConfig = provider.getSyncConfig("bill");+ if (billConfig?.enabled && billConfig.direction !== "pull-from-accounting") {+ const floor = getSweepFloorDate({+ todayIso: ctx.todayIso,+ syncFromDate: billConfig.syncFromDate+ });+ const billIds = await pageIds({+ ctx,+ table: "purchaseInvoice",+ statuses: SWEPT_BILL_STATUSES,+ dateColumn: "postingDate",+ floor+ });+ scanned.bills = billIds.length;+ const parked = await parkedBillIds(ctx);+ scanned.parkedBills = parked.length;+ const billRefIds = new Set([...billIds, ...parked]);+ refs.push(+ ...[...billRefIds].map(+ (id): ReconcileRef => ({ entityType: "bill", entityId: id })+ )+ );+ } else {+ skippedReasons.push("bills: push disabled");+ }++ const invoiceConfig = provider.getSyncConfig("invoice");+ if (+ invoiceConfig?.enabled &&+ invoiceConfig.direction !== "pull-from-accounting"+ ) {+ const floor = getSweepFloorDate({+ todayIso: ctx.todayIso,+ syncFromDate: invoiceConfig.syncFromDate+ });+ const invoiceIds = await pageIds({+ ctx,+ table: "salesInvoice",+ statuses: SWEPT_INVOICE_STATUSES,+ dateColumn: "postingDate",+ floor+ });+ scanned.invoices = invoiceIds.length;+ refs.push(+ ...invoiceIds.map(+ (id): ReconcileRef => ({ entityType: "invoice", entityId: id })+ )+ );+ } else {+ skippedReasons.push("invoices: push disabled");+ }++ if (PAYMENT_PUSH_PROVIDERS.has(providerId)) {+ const floor = getSweepFloorDate({ todayIso: ctx.todayIso });+ const paymentIds = await pageIds({+ ctx,+ table: "payment",+ statuses: SWEPT_PAYMENT_STATUSES,+ dateColumn: "createdAt",+ floor+ });+ scanned.payments = paymentIds.length;+ refs.push(+ ...paymentIds.map(+ (id): ReconcileRef => ({ entityType: "payment", entityId: id })+ )+ );+ } else {+ skippedReasons.push("payments: provider has no outbound payment push");+ }++ // 3. Reconcile — the same executor the event path calls.+ const createdBy = getSyncOperationActor(integration);+ const reconcile: ReconcileSummary = {+ considered: 0,+ enqueued: 0,+ recordedTerminal: 0,+ redriven: 0,+ nothing: 0,+ errors: 0+ };+ for (let start = 0; start < refs.length; start += RECONCILE_BATCH_SIZE) {+ const batch = refs.slice(start, start + RECONCILE_BATCH_SIZE);+ const result = await reconcileEntities({+ client,+ database,+ companyId,+ providerId,+ integrationMetadata: integration.metadata,+ createdBy,+ scope,+ refs: batch+ });+ reconcile.considered += result.considered;+ reconcile.enqueued += result.enqueued;+ reconcile.recordedTerminal += result.recordedTerminal;+ reconcile.redriven += result.redriven;+ reconcile.nothing += result.nothing;+ reconcile.errors += result.errors;+ }++ // 4. Drain everything Pending (including what this run enqueued or+ // re-drove). For providers with no incremental pull (Xero) this is the+ // only periodic drain — UI retries stop rotting as Pending.+ const drain = await drainSyncOperations({+ client,+ database,+ companyId,+ integration: providerId,+ provider,+ integrationMetadata: integration.metadata+ });++ // 5. Alert on failures left behind by the drain (v4 Pillar F). Recipient:+ // whoever configured the integration. Never fail the sweep over a+ // notification.+ if (drain.failed > 0) {+ const recipientId = integration.updatedBy;+ if (recipientId && recipientId !== "system") {+ try {+ await trigger("notify", {+ event: NotificationEvent.IntegrationSync,+ companyId,+ documentId: providerId,+ title: "Accounting sync needs attention",+ body: `${drain.failed} sync operation(s) failed for ${providerId} — review Sync Activity`,+ recipient: { type: "user", userId: recipientId }+ });+ } catch (notifyError) {+ console.error(+ `[OUTBOUND SWEEP] ${companyId}/${providerId}: failed to send sync-failure notification`,+ notifyError+ );+ }+ }+ }++ return {+ subscriptions: {+ ensured: converged.ensured.length,+ removed: converged.removed+ },+ scanned,+ skippedReasons,+ reconcile,+ drain: {+ claimed: drain.claimed,+ completed: drain.completed,+ failed: drain.failed,+ skipped: drain.skipped+ }+ };+}++export const accountingOutboundSweepFunction = inngest.createFunction(+ { id: "accounting-outbound-sweep", retries: 2 },+ // Offset from the inbound pull sweep (*/30) so the two never contend+ // for the same company's ledger claims+ { cron: "15,45 * * * *" },+ async ({ step, runId }) => {+ const client = getCarbonServiceRole();++ const targets = await step.run("find-outbound-sweep-targets", async () => {+ const integrations = await client+ .from("companyIntegration")+ .select("id, companyId")+ .in("id", Object.values(ProviderID))+ .eq("active", true);++ if (integrations.error) {+ throw new Error(+ `Failed to list accounting integrations: ${integrations.error.message}`+ );+ }++ return (integrations.data ?? []).map((row) => ({+ companyId: row.companyId,+ providerId: row.id as ProviderID+ }));+ });++ if (targets.length === 0) {+ return { targets: 0, results: [] };+ }++ const results: Array<+ { companyId: string; providerId: ProviderID } & SweepSummary+ > = [];++ for (const target of targets) {+ const result = await step.run(+ `outbound-sweep-${target.providerId}-${target.companyId}`,+ async () => {+ const pool = getPostgresConnectionPool(5);+ const database = getPostgresClient(pool, PostgresDriver);+ try {+ return await sweepCompanyProvider({+ companyId: target.companyId,+ providerId: target.providerId,+ database,+ scope: runId+ });+ } finally {+ await pool.end();+ }+ }+ );++ results.push({ ...target, ...result });+ }++ return { targets: targets.length, results };+ }+);diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts b/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.tsnew file mode 100644index 0000000000..bf5cdb4100--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/accounting-pull-sweep.ts@@ -0,0 +1,467 @@+/**+ * Generic accounting pull sweep — the correctness guarantee behind every+ * provider's inbound sync (webhooks, where a provider supports them, are+ * only a latency optimization: deliveries can be missed, disabled after+ * repeated failures, or unreachable for firewalled self-hosted instances).+ *+ * Every 30 minutes, per company with an ACTIVE accounting integration+ * whose provider implements SupportsIncrementalPull (QBO wraps Intuit's+ * Change Data Capture; Rillet lists changed invoice payments; Xero has no+ * implementation yet and is skipped):+ *+ * 1. Resolve the cursor from `metadata.settings.pullCursor`; default = the+ * integration row's `updatedAt` (at-or-after install, so pre-connect+ * history is never pulled). Providers with a capped change feed+ * (`pullLookbackDays`) get older cursors clamped and noted.+ * 2. provider.listChanges({ since }) → normalized ProviderChange rows. The+ * provider filters internally to entities whose resolved sync config+ * allows pull.+ * 3. Dependency filter: changes carrying `dependsOnMapping` are dropped+ * (without a ledger row) when the named mapping is absent locally —+ * the ownership filter for providers whose organization is shared by+ * several Carbon instances (e.g. Rillet payments on another+ * subsidiary's invoices).+ * 4. `deleted` stubs are logged and skipped (DELETE sync is deliberately+ * unimplemented, house rule); everything else enqueues a+ * pull-from-accounting ledger operation with trigger "webhook" (the+ * established remote-change trigger) and idempotencyKey scope+ * `pull:<updatedAt>` — stable across cron retries, so re-runs absorb+ * into the same rows.+ * 5. Drain via the shared machinery (drainSyncOperations).+ * 6. Advance the cursor ONLY when every enqueue succeeded and the drain+ * returned (Celigo rule: the cursor moves over provably-covered work),+ * to max(changedSince, every updatedAt seen) — never a server time,+ * which could outrun a lagging snapshot.+ *+ * A RatelimitError (or any throw) fails the company's step before the+ * cursor write → Inngest retries → the same window is re-fetched and+ * re-absorbed. Drain failures land Failed ledger rows (visible in Sync+ * Activity, retryable there) — they do NOT hold the cursor back; the+ * ledger row is the durable record of the change.+ */+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ getPostgresClient,+ getPostgresConnectionPool+} from "@carbon/database/client";+import {+ type AccountingEntityType,+ enqueueSyncOperation,+ findPaymentCompositesByRemoteId,+ getAccountingIntegration,+ getProviderIntegration,+ type ProviderChange,+ ProviderID,+ providerSupportsIncrementalPull,+ type SyncContext+} from "@carbon/ee/accounting";+import { chunkArray } from "@carbon/utils";+import { PostgresDriver } from "kysely";+import { inngest } from "../../client";+import {+ drainSyncOperations,+ getAdvancedPullCursor,+ getPullCursorDecision,+ getPullIdempotencyScope,+ getSyncOperationActor,+ getSyncOperationIdempotencyKey,+ mergePullCursor+} from "./accounting-sync-operations";++// Supabase caps a select at 1000 rows, and a very long .in() list can exceed+// the request URL limit — chunk the dependency-mapping lookup so neither+// truncates (matches the id-chunking in accounting-reconciliation.ts).+const DEPENDENCY_MAPPING_CHUNK_SIZE = 200;++type SweepSummary = {+ changedSince: string | null;+ clamped: boolean;+ changes: number;+ deletedSkipped: number;+ dependencySkipped: number;+ enqueued: number;+ cooldownSkipped: number;+ enqueueErrors: number;+ drain: {+ claimed: number;+ completed: number;+ failed: number;+ skipped: number;+ } | null;+ cursorAdvancedTo: string | null;+ skippedReason?: string;+};++const emptySummary = (): SweepSummary => ({+ changedSince: null,+ clamped: false,+ changes: 0,+ deletedSkipped: 0,+ dependencySkipped: 0,+ enqueued: 0,+ cooldownSkipped: 0,+ enqueueErrors: 0,+ drain: null,+ cursorAdvancedTo: null+});++/**+ * Drop changes whose dependsOnMapping is absent from+ * externalIntegrationMapping. Batched per dependency entity type; a+ * lookup failure keeps the changes (the syncer's own ownership gate skips+ * them benignly) rather than silently losing them.+ */+export async function filterChangesByDependencyMapping(+ client: ReturnType<typeof getCarbonServiceRole>,+ args: {+ companyId: string;+ integration: string;+ changes: ProviderChange[];+ }+): Promise<{ kept: ProviderChange[]; dependencySkipped: number }> {+ const dependentsByType = new Map<AccountingEntityType, Set<string>>();+ for (const change of args.changes) {+ if (!change.dependsOnMapping) continue;+ const existing = dependentsByType.get(change.dependsOnMapping.entityType);+ if (existing) {+ existing.add(change.dependsOnMapping.remoteId);+ } else {+ dependentsByType.set(+ change.dependsOnMapping.entityType,+ new Set([change.dependsOnMapping.remoteId])+ );+ }+ }++ if (dependentsByType.size === 0) {+ return { kept: args.changes, dependencySkipped: 0 };+ }++ const mappedByType = new Map<AccountingEntityType, Set<string>>();+ for (const [entityType, remoteIds] of dependentsByType) {+ const found = new Set<string>();+ let lookupFailed = false;++ for (const idChunk of chunkArray(+ [...remoteIds],+ DEPENDENCY_MAPPING_CHUNK_SIZE+ )) {+ const result = await client+ .from("externalIntegrationMapping")+ .select("externalId")+ .eq("companyId", args.companyId)+ .eq("integration", args.integration)+ .eq("entityType", entityType)+ .in("externalId", idChunk);++ if (result.error) {+ console.error(+ `[PULL SWEEP] ${args.companyId}/${args.integration}: dependency mapping lookup failed for ${entityType} (${result.error.message}); keeping ${remoteIds.size} change(s) for the syncer's ownership gate`+ );+ lookupFailed = true;+ break;+ }++ for (const row of result.data ?? []) {+ if (row.externalId) found.add(row.externalId);+ }+ }++ // On any chunk failure, fail safe: keep every dependency as present so the+ // change survives to the syncer's ownership gate (matches the pre-chunk path).+ mappedByType.set(entityType, lookupFailed ? remoteIds : found);+ }++ const kept: ProviderChange[] = [];+ let dependencySkipped = 0;+ for (const change of args.changes) {+ if (+ change.dependsOnMapping &&+ !mappedByType+ .get(change.dependsOnMapping.entityType)+ ?.has(change.dependsOnMapping.remoteId)+ ) {+ dependencySkipped++;+ continue;+ }+ kept.push(change);+ }++ return { kept, dependencySkipped };+}++async function sweepCompanyProvider(args: {+ companyId: string;+ providerId: ProviderID;+ database: SyncContext["database"];+}): Promise<SweepSummary> {+ const { companyId, providerId, database } = args;+ const client = getCarbonServiceRole();+ const summary = emptySummary();++ const integration = await getAccountingIntegration(+ client,+ companyId,+ providerId+ );++ const provider = getProviderIntegration(+ client,+ companyId,+ integration.id,+ integration.metadata+ );++ if (!providerSupportsIncrementalPull(provider)) {+ return { ...summary, skippedReason: "provider has no incremental pull" };+ }++ const cursorDecision = getPullCursorDecision({+ integrationMetadata: integration.metadata,+ integrationUpdatedAt: integration.updatedAt ?? null,+ maxLookbackDays: provider.pullLookbackDays+ });+ summary.changedSince = cursorDecision.changedSince;+ summary.clamped = cursorDecision.clamped;+ if (cursorDecision.clamped) {+ console.warn(+ `[PULL SWEEP] ${companyId}/${providerId}: cursor predates the ${provider.pullLookbackDays}-day change-feed window; clamped to ${cursorDecision.changedSince} — changes before the window are recovered by two-way owner semantics or a backfill`+ );+ }++ const listed = await provider.listChanges({+ since: cursorDecision.changedSince+ });+ summary.changes = listed.changes.length;++ const { kept, dependencySkipped } = await filterChangesByDependencyMapping(+ client,+ { companyId, integration: providerId, changes: listed.changes }+ );+ summary.dependencySkipped = dependencySkipped;++ const createdBy = getSyncOperationActor(integration);+ const updatedAts: Array<string | null> = listed.changes.map(+ (change) => change.updatedAt+ );++ // Enqueue one pull-from-accounting ledger operation, folding the result into+ // the summary. Shared by the normal change path and the deleted-payment+ // tombstone path (which fans out over resolved composite ids).+ const enqueueChange = async (+ entityType: AccountingEntityType,+ entityId: string,+ updatedAt: string | null+ ): Promise<void> => {+ const enqueued = await enqueueSyncOperation(client, {+ companyId,+ integration: providerId,+ entityType,+ entityId,+ direction: "pull-from-accounting",+ trigger: "webhook",+ idempotencyKey: getSyncOperationIdempotencyKey({+ entityType,+ entityId,+ direction: "pull-from-accounting",+ scope: getPullIdempotencyScope(updatedAt, cursorDecision.changedSince)+ }),+ createdBy+ });++ if (enqueued.error) {+ summary.enqueueErrors++;+ console.error(+ `[PULL SWEEP] ${companyId}/${providerId}: failed to enqueue ${entityType} ${entityId}: ${enqueued.error}`+ );+ } else if (enqueued.data) {+ summary.enqueued++;+ } else {+ summary.cooldownSkipped++;+ }+ };++ for (const change of kept) {+ if (change.deleted) {+ // A deleted `payment` tombstone still needs to VOID the Carbon payment:+ // resolve the composite(s) from the existing mapping (the tombstone+ // carries only the bare payment id) and enqueue the reversing pull — the+ // payment syncer maps the not-found refetch to status "void". Every other+ // deletion follows the house rule (DELETE sync unimplemented — log+skip).+ if (change.entityType === "payment") {+ const composites = await findPaymentCompositesByRemoteId(client, {+ companyId,+ integration: providerId,+ paymentRemoteId: change.remoteId+ });+ if (composites.length === 0) {+ summary.deletedSkipped++;+ console.info(+ `[PULL SWEEP] ${companyId}/${providerId}: deleted payment ${change.remoteId} has no local mapping — skipping (never synced or not ours)`+ );+ continue;+ }+ for (const composite of composites) {+ await enqueueChange("payment", composite, change.updatedAt);+ }+ continue;+ }++ summary.deletedSkipped++;+ console.info(+ `[PULL SWEEP] ${companyId}/${providerId}: skipping deleted ${change.entityType} ${change.remoteId} (remote deletions are not synced)`+ );+ continue;+ }++ await enqueueChange(change.entityType, change.remoteId, change.updatedAt);+ }++ // Drain through the shared machinery (a RatelimitError propagates so the+ // step retries; claimed rows stay In Flight and become re-claimable once+ // stale)+ const drain = await drainSyncOperations({+ client,+ database,+ companyId,+ integration: providerId,+ provider,+ integrationMetadata: integration.metadata+ });+ summary.drain = {+ claimed: drain.claimed,+ completed: drain.completed,+ failed: drain.failed,+ skipped: drain.skipped+ };++ // Celigo cursor rule: advance only over provably-covered work — every+ // change either enqueued into the ledger (drain failures are durable+ // Failed rows with UI retry, so they do not hold the cursor back) or was+ // terminally logged-and-skipped (deletions, absent dependency mappings).+ if (summary.enqueueErrors > 0) {+ console.warn(+ `[PULL SWEEP] ${companyId}/${providerId}: ${summary.enqueueErrors} enqueue error(s); holding the cursor at ${cursorDecision.changedSince} so the next run re-fetches the window`+ );+ return summary;+ }++ const nextCursor = getAdvancedPullCursor({+ changedSince: cursorDecision.changedSince,+ lastUpdatedTimes: updatedAts+ });++ // Skip the no-op write when an unclamped stored cursor saw no newer+ // changes; clamps and first runs persist so the default/clamp becomes+ // the durable cursor+ const shouldStore =+ nextCursor !== cursorDecision.changedSince ||+ cursorDecision.clamped ||+ cursorDecision.source !== "cursor";++ if (shouldStore) {+ await storePullCursor(client, {+ companyId,+ providerId,+ cursor: nextCursor+ });+ summary.cursorAdvancedTo = nextCursor;+ }++ return summary;+}++/**+ * Read-modify-write against the RAW stored metadata (not the zod-parsed+ * copy from getAccountingIntegration) so no sibling key can be clobbered —+ * same contract as the reconciliation report store.+ */+async function storePullCursor(+ client: ReturnType<typeof getCarbonServiceRole>,+ args: { companyId: string; providerId: ProviderID; cursor: string }+): Promise<void> {+ const current = await client+ .from("companyIntegration")+ .select("metadata")+ .eq("id", args.providerId)+ .eq("companyId", args.companyId)+ .single();++ if (current.error) {+ throw new Error(+ `Failed to read integration metadata: ${current.error.message}`+ );+ }++ const merged = mergePullCursor(current.data?.metadata, args.cursor);++ const updated = await client+ .from("companyIntegration")+ .update({ metadata: merged as any })+ .eq("id", args.providerId)+ .eq("companyId", args.companyId);++ if (updated.error) {+ throw new Error(`Failed to store pull cursor: ${updated.error.message}`);+ }+}++export const accountingPullSweepFunction = inngest.createFunction(+ { id: "accounting-pull-sweep", retries: 2 },+ { cron: "*/30 * * * *" }, // every 30 minutes+ async ({ step }) => {+ const client = getCarbonServiceRole();++ // Every ACTIVE accounting integration; providers without an+ // incremental pull skip cheaply inside their step+ const targets = await step.run("find-pull-sweep-targets", async () => {+ const integrations = await client+ .from("companyIntegration")+ .select("id, companyId")+ .in("id", Object.values(ProviderID))+ .eq("active", true);++ if (integrations.error) {+ throw new Error(+ `Failed to list accounting integrations: ${integrations.error.message}`+ );+ }++ return (integrations.data ?? []).map((row) => ({+ companyId: row.companyId,+ providerId: row.id as ProviderID+ }));+ });++ if (targets.length === 0) {+ return { targets: 0, results: [] };+ }++ const results: Array<+ { companyId: string; providerId: ProviderID } & SweepSummary+ > = [];++ for (const target of targets) {+ const result = await step.run(+ `sweep-${target.providerId}-${target.companyId}`,+ async () => {+ // getPostgresConnectionPool returns a process-lifetime singleton+ // (cached, shared with any other caller requesting the same size) —+ // never end it here, or a concurrent invocation queries an ended pool+ // (matches events/sync.ts).+ const pool = getPostgresConnectionPool(5);+ const database = getPostgresClient(pool, PostgresDriver);+ return await sweepCompanyProvider({+ companyId: target.companyId,+ providerId: target.providerId,+ database+ });+ }+ );++ results.push({ ...target, ...result });+ }++ return { targets: targets.length, results };+ }+);diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.test.ts b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.test.tsnew file mode 100644index 0000000000..51917eb669--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.test.ts@@ -0,0 +1,338 @@+// Unit tests for the reconciliation cron's tie-out helpers. The helpers+// live in accounting-sync-operations.ts (the import-light module — no+// Inngest client, no @carbon/auth) exactly like the sweep and+// consolidation decisions, so this file stays runnable without booting+// either.+import { describe, expect, it } from "vitest";+import {+ buildRemoteAccountRefIndex,+ computeTieOutDeltas,+ DOC_BACKED_ERROR_CODE,+ findAccountingPeriodForDate,+ foldTieOutBuckets,+ getBackingDocumentEntityType,+ getLatestOperationsByEntityId,+ getOperationTieOutBucket,+ getTieOutScopeStart,+ isBackingDocumentDelivered,+ TIE_OUT_BUCKETS_LEAST_DELIVERED_FIRST,+ TIE_OUT_DEFAULT_LOOKBACK_DAYS,+ type TieOutBucket+} from "./accounting-sync-operations";++// ── Disposition → bucket ────────────────────────────────────────────────────++describe("getOperationTieOutBucket", () => {+ const bucketOf = (+ status: string,+ errorCode: string | null = null,+ docBackedDelivered = false+ ) =>+ getOperationTieOutBucket(+ { status: status as any, errorCode },+ { docBackedDelivered }+ );++ it("maps Completed to synced", () => {+ expect(bucketOf("Completed")).toBe("synced");+ });++ it("maps Excluded/DOC_BACKED to docBacked only while the backing document is delivered", () => {+ expect(bucketOf("Excluded", DOC_BACKED_ERROR_CODE, true)).toBe("docBacked");+ // an undelivered doc-backed journal has NOT reached the external GL —+ // it is pending, never silently "accounted for" (spec §5)+ expect(bucketOf("Excluded", DOC_BACKED_ERROR_CODE, false)).toBe("pending");+ });++ it("maps other Excluded reasons to excluded", () => {+ expect(bucketOf("Excluded", "FAMILY_OFF")).toBe("excluded");+ expect(bucketOf("Excluded", "SOURCE_TYPE_DISABLED")).toBe("excluded");+ expect(bucketOf("Excluded", null)).toBe("excluded");+ });++ it("maps Pending and In Flight to pending", () => {+ expect(bucketOf("Pending")).toBe("pending");+ expect(bucketOf("In Flight")).toBe("pending");+ });++ it("maps Failed, Warning and Skipped to blocked", () => {+ expect(bucketOf("Failed")).toBe("blocked");+ expect(bucketOf("Warning", "UNMAPPED_ACCOUNTS")).toBe("blocked");+ expect(bucketOf("Skipped")).toBe("blocked");+ });+});++describe("foldTieOutBuckets", () => {+ it("returns pending for a journal with no operations", () => {+ expect(foldTieOutBuckets([])).toBe("pending");+ });++ it("picks the least-delivered bucket when a journal has a normal and a :reversal op", () => {+ expect(foldTieOutBuckets(["synced", "pending"])).toBe("pending");+ expect(foldTieOutBuckets(["docBacked", "blocked"])).toBe("blocked");+ expect(foldTieOutBuckets(["excluded", "synced"])).toBe("excluded");+ expect(foldTieOutBuckets(["synced", "synced"])).toBe("synced");+ });++ it("orders delivery exactly blocked > pending > excluded > docBacked > synced", () => {+ expect(TIE_OUT_BUCKETS_LEAST_DELIVERED_FIRST).toEqual([+ "blocked",+ "pending",+ "excluded",+ "docBacked",+ "synced"+ ]);+ // folding the full list from any order lands on blocked+ const shuffled: TieOutBucket[] = [+ "synced",+ "docBacked",+ "blocked",+ "excluded",+ "pending"+ ];+ expect(foldTieOutBuckets(shuffled)).toBe("blocked");+ });+});++// ── Latest-row-per-entity fold ──────────────────────────────────────────────++describe("getLatestOperationsByEntityId", () => {+ it("keeps the newest row per entityId by createdAt", () => {+ const latest = getLatestOperationsByEntityId([+ { entityId: "j1", createdAt: "2026-08-01T00:00:00Z", status: "Failed" },+ {+ entityId: "j1",+ createdAt: "2026-08-05T00:00:00Z",+ status: "Completed"+ },+ { entityId: "j2", createdAt: "2026-08-02T00:00:00Z", status: "Pending" }+ ] as any[]);++ expect(latest.size).toBe(2);+ expect((latest.get("j1") as any).status).toBe("Completed");+ expect((latest.get("j2") as any).status).toBe("Pending");+ });++ it("is insensitive to input order", () => {+ const latest = getLatestOperationsByEntityId([+ { entityId: "j1", createdAt: "2026-08-05T00:00:00Z", status: "Excluded" },+ { entityId: "j1", createdAt: "2026-08-01T00:00:00Z", status: "Failed" }+ ] as any[]);++ expect((latest.get("j1") as any).status).toBe("Excluded");+ });+});++// ── Period resolution + scope ───────────────────────────────────────────────++describe("findAccountingPeriodForDate", () => {+ const periods = [+ { id: "p-jul", startDate: "2026-07-01", endDate: "2026-07-31" },+ { id: "p-aug", startDate: "2026-08-01", endDate: "2026-08-31" }+ ];++ it("finds the period containing the date, boundaries inclusive", () => {+ expect(findAccountingPeriodForDate(periods, "2026-07-15")?.id).toBe(+ "p-jul"+ );+ expect(findAccountingPeriodForDate(periods, "2026-08-01")?.id).toBe(+ "p-aug"+ );+ expect(findAccountingPeriodForDate(periods, "2026-08-31")?.id).toBe(+ "p-aug"+ );+ });++ it("returns null for a date outside every period or a null date", () => {+ expect(findAccountingPeriodForDate(periods, "2026-06-30")).toBeNull();+ expect(findAccountingPeriodForDate(periods, null)).toBeNull();+ });++ it("slices timestamps down to the calendar day", () => {+ expect(+ findAccountingPeriodForDate(periods, "2026-07-15T10:30:00Z")?.id+ ).toBe("p-jul");+ });+});++describe("getTieOutScopeStart", () => {+ it("uses the posting-sync syncFromDate when set (sliced to a date)", () => {+ expect(+ getTieOutScopeStart({+ todayIso: "2026-08-11",+ syncFromDate: "2026-01-15T00:00:00Z"+ })+ ).toBe("2026-01-15");+ });++ it("falls back to the default lookback window", () => {+ expect(TIE_OUT_DEFAULT_LOOKBACK_DAYS).toBe(90);+ expect(getTieOutScopeStart({ todayIso: "2026-08-11" })).toBe("2026-05-13");+ expect(+ getTieOutScopeStart({ todayIso: "2026-08-11", syncFromDate: null })+ ).toBe("2026-05-13");+ });+});++// ── DOC_BACKED delivery ─────────────────────────────────────────────────────++describe("getBackingDocumentEntityType", () => {+ it("reads metadata.backingDocument.entityType", () => {+ expect(+ getBackingDocumentEntityType({ backingDocument: { entityType: "bill" } })+ ).toBe("bill");+ });++ it("returns null for missing or malformed metadata", () => {+ expect(getBackingDocumentEntityType(null)).toBeNull();+ expect(getBackingDocumentEntityType({})).toBeNull();+ expect(+ getBackingDocumentEntityType({ backingDocument: "bill" })+ ).toBeNull();+ expect(+ getBackingDocumentEntityType({ backingDocument: { entityType: 42 } })+ ).toBeNull();+ });+});++describe("isBackingDocumentDelivered", () => {+ it("delivered when the document's own op is Completed", () => {+ expect(+ isBackingDocumentDelivered({+ latestOperationStatus: "Completed",+ hasExternalMapping: false+ })+ ).toBe(true);+ });++ it("delivered when the document carries an external mapping", () => {+ expect(+ isBackingDocumentDelivered({+ latestOperationStatus: null,+ hasExternalMapping: true+ })+ ).toBe(true);+ });++ it("NOT delivered when the op is non-Completed and no mapping exists", () => {+ for (const status of [null, "Pending", "Failed", "Warning", "Skipped"]) {+ expect(+ isBackingDocumentDelivered({+ latestOperationStatus: status,+ hasExternalMapping: false+ })+ ).toBe(false);+ }+ });+});++// ── Remote-ref → Carbon account index ───────────────────────────────────────++describe("buildRemoteAccountRefIndex", () => {+ it("indexes both the externalId and the metadata externalCode", () => {+ const index = buildRemoteAccountRefIndex([+ {+ entityId: "acc_1",+ externalId: "xero-uuid-1",+ metadata: { externalCode: "1200", externalName: "Inventory" }+ }+ ]);++ // QBO addresses by provider account id; Xero/Rillet by code+ expect(index.get("xero-uuid-1")).toBe("acc_1");+ expect(index.get("1200")).toBe("acc_1");+ });++ it("skips null refs and tolerates non-object metadata", () => {+ const index = buildRemoteAccountRefIndex([+ { entityId: "acc_1", externalId: null, metadata: null },+ { entityId: "acc_2", externalId: "77", metadata: "junk" },+ { entityId: "acc_3", externalId: "88", metadata: ["not", "a", "record"] }+ ]);++ expect(index.size).toBe(2);+ expect(index.get("77")).toBe("acc_2");+ expect(index.get("88")).toBe("acc_3");+ });++ it("first mapping wins on a shared ref (many-to-one consolidation)", () => {+ const index = buildRemoteAccountRefIndex([+ { entityId: "acc_1", externalId: "shared", metadata: null },+ { entityId: "acc_2", externalId: "shared", metadata: null }+ ]);++ expect(index.get("shared")).toBe("acc_1");+ });+});++// ── Delta math ──────────────────────────────────────────────────────────────++describe("computeTieOutDeltas", () => {+ it("is zero-delta when every posted cent is accounted for and matches the provider", () => {+ const { internalDeltaCents, externalDeltaCents } = computeTieOutDeltas({+ carbonPostedCents: 100_00,+ syncedCents: 40_00,+ docBackedCents: 30_00,+ excludedCents: 10_00,+ pendingCents: 15_00,+ blockedCents: 5_00,+ providerCents: 40_00+ });++ expect(internalDeltaCents).toBe(0);+ expect(externalDeltaCents).toBe(0);+ });++ it("surfaces internal drift: posted amounts no disposition covers", () => {+ const { internalDeltaCents } = computeTieOutDeltas({+ carbonPostedCents: 100_00,+ syncedCents: 90_00,+ docBackedCents: 0,+ excludedCents: 0,+ pendingCents: 0,+ blockedCents: 0,+ providerCents: null+ });++ expect(internalDeltaCents).toBe(10_00);+ });++ it("surfaces external drift as synced − provider, and NULLs it without a fetch", () => {+ const drifted = computeTieOutDeltas({+ carbonPostedCents: 50_00,+ syncedCents: 50_00,+ docBackedCents: 0,+ excludedCents: 0,+ pendingCents: 0,+ blockedCents: 0,+ providerCents: 45_00+ });+ expect(drifted.externalDeltaCents).toBe(5_00);++ const unfetched = computeTieOutDeltas({+ carbonPostedCents: 50_00,+ syncedCents: 50_00,+ docBackedCents: 0,+ excludedCents: 0,+ pendingCents: 0,+ blockedCents: 0,+ providerCents: null+ });+ expect(unfetched.externalDeltaCents).toBeNull();+ });++ it("handles net-credit (negative debit-signed) cells", () => {+ const { internalDeltaCents, externalDeltaCents } = computeTieOutDeltas({+ carbonPostedCents: -25_00,+ syncedCents: -25_00,+ docBackedCents: 0,+ excludedCents: 0,+ pendingCents: 0,+ blockedCents: 0,+ providerCents: -25_00+ });++ expect(internalDeltaCents).toBe(0);+ expect(externalDeltaCents).toBe(0);+ });+});diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.tsnew file mode 100644index 0000000000..caae5f7afe--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts@@ -0,0 +1,1031 @@+/**+ * Weekly reconciliation cron (posting sync, v3 spec §5 / v4 Pillar E) —+ * presence drift detection plus the per-period × per-account tie-out.+ *+ * Every Monday 03:00 UTC, per active accounting connection (any provider)+ * with posting sync enabled:+ *+ * (a) PRESENCE — page the last 90 days of Completed journalEntry+ * operations (via getSyncOperations, newest first) and verify each+ * distinct externalId still exists remotely via the provider-agnostic+ * fetchRemoteJournalTotals (Xero manual journals, QBO journal entries,+ * Rillet journal entries). Missing, voided or deleted provider+ * journals produce `{ type: "missing", externalId, journalId, amount? }`+ * drift entries, stored at+ * `companyIntegration.metadata.settings.postingSync.lastReconciliation`+ * as `{ runAt, drift }` (the SyncActivity banner's feed). Fetches are+ * paced (batches of 50, ~1s pause) against provider rate limits and+ * capped at 250 ids per run (newest first, logged when truncated).+ *+ * (b) TIE-OUT — for accounting periods overlapping+ * [postingSync.syncFromDate ?? 90 days back, today], compute one+ * "accountingSyncTieOut" row per (period × account):+ *+ * - carbonPostedAmount: net debit-signed journalLine sums of every+ * Posted/Reversed journal whose postingDate falls in the period+ * (signs via toDebitSignedAmount on the account's class);+ * - synced/docBacked/excluded/pending/blocked: the same line sums+ * split by each journal's sync disposition (its ledger operations,+ * normal + :reversal; least-delivered bucket wins; DOC_BACKED only+ * counts delivered while the backing document really synced);+ * - providerAmount: the remote journals' debit-signed per-account+ * sums, reusing the presence check's fetches (never fetched twice)+ * and mapped back to Carbon accounts via the account-mapping rows;+ * NULL for cells no successful fetch covered;+ * - internalDelta = carbonPosted − (synced+docBacked+excluded++ * pending+blocked); externalDelta = synced − provider.+ *+ * Rows upsert on the (companyId, integration, accountingPeriodId,+ * accountId) cell via the service role — the table has no write RLS.+ */+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ getPostgresClient,+ getPostgresConnectionPool+} from "@carbon/database/client";+import {+ fetchRemoteJournalTotals,+ getAccountingIntegration,+ getJournalEntrySyncEntityId,+ getProviderIntegration,+ getSyncOperations,+ ProviderID,+ parseJournalEntrySyncEntityId,+ RatelimitError,+ type RemoteJournalTotals,+ resolvePostingSyncSettings,+ type SyncContext,+ type SyncOperation,+ toDebitSignedAmount,+ toPostingDateString+} from "@carbon/ee/accounting";+import { PostgresDriver } from "kysely";+import { inngest } from "../../client";+import {+ buildRemoteAccountRefIndex,+ computeTieOutDeltas,+ DOC_BACKED_ERROR_CODE,+ findAccountingPeriodForDate,+ foldTieOutBuckets,+ getBackingDocumentEntityType,+ getLatestOperationsByEntityId,+ getNettedPositiveCents,+ getOperationTieOutBucket,+ getPositiveCents,+ getSyncOperationActor,+ getTieOutScopeStart,+ getUtcDateString,+ isBackingDocumentDelivered,+ isDailyConsolidationMarker,+ mergePostingSyncReconciliation,+ type ReconciliationDriftEntry,+ type ReconciliationReport,+ type TieOutBucket,+ type TieOutCellCents,+ type TieOutPeriod,+ toIsoDateString+} from "./accounting-sync-operations";++export const RECONCILIATION_WINDOW_DAYS = 90;++/** Distinct provider journals verified per run (newest first). */+const MAX_PRESENCE_CHECKS = 250;+/** Pause between presence-check batches (Xero allows 60 calls/min). */+const PRESENCE_BATCH_SIZE = 50;+const PRESENCE_BATCH_PAUSE_MS = 1_100;++const OPERATIONS_PAGE_SIZE = 100;+const MAX_OPERATION_PAGES = 50;+/**+ * Paging is ordered by createdAt but the window filters on completedAt; an+ * operation can complete long after it was created (retries), so paging+ * only stops once rows are 30 days older than the window.+ */+const PAGING_SLACK_DAYS = 30;++const JOURNAL_ID_CHUNK_SIZE = 300;++/** Tie-out scan bounds: pages of posted journals, capped per run. */+const TIE_OUT_JOURNAL_PAGE_SIZE = 500;+const MAX_TIE_OUT_JOURNAL_PAGES = 40;+const TIE_OUT_ENTITY_ID_CHUNK_SIZE = 200;+const TIE_OUT_UPSERT_CHUNK_SIZE = 200;++type ReconciliationSummary = {+ operations: number;+ externalIds: number;+ checkedExternalIds: number;+ missing: number;+ tieOutCells: number;+ truncated: boolean;+ skippedReason?: string;+};++type CarbonJournalData = {+ postingDate: string | null;+ lines: Array<{ accountId: string | null; amount: number }>;+};++// Same Json-vs-Record cast rationale as core/operations.ts+// syncOperationTable: the generated types either don't carry the table yet+// (accountingSyncTieOut, migration pending) or trade the cast for metadata+// typing friction. Row payloads are typed locally.+function syncOperationTable(+ client: ReturnType<typeof getCarbonServiceRole>+): any {+ return client.from("accountingSyncOperation" as any);+}++function tieOutTable(client: ReturnType<typeof getCarbonServiceRole>): any {+ return client.from("accountingSyncTieOut" as any);+}++async function getCarbonJournalData(+ database: SyncContext["database"],+ companyId: string,+ journalIds: string[]+): Promise<Map<string, CarbonJournalData>> {+ const byJournalId = new Map<string, CarbonJournalData>();++ for (let i = 0; i < journalIds.length; i += JOURNAL_ID_CHUNK_SIZE) {+ const chunk = journalIds.slice(i, i + JOURNAL_ID_CHUNK_SIZE);+ if (chunk.length === 0) continue;++ const journals = await database+ .selectFrom("journal")+ .select(["id", "postingDate"])+ .where("companyId", "=", companyId)+ .where("id", "in", chunk)+ .execute();++ for (const journal of journals) {+ byJournalId.set(journal.id, {+ postingDate: toIsoDateString(journal.postingDate),+ lines: []+ });+ }++ const lines = await database+ .selectFrom("journalLine")+ .select(["journalId", "accountId", "amount"])+ .where("companyId", "=", companyId)+ .where("journalId", "in", chunk)+ .execute();++ for (const line of lines) {+ if (!line.journalId) continue;+ byJournalId.get(line.journalId)?.lines.push({+ accountId: line.accountId ?? null,+ amount: Number(line.amount) || 0+ });+ }+ }++ return byJournalId;+}++/**+ * Page the last window of Completed journalEntry push operations that carry+ * an externalId, newest first.+ */+async function getCompletedJournalOperations(+ client: ReturnType<typeof getCarbonServiceRole>,+ args: { companyId: string; integration: string; windowStart: Date }+): Promise<SyncOperation[]> {+ const collected: SyncOperation[] = [];+ const stopBefore = new Date(+ args.windowStart.getTime() - PAGING_SLACK_DAYS * 24 * 60 * 60 * 1000+ ).toISOString();+ const windowStartIso = args.windowStart.toISOString();++ for (let page = 0; page < MAX_OPERATION_PAGES; page++) {+ const result = await getSyncOperations(client, {+ companyId: args.companyId,+ integration: args.integration,+ status: "Completed",+ entityType: "journalEntry",+ limit: OPERATIONS_PAGE_SIZE,+ offset: page * OPERATIONS_PAGE_SIZE+ });++ if (result.error) {+ throw new Error(`Failed to page sync operations: ${result.error}`);+ }+ if (result.data.length === 0) break;++ for (const operation of result.data) {+ if (operation.direction !== "push-to-accounting") continue;+ if (!operation.externalId) continue;+ if (!operation.completedAt || operation.completedAt < windowStartIso) {+ continue;+ }+ collected.push(operation);+ }++ const pastWindow = result.data.every(+ (operation) => operation.createdAt < stopBefore+ );+ if (pastWindow || result.data.length < OPERATIONS_PAGE_SIZE) break;+ }++ return collected;+}++/**+ * All journalEntry push operations (any status) for the given sync entity+ * ids — the disposition source for the tie-out buckets.+ */+async function getJournalDispositionOperations(+ client: ReturnType<typeof getCarbonServiceRole>,+ args: { companyId: string; integration: string; entityIds: string[] }+): Promise<SyncOperation[]> {+ const collected: SyncOperation[] = [];++ for (+ let i = 0;+ i < args.entityIds.length;+ i += TIE_OUT_ENTITY_ID_CHUNK_SIZE+ ) {+ const chunk = args.entityIds.slice(i, i + TIE_OUT_ENTITY_ID_CHUNK_SIZE);+ if (chunk.length === 0) continue;++ const result = await syncOperationTable(client)+ .select("*")+ .eq("companyId", args.companyId)+ .eq("integration", args.integration)+ .eq("entityType", "journalEntry")+ .eq("direction", "push-to-accounting")+ .in("entityId", chunk);++ if (result.error) {+ throw new Error(+ `Failed to load journal sync operations: ${result.error.message}`+ );+ }+ collected.push(...((result.data ?? []) as SyncOperation[]));+ }++ return collected;+}++/**+ * Delivery state per backing document (`entityType:entityId` → delivered):+ * delivered when the document's own latest push operation is Completed OR+ * the document already carries an external mapping.+ */+async function getBackingDocumentDelivery(+ client: ReturnType<typeof getCarbonServiceRole>,+ database: SyncContext["database"],+ args: {+ companyId: string;+ integration: string;+ docs: Array<{ entityType: string; entityId: string }>;+ }+): Promise<Map<string, boolean>> {+ const idsByType = new Map<string, Set<string>>();+ for (const doc of args.docs) {+ const ids = idsByType.get(doc.entityType) ?? new Set<string>();+ ids.add(doc.entityId);+ idsByType.set(doc.entityType, ids);+ }++ const delivered = new Map<string, boolean>();++ for (const [entityType, idSet] of idsByType) {+ const ids = [...idSet];++ const operations: SyncOperation[] = [];+ for (let i = 0; i < ids.length; i += TIE_OUT_ENTITY_ID_CHUNK_SIZE) {+ const chunk = ids.slice(i, i + TIE_OUT_ENTITY_ID_CHUNK_SIZE);+ const result = await syncOperationTable(client)+ .select("*")+ .eq("companyId", args.companyId)+ .eq("integration", args.integration)+ .eq("entityType", entityType)+ .eq("direction", "push-to-accounting")+ .in("entityId", chunk);++ if (result.error) {+ throw new Error(+ `Failed to load ${entityType} sync operations: ${result.error.message}`+ );+ }+ operations.push(...((result.data ?? []) as SyncOperation[]));+ }+ const latestById = getLatestOperationsByEntityId(operations);++ const mappedIds = new Set<string>();+ for (let i = 0; i < ids.length; i += TIE_OUT_ENTITY_ID_CHUNK_SIZE) {+ const chunk = ids.slice(i, i + TIE_OUT_ENTITY_ID_CHUNK_SIZE);+ const rows = await database+ .selectFrom("externalIntegrationMapping")+ .select(["entityId"])+ .where("companyId", "=", args.companyId)+ .where("integration", "=", args.integration)+ .where("entityType", "=", entityType)+ .where("entityId", "in", chunk)+ .where("externalId", "is not", null)+ .execute();+ for (const row of rows) mappedIds.add(row.entityId);+ }++ for (const id of ids) {+ delivered.set(+ `${entityType}:${id}`,+ isBackingDocumentDelivered({+ latestOperationStatus: latestById.get(id)?.status ?? null,+ hasExternalMapping: mappedIds.has(id)+ })+ );+ }+ }++ return delivered;+}++type TieOutJournal = {+ id: string;+ postingDate: string | null;+ reversalOfId: string | null;+ lines: Array<{+ accountId: string | null;+ amount: number;+ documentId: string | null;+ }>;+};++/**+ * Compute and upsert the tie-out cells for one company + provider.+ * Returns the number of cells written. Makes NO provider calls — the+ * external side reuses the presence check's fetches.+ */+async function computeTieOutForCompany(args: {+ client: ReturnType<typeof getCarbonServiceRole>;+ database: SyncContext["database"];+ companyId: string;+ providerId: ProviderID;+ syncFromDate: string | null;+ createdBy: string;+ operationsByExternalId: Map<string, SyncOperation[]>;+ carbonJournals: Map<string, CarbonJournalData>;+ fetchedByExternalId: Map<string, RemoteJournalTotals | null>;+}): Promise<number> {+ const { client, database, companyId, providerId } = args;++ const todayIso = getUtcDateString();+ const scopeStart = getTieOutScopeStart({+ todayIso,+ syncFromDate: args.syncFromDate+ });++ const periodRows = await database+ .selectFrom("accountingPeriod")+ .select(["id", "startDate", "endDate"])+ .where("companyId", "=", companyId)+ .where("startDate", "<=", todayIso)+ .where("endDate", ">=", scopeStart)+ .orderBy("startDate", "asc")+ .execute();++ const periods: TieOutPeriod[] = periodRows.map((row) => ({+ id: row.id,+ startDate: toPostingDateString(row.startDate),+ endDate: toPostingDateString(row.endDate)+ }));+ if (periods.length === 0) return 0;++ const minStart = periods[0]?.startDate ?? scopeStart;+ let maxEnd = periods[0]?.endDate ?? todayIso;+ for (const period of periods) {+ if (period.endDate > maxEnd) maxEnd = period.endDate;+ }++ // ── Posted journals in scope, with lines + account classes ───────────────+ const journals: TieOutJournal[] = [];+ const journalsById = new Map<string, TieOutJournal>();++ for (let page = 0; page < MAX_TIE_OUT_JOURNAL_PAGES; page++) {+ const rows = await database+ .selectFrom("journal")+ .select(["id", "postingDate", "reversalOfId"])+ .where("companyId", "=", companyId)+ .where("status", "in", ["Posted", "Reversed"])+ .where("postingDate", ">=", minStart)+ .where("postingDate", "<=", maxEnd)+ .orderBy("id", "asc")+ .limit(TIE_OUT_JOURNAL_PAGE_SIZE)+ .offset(page * TIE_OUT_JOURNAL_PAGE_SIZE)+ .execute();++ for (const row of rows) {+ const journal: TieOutJournal = {+ id: row.id,+ postingDate:+ row.postingDate == null ? null : toPostingDateString(row.postingDate),+ reversalOfId: row.reversalOfId ?? null,+ lines: []+ };+ journals.push(journal);+ journalsById.set(journal.id, journal);+ }++ if (rows.length < TIE_OUT_JOURNAL_PAGE_SIZE) break;+ if (page === MAX_TIE_OUT_JOURNAL_PAGES - 1) {+ console.warn(+ `[RECONCILIATION] ${companyId}/${providerId}: tie-out journal scan truncated at ${journals.length} journals`+ );+ }+ }++ if (journals.length === 0) return 0;++ const journalIds = journals.map((journal) => journal.id);+ for (let i = 0; i < journalIds.length; i += JOURNAL_ID_CHUNK_SIZE) {+ const chunk = journalIds.slice(i, i + JOURNAL_ID_CHUNK_SIZE);+ const lines = await database+ .selectFrom("journalLine")+ .select(["journalId", "accountId", "amount", "documentId"])+ .where("companyId", "=", companyId)+ .where("journalId", "in", chunk)+ .execute();++ for (const line of lines) {+ if (!line.journalId) continue;+ journalsById.get(line.journalId)?.lines.push({+ accountId: line.accountId ?? null,+ amount: Number(line.amount) || 0,+ documentId: line.documentId ?? null+ });+ }+ }++ const accountIds = [+ ...new Set(+ journals+ .flatMap((journal) => journal.lines.map((line) => line.accountId))+ .filter((accountId): accountId is string => accountId !== null)+ )+ ];+ const accountClassById = new Map<string, string | null>();+ for (let i = 0; i < accountIds.length; i += JOURNAL_ID_CHUNK_SIZE) {+ const chunk = accountIds.slice(i, i + JOURNAL_ID_CHUNK_SIZE);+ // account is company-GROUP scoped (companyGroupId, no companyId); the+ // ids come from this company's own journal lines, so id alone is safe+ const rows = await database+ .selectFrom("account")+ .select(["id", "class"])+ .where("id", "in", chunk)+ .execute();+ for (const row of rows) {+ accountClassById.set(row.id, row.class ?? null);+ }+ }++ // ── Dispositions: latest operation per sync entity id ────────────────────+ // An original journal is covered by its own operation (plus a :reversal+ // one once reversed); a reversal journal ROW (reversalOfId set) is+ // represented by the ORIGINAL journal's :reversal operation — reversal+ // inserts never enqueue their own (getJournalPostingDecision).+ const candidateEntityIds = new Set<string>();+ for (const journal of journals) {+ if (journal.reversalOfId) {+ candidateEntityIds.add(+ getJournalEntrySyncEntityId(journal.reversalOfId, true)+ );+ } else {+ candidateEntityIds.add(getJournalEntrySyncEntityId(journal.id, false));+ candidateEntityIds.add(getJournalEntrySyncEntityId(journal.id, true));+ }+ }+ const dispositionOps = await getJournalDispositionOperations(client, {+ companyId,+ integration: providerId,+ entityIds: [...candidateEntityIds]+ });+ const latestByEntityId = getLatestOperationsByEntityId(dispositionOps);++ // DOC_BACKED delivery: backing document id = the journal's lines'+ // documentId (bill → purchaseInvoice id, invoice → salesInvoice id);+ // entity type from the operation's metadata.backingDocument.+ const backingDocByOpEntityId = new Map<+ string,+ { entityType: string; entityId: string }+ >();+ for (const [entityId, operation] of latestByEntityId) {+ if (+ operation.status !== "Excluded" ||+ operation.errorCode !== DOC_BACKED_ERROR_CODE+ ) {+ continue;+ }+ const backingType = getBackingDocumentEntityType(operation.metadata);+ if (!backingType) continue;++ const { journalId } = parseJournalEntrySyncEntityId(entityId);+ const documentId =+ journalsById+ .get(journalId)+ ?.lines.find((line) => line.documentId !== null)?.documentId ?? null;+ if (!documentId) continue;++ backingDocByOpEntityId.set(entityId, {+ entityType: backingType,+ entityId: documentId+ });+ }+ const deliveredByDoc = await getBackingDocumentDelivery(client, database, {+ companyId,+ integration: providerId,+ docs: [...backingDocByOpEntityId.values()]+ });++ // ── Carbon-side cells: posted totals + disposition buckets ───────────────+ const cellKey = (periodId: string, accountId: string) =>+ `${periodId}::${accountId}`;+ const addCents = (cells: Map<string, number>, key: string, cents: number) => {+ cells.set(key, (cells.get(key) ?? 0) + cents);+ };++ const carbonPostedCells = new Map<string, number>();+ const bucketCells: Record<TieOutBucket, Map<string, number>> = {+ synced: new Map(),+ docBacked: new Map(),+ excluded: new Map(),+ pending: new Map(),+ blocked: new Map()+ };++ for (const journal of journals) {+ const period = findAccountingPeriodForDate(periods, journal.postingDate);+ if (!period) continue;++ const candidates = journal.reversalOfId+ ? [getJournalEntrySyncEntityId(journal.reversalOfId, true)]+ : [+ getJournalEntrySyncEntityId(journal.id, false),+ getJournalEntrySyncEntityId(journal.id, true)+ ];++ const buckets: TieOutBucket[] = [];+ for (const entityId of candidates) {+ const operation = latestByEntityId.get(entityId);+ if (!operation) continue;+ const backingDoc = backingDocByOpEntityId.get(entityId);+ const docBackedDelivered = backingDoc+ ? (deliveredByDoc.get(+ `${backingDoc.entityType}:${backingDoc.entityId}`+ ) ?? false)+ : false;+ buckets.push(getOperationTieOutBucket(operation, { docBackedDelivered }));+ }+ const bucket = foldTieOutBuckets(buckets);++ for (const line of journal.lines) {+ if (!line.accountId) continue;+ const cents = Math.round(+ toDebitSignedAmount(accountClassById.get(line.accountId), line.amount) *+ 100+ );+ const key = cellKey(period.id, line.accountId);+ addCents(carbonPostedCells, key, cents);+ addCents(bucketCells[bucket], key, cents);+ }+ }++ // ── Provider-side cells: reuse the presence check's fetches ──────────────+ const accountMappingRows = await database+ .selectFrom("externalIntegrationMapping")+ .select(["entityId", "externalId", "metadata"])+ .where("companyId", "=", companyId)+ .where("integration", "=", providerId)+ .where("entityType", "=", "account")+ .orderBy("entityId", "asc")+ .execute();+ const remoteRefIndex = buildRemoteAccountRefIndex(accountMappingRows);++ const reversalRowByOriginalId = new Map<string, TieOutJournal>();+ for (const journal of journals) {+ if (journal.reversalOfId) {+ reversalRowByOriginalId.set(journal.reversalOfId, journal);+ }+ }++ const providerCells = new Map<string, number>();+ for (const [externalId, group] of args.operationsByExternalId) {+ const totals = args.fetchedByExternalId.get(externalId);+ if (!totals || !totals.found) continue;++ // The posting date of what this provider journal represents: ordinary+ // ops → the journal row's posting date; reversal ops → the reversal+ // journal ROW's date (that's the row whose lines land in the buckets);+ // consolidation markers → metadata.postingDate.+ let postingDate: string | null = null;+ for (const operation of group) {+ if (isDailyConsolidationMarker(operation.entityId)) {+ if (typeof operation.metadata?.postingDate === "string") {+ postingDate = operation.metadata.postingDate;+ break;+ }+ continue;+ }+ const { journalId, reversal } = parseJournalEntrySyncEntityId(+ operation.entityId+ );+ if (reversal) {+ postingDate =+ reversalRowByOriginalId.get(journalId)?.postingDate ??+ journalsById.get(journalId)?.postingDate ??+ args.carbonJournals.get(journalId)?.postingDate ??+ null;+ } else {+ postingDate =+ journalsById.get(journalId)?.postingDate ??+ args.carbonJournals.get(journalId)?.postingDate ??+ null;+ }+ if (postingDate) break;+ }++ const period = findAccountingPeriodForDate(periods, postingDate);+ if (!period) continue;++ for (const [ref, amount] of totals.debitTotalsByAccountRef) {+ const accountId = remoteRefIndex.get(ref);+ if (!accountId) continue;+ addCents(+ providerCells,+ cellKey(period.id, accountId),+ Math.round(amount * 100)+ );+ }+ }++ // ── Upsert cells ─────────────────────────────────────────────────────────+ const allKeys = new Set<string>([+ ...carbonPostedCells.keys(),+ ...bucketCells.synced.keys(),+ ...bucketCells.docBacked.keys(),+ ...bucketCells.excluded.keys(),+ ...bucketCells.pending.keys(),+ ...bucketCells.blocked.keys(),+ ...providerCells.keys()+ ]);+ if (allKeys.size === 0) return 0;++ const nowIso = new Date().toISOString();+ const rows = [...allKeys].map((key) => {+ const [periodId = "", accountId = ""] = key.split("::");+ const cents: TieOutCellCents = {+ carbonPostedCents: carbonPostedCells.get(key) ?? 0,+ syncedCents: bucketCells.synced.get(key) ?? 0,+ docBackedCents: bucketCells.docBacked.get(key) ?? 0,+ excludedCents: bucketCells.excluded.get(key) ?? 0,+ pendingCents: bucketCells.pending.get(key) ?? 0,+ blockedCents: bucketCells.blocked.get(key) ?? 0,+ providerCents: providerCells.has(key)+ ? (providerCells.get(key) ?? 0)+ : null+ };+ const { internalDeltaCents, externalDeltaCents } =+ computeTieOutDeltas(cents);++ return {+ companyId,+ integration: providerId,+ accountingPeriodId: periodId,+ accountId,+ carbonPostedAmount: cents.carbonPostedCents / 100,+ syncedAmount: cents.syncedCents / 100,+ docBackedAmount: cents.docBackedCents / 100,+ excludedAmount: cents.excludedCents / 100,+ pendingAmount: cents.pendingCents / 100,+ blockedAmount: cents.blockedCents / 100,+ providerAmount:+ cents.providerCents === null ? null : cents.providerCents / 100,+ internalDelta: internalDeltaCents / 100,+ externalDelta:+ externalDeltaCents === null ? null : externalDeltaCents / 100,+ computedAt: nowIso,+ createdBy: args.createdBy,+ updatedBy: args.createdBy,+ updatedAt: nowIso+ };+ });++ for (let i = 0; i < rows.length; i += TIE_OUT_UPSERT_CHUNK_SIZE) {+ const chunk = rows.slice(i, i + TIE_OUT_UPSERT_CHUNK_SIZE);+ const upserted = await tieOutTable(client).upsert(chunk, {+ onConflict: "companyId,integration,accountingPeriodId,accountId"+ });+ if (upserted.error) {+ throw new Error(+ `Failed to upsert tie-out cells: ${upserted.error.message}`+ );+ }+ }++ return rows.length;+}++async function reconcileCompany(args: {+ companyId: string;+ providerId: ProviderID;+ database: SyncContext["database"];+}): Promise<ReconciliationSummary> {+ const { companyId, providerId, database } = args;+ const client = getCarbonServiceRole();++ const summary: ReconciliationSummary = {+ operations: 0,+ externalIds: 0,+ checkedExternalIds: 0,+ missing: 0,+ tieOutCells: 0,+ truncated: false+ };++ const integration = await getAccountingIntegration(+ client,+ companyId,+ providerId+ );++ const settings = resolvePostingSyncSettings(integration.metadata);++ const provider = getProviderIntegration(+ client,+ companyId,+ integration.id,+ integration.metadata+ );++ const runAt = new Date().toISOString();+ const windowStart = new Date(+ Date.now() - RECONCILIATION_WINDOW_DAYS * 24 * 60 * 60 * 1000+ );++ // ── Window of pushed operations, grouped by provider journal ─────────────+ const operations = await getCompletedJournalOperations(client, {+ companyId,+ integration: providerId,+ windowStart+ });+ summary.operations = operations.length;++ const operationsByExternalId = new Map<string, SyncOperation[]>();+ for (const operation of operations) {+ if (!operation.externalId) continue;+ const group = operationsByExternalId.get(operation.externalId);+ if (group) {+ group.push(operation);+ } else {+ operationsByExternalId.set(operation.externalId, [operation]);+ }+ }+ summary.externalIds = operationsByExternalId.size;++ // ── Carbon-side journal data for every member operation ──────────────────+ const memberJournalIds = [+ ...new Set(+ operations+ .filter((operation) => !isDailyConsolidationMarker(operation.entityId))+ .map(+ (operation) =>+ parseJournalEntrySyncEntityId(operation.entityId).journalId+ )+ )+ ];+ const carbonJournals = await getCarbonJournalData(+ database,+ companyId,+ memberJournalIds+ );++ // ── Presence check: fetch each distinct provider journal once ────────────+ const externalIds = [...operationsByExternalId.keys()];+ if (externalIds.length > MAX_PRESENCE_CHECKS) {+ summary.truncated = true;+ console.warn(+ `[RECONCILIATION] ${companyId}/${providerId}: ${externalIds.length} provider journals in the window; checking the newest ${MAX_PRESENCE_CHECKS}`+ );+ }+ const idsToCheck = externalIds.slice(0, MAX_PRESENCE_CHECKS);++ // externalId → fetched totals (null = confirmed missing/voided/deleted;+ // absent from the map = never checked, excluded from every comparison)+ const fetchedByExternalId = new Map<string, RemoteJournalTotals | null>();++ for (let i = 0; i < idsToCheck.length; i++) {+ const externalId = idsToCheck[i];+ if (!externalId) continue;++ if (i > 0 && i % PRESENCE_BATCH_SIZE === 0) {+ await new Promise((resolve) =>+ setTimeout(resolve, PRESENCE_BATCH_PAUSE_MS)+ );+ }++ try {+ const totals = await fetchRemoteJournalTotals(provider, externalId);+ fetchedByExternalId.set(externalId, totals.found ? totals : null);+ } catch (error) {+ if (error instanceof RatelimitError) {+ // Stop fetching — report on what was verified rather than failing+ // the run; unchecked ids are excluded from every comparison so+ // nothing is falsely reported missing+ summary.truncated = true;+ console.warn(+ `[RECONCILIATION] ${companyId}/${providerId}: rate limited after ${fetchedByExternalId.size} presence checks; reporting on the verified subset`+ );+ break;+ }+ throw error;+ }+ }+ summary.checkedExternalIds = fetchedByExternalId.size;++ // ── Presence drift: journals Carbon pushed that the provider lost ────────+ const missingDrift: ReconciliationDriftEntry[] = [];++ for (const [externalId, group] of operationsByExternalId) {+ if (!fetchedByExternalId.has(externalId)) continue; // never checked+ if (fetchedByExternalId.get(externalId) !== null) continue; // exists++ const memberOps = group.filter(+ (operation) => !isDailyConsolidationMarker(operation.entityId)+ );+ const markerOp = group.find((operation) =>+ isDailyConsolidationMarker(operation.entityId)+ );+ const consolidated =+ !!markerOp ||+ memberOps.some(+ (operation) => operation.metadata?.consolidatedInto != null+ );++ // Carbon-side debit total for the missing provider journal+ const memberLines: Array<{ accountId: string | null; amount: number }> = [];+ let rawPositiveCents = 0;+ let membersResolved = 0;++ for (const operation of memberOps) {+ const { journalId, reversal } = parseJournalEntrySyncEntityId(+ operation.entityId+ );+ const data = carbonJournals.get(journalId);+ if (!data) continue;++ membersResolved++;+ const lines = reversal+ ? data.lines.map((line) => ({ ...line, amount: -line.amount }))+ : data.lines;+ memberLines.push(...lines);+ rawPositiveCents += getPositiveCents(lines);+ }++ const carbonCents =+ membersResolved > 0+ ? consolidated+ ? getNettedPositiveCents(memberLines)+ : rawPositiveCents+ : null;++ const journalId =+ memberOps[0]?.entityId ?? markerOp?.entityId ?? externalId;+ missingDrift.push({+ type: "missing",+ externalId,+ journalId,+ ...(carbonCents !== null ? { amount: carbonCents / 100 } : {})+ });+ }+ summary.missing = missingDrift.length;++ // ── Tie-out: per-period × per-account cells (no extra provider calls) ────+ summary.tieOutCells = await computeTieOutForCompany({+ client,+ database,+ companyId,+ providerId,+ syncFromDate: settings.syncFromDate ?? null,+ createdBy: getSyncOperationActor(integration),+ operationsByExternalId,+ carbonJournals,+ fetchedByExternalId+ });++ await storeReconciliationReport(client, {+ companyId,+ providerId,+ report: { runAt, drift: missingDrift }+ });++ return summary;+}++/**+ * Read-modify-write against the RAW stored metadata (not the zod-parsed+ * copy from getAccountingIntegration, which strips unknown keys) so no+ * sibling key can be clobbered.+ */+async function storeReconciliationReport(+ client: ReturnType<typeof getCarbonServiceRole>,+ args: {+ companyId: string;+ providerId: string;+ report: ReconciliationReport;+ }+): Promise<void> {+ const current = await client+ .from("companyIntegration")+ .select("metadata")+ .eq("id", args.providerId)+ .eq("companyId", args.companyId)+ .single();++ if (current.error) {+ throw new Error(+ `Failed to read integration metadata: ${current.error.message}`+ );+ }++ const merged = mergePostingSyncReconciliation(+ current.data?.metadata,+ args.report+ );++ const updated = await client+ .from("companyIntegration")+ .update({ metadata: merged as any })+ .eq("id", args.providerId)+ .eq("companyId", args.companyId);++ if (updated.error) {+ throw new Error(+ `Failed to store reconciliation report: ${updated.error.message}`+ );+ }+}++export const accountingReconciliationFunction = inngest.createFunction(+ { id: "accounting-reconciliation", retries: 2 },+ { cron: "0 3 * * 1" }, // Mondays 03:00 UTC+ async ({ step }) => {+ const client = getCarbonServiceRole();++ const targets = await step.run("find-posting-sync-targets", async () => {+ // Every accounting provider: the reconciliation reader goes through+ // the provider-agnostic fetchRemoteJournalTotals dispatcher.+ const integrations = await client+ .from("companyIntegration")+ .select("id, companyId, metadata")+ .in("id", Object.values(ProviderID))+ .eq("active", true);++ if (integrations.error) {+ throw new Error(+ `Failed to list accounting integrations: ${integrations.error.message}`+ );+ }++ return (integrations.data ?? [])+ .filter((row) => resolvePostingSyncSettings(row.metadata).enabled)+ .map((row) => ({ companyId: row.companyId, providerId: row.id }));+ });++ if (targets.length === 0) {+ return { targets: 0, results: [] };+ }++ const results: Array<+ { companyId: string; providerId: string } & ReconciliationSummary+ > = [];++ for (const target of targets) {+ const result = await step.run(+ `reconcile-${target.companyId}-${target.providerId}`,+ async () => {+ const pool = getPostgresConnectionPool(5);+ const database = getPostgresClient(pool, PostgresDriver);+ try {+ return await reconcileCompany({+ companyId: target.companyId,+ providerId: target.providerId as ProviderID,+ database+ });+ } finally {+ await pool.end();+ }+ }+ );++ results.push({+ companyId: target.companyId,+ providerId: target.providerId,+ ...result+ });+ }++ return { targets: targets.length, results };+ }+);diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.test.ts b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.test.tsnew file mode 100644index 0000000000..169c717a7c--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.test.ts@@ -0,0 +1,1450 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import { describe, expect, it } from "vitest";+import {+ compareMonthlyTotals,+ getAdvancedPullCursor,+ getDailyConsolidationBatchKey,+ getJournalPostingDecision,+ getNettedPositiveCents,+ getPositiveCents,+ getPullCursorDecision,+ getPullIdempotencyScope,+ getSweepFloorDate,+ getSyncOperationCloseDecision,+ getSyncOperationFailureRecord,+ getSyncOperationIdempotencyKey,+ getUtcDateString,+ isClaimableConsolidationOperation,+ isDailyConsolidationMarker,+ isJournalEntryPostingEnabled,+ type JournalPostingEventInput,+ MAX_RECONCILIATION_DRIFT_ENTRIES,+ mergePostingSyncReconciliation,+ mergePullCursor,+ partitionConsolidationOperations,+ planJournalPostingOperation,+ resolvePaymentJournalFamily,+ SWEEP_LOOKBACK_DAYS,+ shouldEnqueueMissingDocument,+ toIsoDateString+} from "./accounting-sync-operations";++// ── Journal posting transition detection ────────────────────────────────────+// The event-system envelope carries the FULL old and new rows for UPDATEs+// (row_to_json in dispatch_event_batch), so a posting transition is+// old.status ≠ new.status landing on Posted/Reversed — never "any UPDATE+// that touches a Posted journal".++function journalEvent(+ overrides: Partial<JournalPostingEventInput>+): JournalPostingEventInput {+ return {+ operation: "UPDATE",+ recordId: "je_1",+ new: { id: "je_1", status: "Posted" },+ old: { id: "je_1", status: "Draft" },+ ...overrides+ };+}++describe("getJournalPostingDecision", () => {+ it("enqueues a push when status transitions to Posted", () => {+ const decision = getJournalPostingDecision(journalEvent({}));+ expect(decision).toEqual({+ action: "enqueue",+ entityId: "je_1",+ reversal: false+ });+ });++ it("does not enqueue an UPDATE that leaves status at Posted", () => {+ // e.g. an unrelated column touched on an already-Posted journal+ const decision = getJournalPostingDecision(+ journalEvent({+ new: { id: "je_1", status: "Posted", description: "edited" },+ old: { id: "je_1", status: "Posted", description: "original" }+ })+ );+ expect(decision.action).toBe("skip");+ if (decision.action === "skip") {+ expect(decision.reason).toContain("did not change");+ }+ });++ it("enqueues a reversal with the suffixed entity id when status transitions to Reversed", () => {+ const decision = getJournalPostingDecision(+ journalEvent({+ new: { id: "je_1", status: "Reversed" },+ old: { id: "je_1", status: "Posted" }+ })+ );+ expect(decision).toEqual({+ action: "enqueue",+ entityId: "je_1:reversal",+ reversal: true+ });+ });++ it("enqueues an INSERT born Posted — the post-* edge functions insert journals already Posted", () => {+ const decision = getJournalPostingDecision(+ journalEvent({+ operation: "INSERT",+ new: { id: "je_1", status: "Posted", reversalOfId: null },+ old: null+ })+ );+ expect(decision).toEqual({+ action: "enqueue",+ entityId: "je_1",+ reversal: false+ });+ });++ it("skips INSERTs born Draft (posting arrives later as an UPDATE transition)", () => {+ const decision = getJournalPostingDecision(+ journalEvent({+ operation: "INSERT",+ new: { id: "je_1", status: "Draft" },+ old: null+ })+ );+ expect(decision.action).toBe("skip");+ if (decision.action === "skip") {+ expect(decision.reason).toContain("INSERT");+ }+ });++ it("skips reversal INSERTs (reversalOfId set) — the original's Reversed transition carries the push", () => {+ const decision = getJournalPostingDecision(+ journalEvent({+ operation: "INSERT",+ new: { id: "je_2", status: "Posted", reversalOfId: "je_1" },+ old: null+ })+ );+ expect(decision.action).toBe("skip");+ if (decision.action === "skip") {+ expect(decision.reason).toContain("reversalOfId");+ }+ });++ it("skips DELETEs", () => {+ const decision = getJournalPostingDecision(+ journalEvent({+ operation: "DELETE",+ new: null,+ old: { id: "je_1", status: "Posted" }+ })+ );+ expect(decision.action).toBe("skip");+ });++ it("skips transitions to a non-posting status", () => {+ const decision = getJournalPostingDecision(+ journalEvent({+ new: { id: "je_1", status: "Draft" },+ old: { id: "je_1", status: "Posted" }+ })+ );+ expect(decision.action).toBe("skip");+ if (decision.action === "skip") {+ expect(decision.reason).toContain("'Draft'");+ }+ });++ it("skips UPDATEs whose envelope is missing the old or new status", () => {+ const missingNew = getJournalPostingDecision(+ journalEvent({ new: { id: "je_1" } })+ );+ expect(missingNew.action).toBe("skip");++ const missingOld = getJournalPostingDecision(+ journalEvent({ old: { id: "je_1" } })+ );+ expect(missingOld.action).toBe("skip");+ });+});++describe("isJournalEntryPostingEnabled", () => {+ it("is enabled by default (posting sync is always-on)", () => {+ expect(isJournalEntryPostingEnabled(undefined)).toBe(true);+ expect(isJournalEntryPostingEnabled({})).toBe(true);+ });++ it("honors a stored explicit disable at this seam (legacy escape hatch — the provider configs force it back on for the syncers)", () => {+ expect(+ isJournalEntryPostingEnabled({+ syncConfig: { entities: { journalEntry: { enabled: false } } }+ })+ ).toBe(false);+ });++ it("ignores invalid stored fragments and keeps the always-on default", () => {+ expect(+ isJournalEntryPostingEnabled({+ syncConfig: { entities: { journalEntry: { enabled: "yes" } } }+ })+ ).toBe(true);+ });+});++// ── Structured failure fidelity ──────────────────────────────────────────────+// Journal pre-flight failures surface on SyncResult.error as a structured+// envelope; the drain must record errorCode + Warning/Failed and keep the+// envelope metadata. Everything else keeps the flattened-string behavior.++describe("getSyncOperationFailureRecord", () => {+ const operation = { metadata: { reversal: true } };++ it("reports a missing sync result", () => {+ expect(getSyncOperationFailureRecord(operation, undefined)).toEqual({+ errorMessage: "No sync result returned for entity"+ });+ });++ it("keeps errorCode, warning flag and metadata for a structured journal failure", () => {+ const record = getSyncOperationFailureRecord(operation, {+ error: {+ errorCode: "UNMAPPED_ACCOUNTS",+ message: "2 account(s) have no provider account mapping",+ warning: true,+ metadata: { unmappedAccountIds: ["acc_1", "acc_2"] }+ }+ });++ expect(record).toEqual({+ errorCode: "UNMAPPED_ACCOUNTS",+ errorMessage: "2 account(s) have no provider account mapping",+ warning: true,+ // The failure metadata merges OVER the operation's existing metadata+ // so enqueue-time keys (reversal) survive the failure+ metadata: { reversal: true, unmappedAccountIds: ["acc_1", "acc_2"] }+ });+ });++ it("marks hard failures (warning: false) as Failed, not Warning", () => {+ const record = getSyncOperationFailureRecord(operation, {+ error: {+ errorCode: "UNBALANCED_JOURNAL",+ message: "Journal JE-1 does not balance",+ warning: false+ }+ });++ expect(record.warning).toBe(false);+ expect(record.errorCode).toBe("UNBALANCED_JOURNAL");+ // No envelope metadata → the operation's stored metadata is untouched+ expect(record.metadata).toBeUndefined();+ });++ it("flattens non-structured errors to strings exactly as before", () => {+ expect(+ getSyncOperationFailureRecord(operation, {+ error: new Error("Xero API returned 500")+ })+ ).toEqual({ errorMessage: "Xero API returned 500" });++ expect(+ getSyncOperationFailureRecord(operation, { error: "plain string" })+ ).toEqual({ errorMessage: "plain string" });++ expect(+ getSyncOperationFailureRecord(operation, { error: undefined })+ ).toEqual({ errorMessage: "Unknown sync error" });+ });++ it("rejects lookalike envelopes with an unknown errorCode", () => {+ const record = getSyncOperationFailureRecord(operation, {+ error: { errorCode: "NOT_A_REAL_CODE", message: "nope", warning: true }+ });++ expect(record.errorCode).toBeUndefined();+ expect(record.errorMessage).toBe(+ JSON.stringify({+ errorCode: "NOT_A_REAL_CODE",+ message: "nope",+ warning: true+ })+ );+ });+});++describe("getSyncOperationIdempotencyKey", () => {+ it("scopes the key by entity, direction and delivery — the reversal suffix rides in the entityId", () => {+ expect(+ getSyncOperationIdempotencyKey({+ entityType: "journalEntry",+ entityId: "je_1:reversal",+ direction: "push-to-accounting",+ scope: "evt_123"+ })+ ).toBe("journalEntry:je_1:reversal:push-to-accounting:evt_123");+ });+});++// ── Daily-consolidation decisions (Task 12) ──────────────────────────────────++describe("getDailyConsolidationBatchKey", () => {+ it("builds daily:<integration>:<postingDate> (legacy, no source type)", () => {+ expect(getDailyConsolidationBatchKey("xero", "2026-07-08")).toBe(+ "daily:xero:2026-07-08"+ );+ expect(getDailyConsolidationBatchKey("xero", "2026-07-08", null)).toBe(+ "daily:xero:2026-07-08"+ );+ });++ it("builds daily:<integration>:<source-type-slug>:<postingDate> for v3 partitions", () => {+ expect(+ getDailyConsolidationBatchKey("xero", "2026-07-08", "Production Event")+ ).toBe("daily:xero:production-event:2026-07-08");+ expect(+ getDailyConsolidationBatchKey("xero", "2026-07-08", "Job Consumption")+ ).toBe("daily:xero:job-consumption:2026-07-08");+ });++ it("round-trips through the marker detector", () => {+ expect(+ isDailyConsolidationMarker(+ getDailyConsolidationBatchKey("xero", "2026-07-08")+ )+ ).toBe(true);+ expect(+ isDailyConsolidationMarker(+ getDailyConsolidationBatchKey("xero", "2026-07-08", "Production Event")+ )+ ).toBe(true);+ expect(isDailyConsolidationMarker("journal_123")).toBe(false);+ expect(isDailyConsolidationMarker("journal_123:reversal")).toBe(false);+ });+});++describe("toIsoDateString", () => {+ it("passes through ISO date strings and trims timestamps", () => {+ expect(toIsoDateString("2026-07-08")).toBe("2026-07-08");+ expect(toIsoDateString("2026-07-08T14:00:00.000Z")).toBe("2026-07-08");+ });++ it("converts Date objects (driver-dependent date parsing) to UTC dates", () => {+ expect(toIsoDateString(new Date("2026-07-08T00:00:00.000Z"))).toBe(+ "2026-07-08"+ );+ });++ it("returns null for garbage", () => {+ expect(toIsoDateString(null)).toBeNull();+ expect(toIsoDateString(undefined)).toBeNull();+ expect(toIsoDateString(123)).toBeNull();+ expect(toIsoDateString("short")).toBeNull();+ expect(toIsoDateString(new Date("not a date"))).toBeNull();+ });+});++describe("getUtcDateString", () => {+ it("formats the UTC calendar date", () => {+ expect(getUtcDateString(new Date("2026-07-09T01:59:00.000Z"))).toBe(+ "2026-07-09"+ );+ // 23:30 UTC is still the same UTC day regardless of local offsets+ expect(getUtcDateString(new Date("2026-07-08T23:30:00.000Z"))).toBe(+ "2026-07-08"+ );+ });+});++describe("isClaimableConsolidationOperation", () => {+ const now = new Date("2026-07-09T02:00:00.000Z");++ it("claims Pending rows", () => {+ expect(+ isClaimableConsolidationOperation(+ { status: "Pending", lastAttemptAt: null },+ now+ )+ ).toBe(true);+ });++ it("claims only STALE In Flight rows (older than the 10 minute window)", () => {+ expect(+ isClaimableConsolidationOperation(+ { status: "In Flight", lastAttemptAt: "2026-07-09T01:55:00.000Z" },+ now+ )+ ).toBe(false);+ expect(+ isClaimableConsolidationOperation(+ { status: "In Flight", lastAttemptAt: "2026-07-09T01:49:59.000Z" },+ now+ )+ ).toBe(true);+ // No lastAttemptAt matches the claim query's `.lt` behavior: not claimable+ expect(+ isClaimableConsolidationOperation(+ { status: "In Flight", lastAttemptAt: null },+ now+ )+ ).toBe(false);+ });++ it("never claims terminal statuses", () => {+ for (const status of [+ "Completed",+ "Failed",+ "Warning",+ "Skipped"+ ] as const) {+ expect(+ isClaimableConsolidationOperation({ status, lastAttemptAt: null }, now)+ ).toBe(false);+ }+ });+});++describe("partitionConsolidationOperations", () => {+ const today = "2026-07-09";+ const integration = "xero";++ const op = (+ id: string,+ entityId: string,+ metadata: Record<string, unknown> | null = null+ ) => ({ id, entityId, metadata });++ const groupIds = (+ partition: ReturnType<typeof partitionConsolidationOperations>,+ batchKey: string+ ) => partition.byGroup.get(batchKey)?.operations.map((o) => o.id);++ it("splits markers, reversals, dated members, held and missing", () => {+ const partition = partitionConsolidationOperations({+ operations: [+ op("op_marker", "daily:xero:2026-07-07"),+ op("op_rev_meta", "j_rev", { reversal: true }),+ op("op_rev_suffix", "j_orig:reversal"),+ op("op_yesterday_a", "j_a"),+ op("op_yesterday_b", "j_b"),+ op("op_older", "j_c"),+ op("op_today", "j_today"),+ op("op_missing", "j_gone")+ ],+ postingDateByJournalId: new Map([+ ["j_rev", "2026-07-01"],+ ["j_orig", "2026-07-01"],+ ["j_a", "2026-07-08"],+ ["j_b", "2026-07-08"],+ ["j_c", "2026-07-05"],+ ["j_today", "2026-07-09"]+ ]),+ today,+ integration,+ consolidatedBatchKeys: new Set()+ });++ expect(partition.markers.map((o) => o.id)).toEqual(["op_marker"]);+ expect(partition.reversals.map((o) => o.id)).toEqual([+ "op_rev_meta",+ "op_rev_suffix"+ ]);+ // Unstamped (legacy) ops group under the sourceType-less legacy key+ expect([...partition.byGroup.keys()].sort()).toEqual([+ "daily:xero:2026-07-05",+ "daily:xero:2026-07-08"+ ]);+ expect(groupIds(partition, "daily:xero:2026-07-08")).toEqual([+ "op_yesterday_a",+ "op_yesterday_b"+ ]);+ expect(groupIds(partition, "daily:xero:2026-07-05")).toEqual(["op_older"]);+ expect(partition.held.map((o) => o.id)).toEqual(["op_today"]);+ expect(partition.missing.map((o) => o.id)).toEqual(["op_missing"]);+ expect(partition.individual).toEqual([]);+ });++ it("groups stamped members per (source type, posting date) batch key", () => {+ const partition = partitionConsolidationOperations({+ operations: [+ op("op_pe_1", "j_1", {+ sourceType: "Production Event",+ granularity: "daily-summary"+ }),+ op("op_pe_2", "j_2", {+ sourceType: "Production Event",+ granularity: "daily-summary"+ }),+ op("op_jc", "j_3", {+ sourceType: "Job Consumption",+ granularity: "daily-summary"+ }),+ op("op_legacy", "j_4")+ ],+ postingDateByJournalId: new Map([+ ["j_1", "2026-07-08"],+ ["j_2", "2026-07-08"],+ ["j_3", "2026-07-08"],+ ["j_4", "2026-07-08"]+ ]),+ today,+ integration,+ consolidatedBatchKeys: new Set()+ });++ expect([...partition.byGroup.keys()].sort()).toEqual([+ "daily:xero:2026-07-08",+ "daily:xero:job-consumption:2026-07-08",+ "daily:xero:production-event:2026-07-08"+ ]);+ expect(+ groupIds(partition, "daily:xero:production-event:2026-07-08")+ ).toEqual(["op_pe_1", "op_pe_2"]);+ expect(+ partition.byGroup.get("daily:xero:production-event:2026-07-08")+ ?.sourceType+ ).toBe("Production Event");+ expect(groupIds(partition, "daily:xero:2026-07-08")).toEqual(["op_legacy"]);+ });++ it("routes individual-granularity ops to the individual path, never consolidating them", () => {+ const partition = partitionConsolidationOperations({+ operations: [+ op("op_individual", "j_ind", {+ sourceType: "Purchase Receipt",+ granularity: "individual"+ })+ ],+ postingDateByJournalId: new Map([["j_ind", "2026-07-08"]]),+ today,+ integration,+ consolidatedBatchKeys: new Set()+ });+ expect(partition.individual.map((o) => o.id)).toEqual(["op_individual"]);+ expect(partition.byGroup.size).toBe(0);+ });++ it("holds journals dated after today (post-dated) as well", () => {+ const partition = partitionConsolidationOperations({+ operations: [op("op_future", "j_future")],+ postingDateByJournalId: new Map([["j_future", "2026-08-01"]]),+ today,+ integration,+ consolidatedBatchKeys: new Set()+ });+ expect(partition.held.map((o) => o.id)).toEqual(["op_future"]);+ });++ it("routes members of an already-consolidated batch (marker Completed) to the individual path", () => {+ const partition = partitionConsolidationOperations({+ operations: [op("op_backdated", "j_late"), op("op_normal", "j_new")],+ postingDateByJournalId: new Map([+ ["j_late", "2026-07-01"],+ ["j_new", "2026-07-08"]+ ]),+ today,+ integration,+ consolidatedBatchKeys: new Set(["daily:xero:2026-07-01"])+ });++ expect(partition.individual.map((o) => o.id)).toEqual(["op_backdated"]);+ expect(groupIds(partition, "daily:xero:2026-07-08")).toEqual(["op_normal"]);+ });+});++// ── Reconciliation comparisons (Task 13) ─────────────────────────────────────++describe("getPositiveCents", () => {+ it("sums only debit (positive) line amounts, in cents", () => {+ expect(+ getPositiveCents([+ { amount: 100.25 },+ { amount: -100.25 },+ { amount: 0.1 },+ { amount: 0.2 }+ ])+ ).toBe(10055);+ });++ it("is zero for an all-credit set", () => {+ expect(getPositiveCents([{ amount: -5 }, { amount: -1.5 }])).toBe(0);+ });+});++describe("getNettedPositiveCents", () => {+ it("nets per account before summing debits (consolidated batches)", () => {+ // acct_a nets to zero across members, so only acct_b's 100 books+ expect(+ getNettedPositiveCents([+ { accountId: "acct_a", amount: 100 },+ { accountId: "acct_c", amount: -100 },+ { accountId: "acct_a", amount: -100 },+ { accountId: "acct_b", amount: 100 }+ ])+ ).toBe(10000);+ });++ it("differs from the raw debit sum exactly when accounts cancel", () => {+ const lines = [+ { accountId: "acct_a", amount: 50 },+ { accountId: "acct_a", amount: -50 },+ { accountId: "acct_b", amount: 25 },+ { accountId: "acct_c", amount: -25 }+ ];+ expect(getPositiveCents(lines)).toBe(7500);+ expect(getNettedPositiveCents(lines)).toBe(2500);+ });+});++describe("compareMonthlyTotals", () => {+ it("reports exactly one drift row for one matching and one mismatched month", () => {+ const drift = compareMonthlyTotals({+ carbonCentsByMonth: new Map([+ ["2026-05", 125000],+ ["2026-06", 200000]+ ]),+ providerCentsByMonth: new Map([+ ["2026-05", 125000],+ ["2026-06", 190000]+ ])+ });++ expect(drift).toEqual([+ {+ type: "mismatch",+ month: "2026-06",+ carbonTotal: 2000,+ providerTotal: 1900+ }+ ]);+ });++ it("tolerates a difference of exactly 0.01 but not more", () => {+ const atBoundary = compareMonthlyTotals({+ carbonCentsByMonth: new Map([["2026-06", 10001]]),+ providerCentsByMonth: new Map([["2026-06", 10000]])+ });+ expect(atBoundary).toEqual([]);++ const overBoundary = compareMonthlyTotals({+ carbonCentsByMonth: new Map([["2026-06", 10002]]),+ providerCentsByMonth: new Map([["2026-06", 10000]])+ });+ expect(overBoundary).toEqual([+ {+ type: "mismatch",+ month: "2026-06",+ carbonTotal: 100.02,+ providerTotal: 100+ }+ ]);+ });++ it("treats a month missing on one side as zero", () => {+ const drift = compareMonthlyTotals({+ carbonCentsByMonth: new Map([["2026-04", 5000]]),+ providerCentsByMonth: new Map()+ });+ expect(drift).toEqual([+ {+ type: "mismatch",+ month: "2026-04",+ carbonTotal: 50,+ providerTotal: 0+ }+ ]);+ });++ it("sorts drift rows by month", () => {+ const drift = compareMonthlyTotals({+ carbonCentsByMonth: new Map([+ ["2026-06", 100],+ ["2026-04", 300]+ ]),+ providerCentsByMonth: new Map()+ });+ expect(drift.map((entry) => entry.month)).toEqual(["2026-04", "2026-06"]);+ });+});++describe("mergePostingSyncReconciliation", () => {+ const report = {+ runAt: "2026-07-13T03:00:00.000Z",+ drift: [+ {+ type: "missing" as const,+ externalId: "mj_1",+ journalId: "j_1",+ amount: 100+ }+ ]+ };++ it("preserves credentials, syncConfig and sibling settings keys", () => {+ const metadata = {+ credentials: { type: "oauth2", accessToken: "secret" },+ syncConfig: { entities: { journalEntry: { enabled: true } } },+ defaultSalesAccountCode: "200",+ settings: {+ other: { keep: true },+ postingSync: {+ enabled: true,+ consolidation: "daily",+ sourceTypes: ["Purchase Receipt"]+ }+ }+ };++ const merged = mergePostingSyncReconciliation(metadata, report);++ expect(merged.credentials).toEqual(metadata.credentials);+ expect(merged.syncConfig).toEqual(metadata.syncConfig);+ expect(merged.defaultSalesAccountCode).toBe("200");+ expect((merged.settings as Record<string, unknown>).other).toEqual({+ keep: true+ });++ const postingSync = (merged.settings as Record<string, any>).postingSync;+ expect(postingSync.enabled).toBe(true);+ expect(postingSync.consolidation).toBe("daily");+ expect(postingSync.sourceTypes).toEqual(["Purchase Receipt"]);+ expect(postingSync.lastReconciliation).toEqual({+ runAt: report.runAt,+ drift: report.drift+ });+ });++ it("replaces a previous report instead of accumulating", () => {+ const metadata = {+ settings: {+ postingSync: {+ enabled: true,+ lastReconciliation: {+ runAt: "2026-07-06T03:00:00.000Z",+ drift: [{ type: "mismatch", month: "2026-05" }]+ }+ }+ }+ };++ const merged = mergePostingSyncReconciliation(metadata, report);+ const postingSync = (merged.settings as Record<string, any>).postingSync;+ expect(postingSync.lastReconciliation.runAt).toBe(report.runAt);+ expect(postingSync.lastReconciliation.drift).toEqual(report.drift);+ });++ it("builds the settings path from nothing (null metadata)", () => {+ const merged = mergePostingSyncReconciliation(null, report);+ expect(+ (merged.settings as Record<string, any>).postingSync.lastReconciliation+ .runAt+ ).toBe(report.runAt);+ });++ it("caps drift at 100 entries", () => {+ const bigReport = {+ runAt: report.runAt,+ drift: Array.from({ length: 150 }, (_, index) => ({+ type: "missing" as const,+ externalId: `mj_${index}`,+ journalId: `j_${index}`+ }))+ };++ const merged = mergePostingSyncReconciliation({}, bigReport);+ const stored = (merged.settings as Record<string, any>).postingSync+ .lastReconciliation.drift;+ expect(stored).toHaveLength(MAX_RECONCILIATION_DRIFT_ENTRIES);+ expect(stored[0].externalId).toBe("mj_0");+ expect(stored[99].externalId).toBe("mj_99");+ });+});++// ── Pull-sweep cursor decisions ──────────────────────────────────────────────++describe("getPullCursorDecision", () => {+ const now = new Date("2026-07-09T12:00:00.000Z");+ // 29 days before `now` (QBO CDC caps the lookback at 30)+ const clampFloor = "2026-06-10T12:00:00.000Z";+ const maxLookbackDays = 29;++ it("uses the stored settings.pullCursor, normalized to UTC", () => {+ expect(+ getPullCursorDecision({+ integrationMetadata: {+ settings: { pullCursor: "2026-07-08T13:07:59-07:00" }+ },+ integrationUpdatedAt: "2026-07-01T00:00:00.000Z",+ maxLookbackDays,+ now+ })+ ).toEqual({+ changedSince: "2026-07-08T20:07:59.000Z",+ clamped: false,+ source: "cursor"+ });+ });++ it("defaults to the integration's updatedAt (connect time) when no cursor is stored", () => {+ expect(+ getPullCursorDecision({+ integrationMetadata: { settings: {} },+ integrationUpdatedAt: "2026-07-01T00:00:00.000Z",+ maxLookbackDays,+ now+ })+ ).toEqual({+ changedSince: "2026-07-01T00:00:00.000Z",+ clamped: false,+ source: "connectTime"+ });+ });++ it("clamps cursors older than a capped provider's window and reports it", () => {+ expect(+ getPullCursorDecision({+ integrationMetadata: {+ settings: { pullCursor: "2026-01-01T00:00:00.000Z" }+ },+ integrationUpdatedAt: null,+ maxLookbackDays,+ now+ })+ ).toEqual({+ changedSince: clampFloor,+ clamped: true,+ source: "cursor"+ });+ });++ it("clamps a stale connect-time default the same way", () => {+ expect(+ getPullCursorDecision({+ integrationMetadata: null,+ integrationUpdatedAt: "2026-01-01T00:00:00.000Z",+ maxLookbackDays,+ now+ })+ ).toEqual({+ changedSince: clampFloor,+ clamped: true,+ source: "connectTime"+ });+ });++ it("falls back to the clamp floor when neither a parseable cursor nor updatedAt exists", () => {+ expect(+ getPullCursorDecision({+ integrationMetadata: { settings: { pullCursor: "not a date" } },+ integrationUpdatedAt: null,+ maxLookbackDays,+ now+ })+ ).toEqual({+ changedSince: clampFloor,+ clamped: false,+ source: "fallback"+ });+ });++ it("never clamps a provider without a lookback cap (Rillet)", () => {+ expect(+ getPullCursorDecision({+ integrationMetadata: {+ settings: { pullCursor: "2026-01-01T00:00:00.000Z" }+ },+ integrationUpdatedAt: null,+ now+ })+ ).toEqual({+ changedSince: "2026-01-01T00:00:00.000Z",+ clamped: false,+ source: "cursor"+ });+ });++ it("uncapped fallback is `now` when nothing usable is stored", () => {+ expect(+ getPullCursorDecision({+ integrationMetadata: null,+ integrationUpdatedAt: null,+ now+ })+ ).toEqual({+ changedSince: now.toISOString(),+ clamped: false,+ source: "fallback"+ });+ });+});++describe("getAdvancedPullCursor", () => {+ it("advances to the max LastUpdatedTime seen, normalizing offsets to UTC", () => {+ expect(+ getAdvancedPullCursor({+ changedSince: "2026-07-08T00:00:00.000Z",+ lastUpdatedTimes: [+ "2026-07-08T23:00:00Z",+ // 18:00 -07:00 = 2026-07-09T01:00:00Z — chronologically later+ // despite the smaller wall-clock time+ "2026-07-08T18:00:00-07:00",+ null+ ]+ })+ ).toBe("2026-07-09T01:00:00.000Z");+ });++ it("never regresses: an empty or all-older change set keeps changedSince", () => {+ expect(+ getAdvancedPullCursor({+ changedSince: "2026-07-08T00:00:00.000Z",+ lastUpdatedTimes: []+ })+ ).toBe("2026-07-08T00:00:00.000Z");++ expect(+ getAdvancedPullCursor({+ changedSince: "2026-07-08T00:00:00.000Z",+ lastUpdatedTimes: ["2026-07-01T00:00:00.000Z", "garbage", null]+ })+ ).toBe("2026-07-08T00:00:00.000Z");+ });+});++describe("getPullIdempotencyScope", () => {+ it("scopes by the change's updatedAt — stable across cron retries", () => {+ expect(+ getPullIdempotencyScope(+ "2026-07-08T13:07:59-07:00",+ "2026-07-08T00:00:00.000Z"+ )+ ).toBe("pull:2026-07-08T13:07:59-07:00");+ });++ it("falls back to the run's changedSince when the record has no timestamp", () => {+ expect(getPullIdempotencyScope(null, "2026-07-08T00:00:00.000Z")).toBe(+ "pull:2026-07-08T00:00:00.000Z"+ );+ });++ it("composes with the established idempotency-key scheme", () => {+ expect(+ getSyncOperationIdempotencyKey({+ entityType: "customer",+ entityId: "63",+ direction: "pull-from-accounting",+ scope: getPullIdempotencyScope(+ "2026-07-08T13:07:59-07:00",+ "2026-07-08T00:00:00.000Z"+ )+ })+ ).toBe("customer:63:pull-from-accounting:pull:2026-07-08T13:07:59-07:00");+ });+});++describe("mergePullCursor", () => {+ it("writes settings.pullCursor (NOT under postingSync) preserving every sibling", () => {+ const metadata = {+ credentials: { type: "oauth2", accessToken: "secret" },+ syncConfig: { entities: { customer: { enabled: true } } },+ settings: {+ postingSync: { enabled: true, consolidation: "daily" },+ other: { keep: true },+ pullCursor: "2026-07-01T00:00:00.000Z"+ }+ };++ const merged = mergePullCursor(metadata, "2026-07-08T20:07:59.000Z");++ expect(merged.credentials).toEqual(metadata.credentials);+ expect(merged.syncConfig).toEqual(metadata.syncConfig);+ const settings = merged.settings as Record<string, unknown>;+ expect(settings.postingSync).toEqual({+ enabled: true,+ consolidation: "daily"+ });+ expect(settings.other).toEqual({ keep: true });+ expect(settings.pullCursor).toBe("2026-07-08T20:07:59.000Z");+ });++ it("builds the settings path from nothing", () => {+ expect(mergePullCursor(null, "2026-07-08T00:00:00.000Z")).toEqual({+ settings: { pullCursor: "2026-07-08T00:00:00.000Z" }+ });+ });+});++// ── v3 posting dispositions (plan + payment family) ─────────────────────────++/**+ * Minimal supabase stub for resolvePaymentJournalFamily: accountDefault+ * resolves the control accounts, journalLine resolves the line accountIds.+ */+function stubPaymentClient(args: {+ receivables: string;+ payables: string;+ lineAccounts: string[];+}): SupabaseClient<Database> {+ return {+ from(table: string) {+ if (table === "accountDefault") {+ return {+ select: () => ({+ eq: () => ({+ maybeSingle: async () => ({+ data: {+ receivablesAccount: args.receivables,+ payablesAccount: args.payables+ },+ error: null+ })+ })+ })+ };+ }+ return {+ select: () => ({+ eq: () => ({+ eq: async () => ({+ data: args.lineAccounts.map((accountId) => ({ accountId })),+ error: null+ })+ })+ })+ };+ }+ } as unknown as SupabaseClient<Database>;+}++/** Client that throws if touched — non-Payment paths must not query. */+const untouchableClient = new Proxy(+ {},+ {+ get() {+ throw new Error("planJournalPostingOperation touched the client");+ }+ }+) as SupabaseClient<Database>;++const postingEnabledMetadata = (overrides?: {+ postingSync?: Record<string, unknown>;+ entities?: Record<string, Record<string, unknown>>;+}) => ({+ syncConfig: {+ entities: {+ journalEntry: { enabled: true, direction: "push-to-accounting" },+ ...(overrides?.entities ?? {})+ }+ },+ settings: {+ postingSync: { enabled: true, ...(overrides?.postingSync ?? {}) }+ }+});++describe("resolvePaymentJournalFamily", () => {+ it("resolves AR when the lines touch the receivables control account", async () => {+ const family = await resolvePaymentJournalFamily(+ stubPaymentClient({+ receivables: "acc-ar",+ payables: "acc-ap",+ lineAccounts: ["acc-bank", "acc-ar"]+ }),+ { companyId: "co_1", journalId: "je_1" }+ );+ expect(family).toBe("ar");+ });++ it("resolves AP when the lines touch the payables control account", async () => {+ const family = await resolvePaymentJournalFamily(+ stubPaymentClient({+ receivables: "acc-ar",+ payables: "acc-ap",+ lineAccounts: ["acc-bank", "acc-ap"]+ }),+ { companyId: "co_1", journalId: "je_1" }+ );+ expect(family).toBe("ap");+ });++ it("returns null when neither or both control sides appear", async () => {+ expect(+ await resolvePaymentJournalFamily(+ stubPaymentClient({+ receivables: "acc-ar",+ payables: "acc-ap",+ lineAccounts: ["acc-bank"]+ }),+ { companyId: "co_1", journalId: "je_1" }+ )+ ).toBeNull();++ expect(+ await resolvePaymentJournalFamily(+ stubPaymentClient({+ receivables: "acc-ar",+ payables: "acc-ap",+ lineAccounts: ["acc-ar", "acc-ap"]+ }),+ { companyId: "co_1", journalId: "je_1" }+ )+ ).toBeNull();+ });+});++describe("planJournalPostingOperation", () => {+ it("skips non-posting events without touching the policy", async () => {+ const plan = await planJournalPostingOperation({+ client: untouchableClient,+ companyId: "co_1",+ event: {+ operation: "INSERT",+ recordId: "je_1",+ new: { id: "je_1", status: "Draft" },+ old: null+ },+ integrationMetadata: postingEnabledMetadata()+ });+ expect(plan.action).toBe("skip");+ });++ it("plans a push with granularity + sourceType metadata for enabled journal types", async () => {+ const plan = await planJournalPostingOperation({+ client: untouchableClient,+ companyId: "co_1",+ event: {+ operation: "INSERT",+ recordId: "je_1",+ new: {+ id: "je_1",+ status: "Posted",+ reversalOfId: null,+ sourceType: "Production Event"+ },+ old: null+ },+ integrationMetadata: postingEnabledMetadata()+ });++ expect(plan).toEqual({+ action: "push",+ request: {+ entityType: "journalEntry",+ entityId: "je_1",+ direction: "push-to-accounting",+ metadata: {+ sourceType: "Production Event",+ granularity: "daily-summary"+ }+ }+ });+ });++ it("records DOC_BACKED exclusions with the backing document entity", async () => {+ const plan = await planJournalPostingOperation({+ client: untouchableClient,+ companyId: "co_1",+ event: {+ operation: "INSERT",+ recordId: "je_1",+ new: {+ id: "je_1",+ status: "Posted",+ reversalOfId: null,+ sourceType: "Sales Invoice"+ },+ old: null+ },+ integrationMetadata: postingEnabledMetadata()+ });++ expect(plan.action).toBe("terminal");+ if (plan.action !== "terminal") throw new Error("expected terminal");+ expect(plan.request.status).toBe("Excluded");+ expect(plan.request.errorCode).toBe("DOC_BACKED");+ expect(plan.request.metadata).toMatchObject({+ sourceType: "Sales Invoice",+ backingDocument: { entityType: "invoice" }+ });+ });++ it("parks DOC_SYNC_DISABLED as a Warning when the backing document sync is off", async () => {+ const plan = await planJournalPostingOperation({+ client: untouchableClient,+ companyId: "co_1",+ event: {+ operation: "INSERT",+ recordId: "je_1",+ new: {+ id: "je_1",+ status: "Posted",+ reversalOfId: null,+ sourceType: "Sales Invoice"+ },+ old: null+ },+ integrationMetadata: postingEnabledMetadata({+ entities: { invoice: { enabled: false } }+ })+ });++ expect(plan.action).toBe("terminal");+ if (plan.action !== "terminal") throw new Error("expected terminal");+ expect(plan.request.status).toBe("Warning");+ expect(plan.request.errorCode).toBe("DOC_SYNC_DISABLED");+ });++ it("suffixes reversal pushes and stamps reversal metadata", async () => {+ const plan = await planJournalPostingOperation({+ client: untouchableClient,+ companyId: "co_1",+ event: {+ operation: "UPDATE",+ recordId: "je_1",+ new: { id: "je_1", status: "Reversed", sourceType: "Purchase Receipt" },+ old: { id: "je_1", status: "Posted" }+ },+ integrationMetadata: postingEnabledMetadata()+ });++ expect(plan).toEqual({+ action: "push",+ request: {+ entityType: "journalEntry",+ entityId: "je_1:reversal",+ direction: "push-to-accounting",+ metadata: {+ reversal: true,+ sourceType: "Purchase Receipt",+ granularity: "individual"+ }+ }+ });+ });++ it("resolves the Payment side from control-account lines when family modes diverge", async () => {+ const metadata = postingEnabledMetadata({+ postingSync: {+ families: { ar: "journals", ap: "documents" }+ },+ entities: { invoice: { enabled: false } }+ });++ const arPlan = await planJournalPostingOperation({+ client: stubPaymentClient({+ receivables: "acc-ar",+ payables: "acc-ap",+ lineAccounts: ["acc-bank", "acc-ar"]+ }),+ companyId: "co_1",+ event: {+ operation: "INSERT",+ recordId: "je_1",+ new: {+ id: "je_1",+ status: "Posted",+ reversalOfId: null,+ sourceType: "Payment"+ },+ old: null+ },+ integrationMetadata: metadata+ });+ expect(arPlan.action).toBe("push");++ const unresolvedPlan = await planJournalPostingOperation({+ client: stubPaymentClient({+ receivables: "acc-ar",+ payables: "acc-ap",+ lineAccounts: ["acc-bank"]+ }),+ companyId: "co_1",+ event: {+ operation: "INSERT",+ recordId: "je_2",+ new: {+ id: "je_2",+ status: "Posted",+ reversalOfId: null,+ sourceType: "Payment"+ },+ old: null+ },+ integrationMetadata: metadata+ });+ expect(unresolvedPlan.action).toBe("terminal");+ if (unresolvedPlan.action !== "terminal")+ throw new Error("expected terminal");+ expect(unresolvedPlan.request.errorCode).toBe("PAYMENT_FAMILY_UNRESOLVED");+ });+});++// ── Truthful-ledger close decisions (v4 spec, Pillar C) ─────────────────────++describe("getSyncOperationCloseDecision", () => {+ const pushOp = { metadata: null, direction: "push-to-accounting" as const };+ const pullOp = { metadata: null, direction: "pull-from-accounting" as const };++ it("fails when the syncer returned no result for the entity", () => {+ const decision = getSyncOperationCloseDecision(pushOp, undefined);+ expect(decision.outcome).toBe("failed");+ });++ it("fails on an error result, preserving the failure record", () => {+ const decision = getSyncOperationCloseDecision(pushOp, {+ status: "error",+ action: "none",+ localId: "pi_1",+ error: "boom"+ });+ expect(decision).toEqual({+ outcome: "failed",+ record: { errorMessage: "boom" }+ });+ });++ it("completes a skip that carries a remoteId — the remote copy exists", () => {+ // Fast-bailout ("Already synced - local unchanged") and already-linked+ // hard-skips return the mapping's externalId; recording Completed with+ // that id is the truth.+ const decision = getSyncOperationCloseDecision(pushOp, {+ status: "skipped",+ action: "none",+ localId: "pi_1",+ remoteId: "remote-1",+ error: "Already synced - local unchanged"+ });+ expect(decision).toEqual({ outcome: "completed", externalId: "remote-1" });+ });++ it("records Skipped (not Completed) for a no-op with nothing behind it", () => {+ // The observed false-green failure mode: a shouldSync gate ("Bill must+ // be posted…") closing as Completed with no external mapping.+ const decision = getSyncOperationCloseDecision(pushOp, {+ status: "skipped",+ action: "none",+ localId: "pi_1",+ error: "Bill must be posted before syncing"+ });+ expect(decision).toEqual({+ outcome: "skipped",+ reason: "Bill must be posted before syncing"+ });+ });++ it("defaults the skip reason when the syncer supplied none", () => {+ const decision = getSyncOperationCloseDecision(pushOp, {+ status: "skipped",+ action: "none",+ localId: "pi_1"+ });+ expect(decision).toEqual({+ outcome: "skipped",+ reason: "Not eligible for sync"+ });+ });++ it("fails a push success that produced no remote id (POSTCONDITION)", () => {+ const decision = getSyncOperationCloseDecision(pushOp, {+ status: "success",+ action: "created",+ localId: "pi_1"+ });+ expect(decision.outcome).toBe("failed");+ if (decision.outcome === "failed") {+ expect(decision.record.errorCode).toBe("POSTCONDITION");+ }+ });++ it("completes a push success with its remote id", () => {+ const decision = getSyncOperationCloseDecision(pushOp, {+ status: "success",+ action: "created",+ localId: "pi_1",+ remoteId: "remote-1"+ });+ expect(decision).toEqual({ outcome: "completed", externalId: "remote-1" });+ });++ it("completes a pull success without requiring a remote id", () => {+ const decision = getSyncOperationCloseDecision(pullOp, {+ status: "success",+ action: "created",+ localId: "pay_1"+ });+ expect(decision).toEqual({ outcome: "completed" });+ });+});++// ── Outbound-sweep decisions (v4 spec, Pillar B) ────────────────────────────++describe("getSweepFloorDate", () => {+ it("looks back SWEEP_LOOKBACK_DAYS from today", () => {+ expect(SWEEP_LOOKBACK_DAYS).toBe(7);+ expect(getSweepFloorDate({ todayIso: "2026-08-11" })).toBe("2026-08-04");+ });++ it("raises the floor to syncFromDate when that is later", () => {+ expect(+ getSweepFloorDate({ todayIso: "2026-08-11", syncFromDate: "2026-08-08" })+ ).toBe("2026-08-08");+ });++ it("ignores a syncFromDate older than the lookback window", () => {+ expect(+ getSweepFloorDate({ todayIso: "2026-08-11", syncFromDate: "2026-01-01" })+ ).toBe("2026-08-04");+ });++ it("accepts a timestamp-shaped syncFromDate (date part only)", () => {+ expect(+ getSweepFloorDate({+ todayIso: "2026-08-11",+ syncFromDate: "2026-08-09T14:00:00.000Z"+ })+ ).toBe("2026-08-09");+ });+});++describe("shouldEnqueueMissingDocument", () => {+ const base = {+ hasMapping: false,+ hasLiveOperation: false,+ latestOperationStatus: null as string | null+ };++ it("enqueues a pure lost event (no mapping, no ops at all)", () => {+ expect(shouldEnqueueMissingDocument(base)).toBe(true);+ });++ it("enqueues a phantom success (latest op Completed but no mapping)", () => {+ // The observed pi_Rhnz signature: a pre-truthful-ledger Completed row+ // with nothing behind it. A real Completed push implies a mapping.+ expect(+ shouldEnqueueMissingDocument({+ ...base,+ latestOperationStatus: "Completed"+ })+ ).toBe(true);+ });++ it("leaves mapped documents alone", () => {+ expect(shouldEnqueueMissingDocument({ ...base, hasMapping: true })).toBe(+ false+ );+ });++ it("leaves documents with a live operation alone", () => {+ expect(+ shouldEnqueueMissingDocument({ ...base, hasLiveOperation: true })+ ).toBe(false);+ });++ it("never re-enqueues parked dispositions (the re-drive rules own those)", () => {+ for (const status of ["Skipped", "Warning", "Failed", "Excluded"]) {+ expect(+ shouldEnqueueMissingDocument({+ ...base,+ latestOperationStatus: status+ }),+ `latest ${status} must not re-enqueue`+ ).toBe(false);+ }+ });+});diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.tsnew file mode 100644index 0000000000..e2177c7cc6--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts@@ -0,0 +1,1692 @@+/**+ * Shared machinery for routing Inngest accounting-sync entry points through+ * the "accountingSyncOperation" ledger.+ *+ * Every entry point (event sync, webhook/scheduled sync, backfill) follows+ * the same two phases:+ *+ * 1. Enqueue — one ledger row per (entityType, entityId, direction) via+ * enqueueSyncOperation. Re-triggers are absorbed into the live+ * (Pending/In Flight) row, and event/webhook triggers respect the 60s+ * completed-row cooldown enforced inside the operations service.+ * 2. Drain — claimPendingOperations moves Pending rows (plus In Flight rows+ * abandoned for more than 10 minutes) to In Flight, the same entity+ * syncers that ran before the ledger existed perform the work, and every+ * claimed row is closed out with completeOperation / failOperation.+ *+ * Because enqueue absorbs duplicates and claim/complete are idempotent, an+ * Inngest retry that re-runs an enqueue or drain step cannot duplicate work.+ *+ * Posting sync (journalEntry) rides the same machinery with two twists:+ * journal events enqueue on an INSERT born Posted (the post-* edge functions+ * insert journals already Posted; reversal inserts skip via reversalOfId) or+ * on a status TRANSITION to Posted/Reversed (getJournalPostingDecision) with+ * trigger "posting", and companies whose posting-sync settings resolve to+ * consolidation "daily" have their journalEntry operations held Pending at+ * claim time for the daily-consolidation cron instead of being pushed+ * individually.+ */+import type { Database } from "@carbon/database";+import {+ type AccountingEntityType,+ type AccountingProvider,+ type BatchSyncResult,+ claimPendingOperations,+ completeOperation,+ enqueueSyncOperation,+ failOperation,+ getJournalEntrySyncEntityId,+ getJournalPostingPolicyDecision,+ insertTerminalSyncOperation,+ isJournalEntrySyncFailure,+ netJournalLinesPerAccount,+ type PostingSyncSettings,+ parseJournalEntrySyncEntityId,+ RatelimitError,+ resolvePostingSyncSettings,+ resolveSyncConfig,+ SYNC_OPERATION_STALE_IN_FLIGHT_MS,+ type SyncContext,+ SyncFactory,+ type SyncOperation,+ type SyncOperationDirection,+ type SyncOperationTrigger,+ type SyncResult,+ skipOperation+} from "@carbon/ee/accounting";+import { groupBy } from "@carbon/utils";+import { parseDate } from "@internationalized/date";+import type { SupabaseClient } from "@supabase/supabase-js";++/**+ * Upper bound on claim iterations per drain so a single Inngest step cannot+ * spin forever on a queue that keeps refilling (25 iterations × the claim+ * batch of 20 = 500 operations).+ */+const MAX_DRAIN_ITERATIONS = 25;++/**+ * An operation claimed more times than this parks as Failed+ * (ATTEMPTS_EXHAUSTED) instead of running again — the backstop for+ * crash-looping ops that cycle In Flight → stale → re-claim forever+ * (claiming increments attemptCount). A human retry from Sync Activity+ * resets the loop deliberately.+ */+export const MAX_SYNC_OPERATION_ATTEMPTS = 10;++/**+ * The sync jobs run with a service-role client, but ledger rows need a+ * non-null createdBy (FK to "user"). None of the sync payloads carry a+ * userId, so operations are attributed to whoever last configured the+ * integration, falling back to the seeded "system" user.+ */+export function getSyncOperationActor(integration: {+ updatedBy: string | null;+}): string {+ return integration.updatedBy ?? "system";+}++/**+ * Idempotency key for one requested sync of one entity in one direction.+ *+ * The ledger has a total unique index on (companyId, integration,+ * idempotencyKey), so the scope must identify the triggering occurrence: the+ * Inngest event id (stable across retries of a run) for live event/webhook+ * syncs, or the backfill run id for backfill runs. Retries of the same+ * delivery are absorbed by the key; later deliveries get a new scope and are+ * deduped by live-row absorption and the completed-row cooldown instead.+ */+export function getSyncOperationIdempotencyKey(args: {+ entityType: string;+ entityId: string;+ direction: SyncOperationDirection;+ scope: string;+}): string {+ return `${args.entityType}:${args.entityId}:${args.direction}:${args.scope}`;+}++export type SyncOperationRequest = {+ entityType: string;+ entityId: string;+ direction: SyncOperationDirection;+ /** Stored on the ledger row (e.g. `{ reversal: true }` for journal reversal pushes). */+ metadata?: Record<string, unknown>;+};++// /********************************************************\+// * Journal posting decisions (events/sync) *+// \********************************************************/++/**+ * The slice of the event-system envelope the posting decision needs. The+ * discriminated EventSystemEvent union is assignable: UPDATE events carry+ * the full old AND new rows (`row_to_json` in dispatch_event_batch), which+ * is what makes status-transition detection possible at all.+ */+export type JournalPostingEventInput = {+ operation: "INSERT" | "UPDATE" | "DELETE" | "TRUNCATE";+ recordId: string;+ new: Record<string, unknown> | null;+ old: Record<string, unknown> | null;+};++export type JournalPostingDecision =+ | { action: "enqueue"; entityId: string; reversal: boolean }+ | { action: "skip"; reason: string };++/**+ * Decide whether a `journal` table event is a posting event worth a ledger+ * operation. Two paths enqueue (spec Phase B §2, amended 2026-07-09):+ *+ * - INSERT born `status='Posted'` with no `reversalOfId` — Carbon's `post-*`+ * edge functions insert journals already Posted (they are never UPDATEd+ * from Draft), so INSERT is the posting event on the main path. Reversal+ * inserts (`reversalOfId` set, see `reverseJournalEntry`) skip: they are+ * represented by the original journal's Reversed transition below.+ * - UPDATE whose status MOVED to 'Posted' (Draft→Posted flows) or 'Reversed'+ * (reversal push, suffixed entity id). An UPDATE that touches unrelated+ * columns while status stays 'Posted' must not re-push.+ */+export function getJournalPostingDecision(+ event: JournalPostingEventInput+): JournalPostingDecision {+ if (event.operation === "INSERT") {+ const insertedStatus =+ typeof event.new?.status === "string" ? event.new.status : null;+ if (insertedStatus !== "Posted") {+ return {+ action: "skip",+ reason: `Journal INSERT with status '${insertedStatus ?? "unknown"}' is not a posting event (only journals born Posted enqueue on INSERT)`+ };+ }+ if (event.new?.reversalOfId != null) {+ return {+ action: "skip",+ reason:+ "Journal INSERT is a reversal entry (reversalOfId set); the original journal's Reversed transition carries the reversal push"+ };+ }+ return {+ action: "enqueue",+ entityId: getJournalEntrySyncEntityId(event.recordId, false),+ reversal: false+ };+ }++ if (event.operation !== "UPDATE") {+ return {+ action: "skip",+ reason: `Journal ${event.operation} is not a posting event (journals enqueue on INSERT born Posted or when an UPDATE moves status to Posted or Reversed)`+ };+ }++ const newStatus =+ typeof event.new?.status === "string" ? event.new.status : null;+ const oldStatus =+ typeof event.old?.status === "string" ? event.old.status : null;++ if (!newStatus || !oldStatus) {+ return {+ action: "skip",+ reason:+ "Journal UPDATE event is missing the old or new status; cannot detect a posting transition"+ };+ }++ if (newStatus === oldStatus) {+ return {+ action: "skip",+ reason: `Journal status did not change (still '${newStatus}'); not a posting transition`+ };+ }++ if (newStatus === "Posted") {+ return {+ action: "enqueue",+ entityId: getJournalEntrySyncEntityId(event.recordId, false),+ reversal: false+ };+ }++ if (newStatus === "Reversed") {+ return {+ action: "enqueue",+ entityId: getJournalEntrySyncEntityId(event.recordId, true),+ reversal: true+ };+ }++ return {+ action: "skip",+ reason: `Journal status transitioned to '${newStatus}', which is not a posting status (only Posted and Reversed enqueue)`+ };+}++/**+ * Journal posting is ALWAYS-ON: enabled in DEFAULT_SYNC_CONFIG and forced on+ * by every provider's build*SyncConfig, so this resolves true for any+ * connected accounting integration. Kept as a function (not a constant) so a+ * future provider that genuinely can't take journals has a seam to say so.+ */+export function isJournalEntryPostingEnabled(+ integrationMetadata: unknown+): boolean {+ return resolveSyncConfig(integrationMetadata).entities.journalEntry.enabled;+}++/**+ * Resolve which AR/AP side a Payment journal's lines touch, from the+ * company's control accounts (accountDefault.receivablesAccount /+ * payablesAccount). Deterministic per build-payment-journal (a payment+ * journal books against exactly one control side); returns null when+ * neither or both sides appear — the policy decision parks that as+ * PAYMENT_FAMILY_UNRESOLVED when the family modes diverge.+ */+export async function resolvePaymentJournalFamily(+ client: SupabaseClient<Database>,+ args: { companyId: string; journalId: string }+): Promise<"ar" | "ap" | null> {+ const defaults = await client+ .from("accountDefault")+ .select("receivablesAccount, payablesAccount")+ .eq("companyId", args.companyId)+ .maybeSingle();++ if (defaults.error || !defaults.data) return null;++ const lines = await client+ .from("journalLine")+ .select("accountId")+ .eq("companyId", args.companyId)+ .eq("journalId", args.journalId);++ if (lines.error || !lines.data) return null;++ const accountIds = new Set(+ lines.data+ .map((line) => line.accountId)+ .filter((id): id is string => typeof id === "string" && id.length > 0)+ );++ const touchesReceivables = accountIds.has(defaults.data.receivablesAccount);+ const touchesPayables = accountIds.has(defaults.data.payablesAccount);++ if (touchesReceivables && !touchesPayables) return "ar";+ if (touchesPayables && !touchesReceivables) return "ap";+ return null;+}++export type TerminalSyncOperationRequest = {+ entityType: string;+ entityId: string;+ direction: SyncOperationDirection;+ status: "Excluded" | "Warning";+ errorCode: string;+ errorMessage: string;+ metadata?: Record<string, unknown>;+};++/**+ * What to do with one journal posting event after the transition check AND+ * the v3 policy decision: skip (not a posting event), enqueue a push, or+ * record a terminal disposition (Excluded/Warning) so the journal is+ * accounted for either way (spec I1).+ */+export type JournalPostingOperationPlan =+ | { action: "skip"; reason: string }+ | { action: "push"; request: SyncOperationRequest }+ | { action: "terminal"; request: TerminalSyncOperationRequest };++/**+ * Compose the event-transition check with the posting-policy decision for+ * one `journal` table event. The Payment control-account lookup runs only+ * when the source type is Payment AND the AR/AP family modes diverge+ * (otherwise the side cannot change the outcome).+ */+export async function planJournalPostingOperation(args: {+ client: SupabaseClient<Database>;+ companyId: string;+ event: JournalPostingEventInput;+ integrationMetadata: unknown;+}): Promise<JournalPostingOperationPlan> {+ const transition = getJournalPostingDecision(args.event);+ if (transition.action === "skip") {+ return { action: "skip", reason: transition.reason };+ }++ const settings = resolvePostingSyncSettings(args.integrationMetadata);+ const syncConfig = resolveSyncConfig(args.integrationMetadata);++ const sourceType =+ typeof args.event.new?.sourceType === "string"+ ? args.event.new.sourceType+ : null;++ const paymentFamily =+ sourceType === "Payment" && settings.families.ar !== settings.families.ap+ ? await resolvePaymentJournalFamily(args.client, {+ companyId: args.companyId,+ journalId: args.event.recordId+ })+ : null;++ return planJournalPostingFromState({+ journalId: args.event.recordId,+ sourceType,+ reversal: transition.reversal,+ settings,+ docSync: {+ invoiceEnabled: syncConfig.entities.invoice.enabled,+ billEnabled: syncConfig.entities.bill.enabled+ },+ paymentFamily,+ inventoryAdjustmentEntitySyncEnabled:+ syncConfig.entities.inventoryAdjustment.enabled+ });+}++/**+ * The STATE-shaped core of the journal posting plan (v5 reconciler): given a+ * posted journal's identity and the resolved settings — no event envelope —+ * route through the v3 policy decision and build the push/terminal request.+ * `planJournalPostingOperation` (event path, backfill) and the reconcile+ * decision core both delegate here, so the policy routing can never diverge+ * between callers. Pure: `paymentFamily` is resolved by the caller when the+ * source type is Payment and the AR/AP family modes diverge.+ */+export function planJournalPostingFromState(args: {+ journalId: string;+ sourceType: string | null;+ reversal: boolean;+ settings: PostingSyncSettings;+ docSync: { invoiceEnabled: boolean; billEnabled: boolean };+ paymentFamily: "ar" | "ap" | null;+ inventoryAdjustmentEntitySyncEnabled: boolean;+}): JournalPostingOperationPlan {+ const entityId = getJournalEntrySyncEntityId(args.journalId, args.reversal);++ const decision = getJournalPostingPolicyDecision({+ sourceType: args.sourceType,+ settings: args.settings,+ docSync: args.docSync,+ paymentFamily: args.paymentFamily,+ inventoryAdjustmentEntitySyncEnabled:+ args.inventoryAdjustmentEntitySyncEnabled+ });++ const baseMetadata = {+ ...(args.reversal ? { reversal: true } : {}),+ ...(args.sourceType ? { sourceType: args.sourceType } : {})+ };++ if (decision.kind === "push") {+ return {+ action: "push",+ request: {+ entityType: "journalEntry",+ entityId,+ direction: "push-to-accounting",+ metadata: { ...baseMetadata, granularity: decision.granularity }+ }+ };+ }++ if (decision.kind === "exclude") {+ return {+ action: "terminal",+ request: {+ entityType: "journalEntry",+ entityId,+ direction: "push-to-accounting",+ status: "Excluded",+ errorCode: decision.reason,+ errorMessage: decision.message,+ metadata: {+ ...baseMetadata,+ ...(decision.backingDocument+ ? { backingDocument: decision.backingDocument }+ : {})+ }+ }+ };+ }++ return {+ action: "terminal",+ request: {+ entityType: "journalEntry",+ entityId,+ direction: "push-to-accounting",+ status: "Warning",+ errorCode: decision.code,+ errorMessage: decision.message,+ metadata: baseMetadata+ }+ };+}++/**+ * Record terminal dispositions (Excluded/Warning at decision time), one+ * ledger row per unique request. Existing rows for a journal absorb the+ * insert (see insertTerminalSyncOperation) — re-deliveries and backfills+ * never churn duplicate terminal rows.+ */+export async function insertTerminalSyncOperations(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ integration: string;+ trigger: SyncOperationTrigger;+ createdBy: string;+ scope: string;+ requests: TerminalSyncOperationRequest[];+ }+): Promise<EnqueueOutcome[]> {+ const outcomes: EnqueueOutcome[] = [];+ const seen = new Set<string>();++ for (const request of args.requests) {+ const idempotencyKey = getSyncOperationIdempotencyKey({+ entityType: request.entityType,+ entityId: request.entityId,+ direction: request.direction,+ scope: args.scope+ });++ if (seen.has(idempotencyKey)) continue;+ seen.add(idempotencyKey);++ const { data, error } = await insertTerminalSyncOperation(client, {+ companyId: args.companyId,+ integration: args.integration,+ entityType: request.entityType,+ entityId: request.entityId,+ direction: request.direction,+ trigger: args.trigger,+ idempotencyKey,+ createdBy: args.createdBy,+ status: request.status,+ errorCode: request.errorCode,+ errorMessage: request.errorMessage,+ ...(request.metadata ? { metadata: request.metadata } : {})+ });++ if (error) {+ outcomes.push({+ entityType: request.entityType,+ entityId: request.entityId,+ direction: request.direction,+ outcome: "error",+ error+ });+ } else if (data) {+ outcomes.push({+ entityType: request.entityType,+ entityId: request.entityId,+ direction: request.direction,+ outcome: "enqueued"+ });+ } else {+ outcomes.push({+ entityType: request.entityType,+ entityId: request.entityId,+ direction: request.direction,+ outcome: "cooldown"+ });+ }+ }++ return outcomes;+}++export type EnqueueOutcome = {+ entityType: string;+ entityId: string;+ direction: SyncOperationDirection;+ /**+ * "enqueued" covers both a newly inserted row and absorption into an+ * existing one — either way an operation now covers the request.+ * "cooldown" means a Completed row for the same tuple finished inside the+ * 60s window (event/webhook triggers only).+ */+ outcome: "enqueued" | "cooldown" | "error";+ error?: string;+};++/**+ * Enqueue one ledger operation per unique request. Duplicate requests in the+ * same call (same entityType, entityId, and direction) are deduped locally.+ */+export async function enqueueSyncOperations(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ integration: string;+ trigger: SyncOperationTrigger;+ createdBy: string;+ scope: string;+ requests: SyncOperationRequest[];+ }+): Promise<EnqueueOutcome[]> {+ const outcomes: EnqueueOutcome[] = [];+ const seen = new Set<string>();++ for (const request of args.requests) {+ const idempotencyKey = getSyncOperationIdempotencyKey({+ ...request,+ scope: args.scope+ });++ if (seen.has(idempotencyKey)) continue;+ seen.add(idempotencyKey);++ const { data, error } = await enqueueSyncOperation(client, {+ companyId: args.companyId,+ integration: args.integration,+ entityType: request.entityType,+ entityId: request.entityId,+ direction: request.direction,+ trigger: args.trigger,+ idempotencyKey,+ createdBy: args.createdBy,+ ...(request.metadata ? { metadata: request.metadata } : {})+ });++ if (error) {+ outcomes.push({ ...request, outcome: "error", error });+ } else if (data) {+ outcomes.push({ ...request, outcome: "enqueued" });+ } else {+ outcomes.push({ ...request, outcome: "cooldown" });+ }+ }++ return outcomes;+}++export type DrainedGroup = {+ entityType: string;+ direction: SyncOperationDirection;+ result: BatchSyncResult;+};++export type DrainSummary = {+ claimed: number;+ completed: number;+ failed: number;+ skipped: number;+ groups: DrainedGroup[];+};++function toSyncErrorMessage(error: unknown): string {+ if (error instanceof Error) return error.message;+ if (typeof error === "string") return error;+ if (error == null) return "Unknown sync error";+ return JSON.stringify(error);+}++export type SyncOperationFailureRecord = {+ errorCode?: string;+ errorMessage: string;+ warning?: boolean;+ metadata?: Record<string, unknown>;+};++/**+ * Map a sync result's error onto the failOperation payload.+ *+ * Structured journal pre-flight failures (isJournalEntrySyncFailure on+ * SyncResult.error) keep their machine-readable errorCode, land Warning or+ * Failed per the envelope's `warning` flag, and merge the failure's+ * metadata (e.g. unmappedAccountIds) over the operation's existing+ * metadata (so enqueue-time keys like `reversal` survive). Every other+ * error keeps the flattened-string behavior.+ */+export function getSyncOperationFailureRecord(+ operation: Pick<SyncOperation, "metadata">,+ syncResult: Pick<SyncResult, "error"> | undefined+): SyncOperationFailureRecord {+ if (!syncResult) {+ return { errorMessage: "No sync result returned for entity" };+ }++ if (isJournalEntrySyncFailure(syncResult.error)) {+ const failure = syncResult.error;+ return {+ errorCode: failure.errorCode,+ errorMessage: failure.message,+ warning: failure.warning,+ ...(failure.metadata+ ? { metadata: { ...(operation.metadata ?? {}), ...failure.metadata } }+ : {})+ };+ }++ return { errorMessage: toSyncErrorMessage(syncResult.error) };+}++export type SyncOperationCloseDecision =+ | { outcome: "completed"; externalId?: string }+ | { outcome: "skipped"; reason: string }+ | { outcome: "failed"; record: SyncOperationFailureRecord };++/**+ * Decide how a claimed operation closes from its sync result — the+ * truthful-ledger rules (v4 spec, Pillar C):+ *+ * - error / missing result → Failed (structured Warnings preserved).+ * - "skipped" WITH a remoteId (fast-bailout, already-linked) → Completed+ * stamping that externalId: the remote copy exists, so Completed is the+ * truth even though this attempt was a no-op.+ * - "skipped" WITHOUT a remoteId (shouldSync gate, disabled entity,+ * parked payment) → Skipped with the reason: nothing exists remotely,+ * so Completed would be a lie — the observed false-green failure mode.+ * - push "success" WITHOUT a remoteId → Failed POSTCONDITION: a push+ * success must produce an external id/mapping; treating the violation+ * as failure surfaces the bug instead of recording a phantom sync.+ */+export function getSyncOperationCloseDecision(+ operation: Pick<SyncOperation, "metadata" | "direction">,+ syncResult: SyncResult | undefined+): SyncOperationCloseDecision {+ if (!syncResult || syncResult.status === "error") {+ return {+ outcome: "failed",+ record: getSyncOperationFailureRecord(operation, syncResult)+ };+ }++ if (syncResult.status === "skipped") {+ if (syncResult.remoteId) {+ return { outcome: "completed", externalId: syncResult.remoteId };+ }+ return {+ outcome: "skipped",+ reason: toSyncErrorMessage(syncResult.error ?? "Not eligible for sync")+ };+ }++ if (operation.direction === "push-to-accounting" && !syncResult.remoteId) {+ return {+ outcome: "failed",+ record: {+ errorCode: "POSTCONDITION",+ errorMessage:+ "Sync reported success without a remote id — no external mapping was recorded, so the push is treated as failed"+ }+ };+ }++ return {+ outcome: "completed",+ ...(syncResult.remoteId ? { externalId: syncResult.remoteId } : {})+ };+}++/**+ * Drain the ledger for one company + integration: claim Pending (and stale+ * In Flight) operations, run the same entity syncers the entry points used+ * to call directly, and close every claimed operation out. Claimed rows are+ * grouped by (entityType, direction) so each group is one syncer batch call,+ * exactly like the pre-ledger dispatch.+ *+ * Daily-consolidation hold: when the company's posting-sync settings+ * (resolved from `integrationMetadata`) have consolidation "daily",+ * journalEntry operations are never claimed — they stay Pending for the+ * daily-consolidation cron, which pushes one aggregated provider journal+ * per posting date. Individual-mode journal operations drain normally+ * through the JournalEntrySyncer.+ *+ * A RatelimitError propagates so the caller's retry machinery applies;+ * claimed rows stay In Flight and become re-claimable once stale. Any other+ * group-level error marks that group's operations Failed and the drain+ * continues with the next group.+ */+export async function drainSyncOperations(args: {+ client: SupabaseClient<Database>;+ database: SyncContext["database"];+ companyId: string;+ integration: string;+ provider: AccountingProvider;+ /**+ * `metadata` of the companyIntegration row (already loaded by every+ * caller via getAccountingIntegration) — required so no drain path can+ * silently push daily-consolidation journal operations individually.+ */+ integrationMetadata: unknown;+}): Promise<DrainSummary> {+ const summary: DrainSummary = {+ claimed: 0,+ completed: 0,+ failed: 0,+ skipped: 0,+ groups: []+ };++ const postingSyncSettings = resolvePostingSyncSettings(+ args.integrationMetadata+ );+ // Two hold mechanisms for the consolidation cron's work:+ // - transitional: pure-daily configs (v2 shims) hold ALL journal ops by+ // entity type — covers legacy Pending rows with no granularity stamp;+ // - v3: otherwise hold only journal ops stamped granularity+ // "daily-summary"; individual ones drain right here in the event path.+ const excludeEntityTypes: AccountingEntityType[] | undefined =+ postingSyncSettings.consolidation === "daily"+ ? ["journalEntry"]+ : undefined;++ for (let iteration = 0; iteration < MAX_DRAIN_ITERATIONS; iteration++) {+ const claimed = await claimPendingOperations(args.client, {+ companyId: args.companyId,+ integration: args.integration,+ ...(excludeEntityTypes+ ? { excludeEntityTypes }+ : { holdDailySummaryJournalEntries: true })+ });++ if (claimed.error) {+ throw new Error(`Failed to claim sync operations: ${claimed.error}`);+ }++ if (claimed.data.length === 0) break;++ summary.claimed += claimed.data.length;++ // Attempt-cap backstop: claiming increments attemptCount, so a+ // crash-looping op re-claims forever without this. Park it Failed —+ // visible and retryable in Sync Activity — instead of burning another+ // provider call every drain.+ const workable: SyncOperation[] = [];+ for (const operation of claimed.data) {+ if (operation.attemptCount > MAX_SYNC_OPERATION_ATTEMPTS) {+ summary.failed++;+ await failOperation(args.client, {+ id: operation.id,+ companyId: operation.companyId,+ errorCode: "ATTEMPTS_EXHAUSTED",+ errorMessage: `Sync was attempted ${operation.attemptCount} times without reaching a terminal outcome; parked as Failed — retry manually once the underlying issue is fixed`+ });+ continue;+ }+ workable.push(operation);+ }++ const groups = groupBy(+ workable,+ (operation) => `${operation.entityType}:${operation.direction}`+ );++ for (const operations of Object.values(groups)) {+ const first = operations[0];+ if (!first) continue;++ const { entityType, direction } = first;++ try {+ const syncer = SyncFactory.getSyncer({+ database: args.database,+ companyId: args.companyId,+ provider: args.provider,+ config: args.provider.getSyncConfig(+ entityType as AccountingEntityType+ ),+ entityType: entityType as AccountingEntityType+ });++ const entityIds = operations.map((operation) => operation.entityId);+ const result =+ direction === "push-to-accounting"+ ? await syncer.pushBatchToAccounting(entityIds)+ : await syncer.pullBatchFromAccounting(entityIds);++ summary.groups.push({ entityType, direction, result });++ for (const operation of operations) {+ const syncResult = result.results.find((r) =>+ direction === "push-to-accounting"+ ? r.localId === operation.entityId+ : r.remoteId === operation.entityId+ );++ const decision = getSyncOperationCloseDecision(operation, syncResult);++ if (decision.outcome === "failed") {+ summary.failed++;+ // Structured journal pre-flight failures keep their errorCode,+ // Warning/Failed flag and metadata; other errors flatten to a+ // string exactly as before+ await failOperation(args.client, {+ id: operation.id,+ companyId: operation.companyId,+ ...decision.record+ });+ continue;+ }++ if (decision.outcome === "skipped") {+ summary.skipped++;+ await skipOperation(args.client, {+ id: operation.id,+ companyId: operation.companyId,+ reason: decision.reason+ });+ continue;+ }++ summary.completed++;+ await completeOperation(args.client, {+ id: operation.id,+ companyId: operation.companyId,+ ...(decision.externalId ? { externalId: decision.externalId } : {})+ });+ }+ } catch (error) {+ if (error instanceof RatelimitError) {+ const { retryAfterSeconds } = error.rateLimitInfo;+ console.warn(+ `[RATE LIMIT] Drain hit rate limit, will retry after ${retryAfterSeconds}s`+ );+ throw error;+ }++ const errorMessage =+ error instanceof Error ? error.message : "Unknown error";++ for (const operation of operations) {+ summary.failed++;+ await failOperation(args.client, {+ id: operation.id,+ companyId: operation.companyId,+ errorMessage+ });+ }+ }+ }+ }++ return summary;+}++// /********************************************************\+// * Daily-consolidation decisions (cron, Task 12) *+// \********************************************************/+// Pure helpers for the accounting-consolidation cron, kept in this+// import-light module (like the journal posting decisions above) so they+// are unit-testable without booting the Inngest client.++export const DAILY_CONSOLIDATION_PREFIX = "daily:";++/** "Production Event" → "production-event" (batch-key segment). */+export function getDailyConsolidationSourceTypeSlug(+ sourceType: string+): string {+ return sourceType.toLowerCase().replace(/\s+/g, "-");+}++/**+ * Batch key for one integration + posting date (+ source type since the v3+ * per-source-type partitions). Used as the marker operation's entityId AND+ * idempotencyKey, and recorded on member operations as+ * `metadata.consolidatedInto`. The sourceType-less form is the legacy key+ * shape — kept so markers completed before the partition change still+ * dedupe their date's legacy members.+ */+export function getDailyConsolidationBatchKey(+ integration: string,+ postingDate: string,+ sourceType?: string | null+): string {+ return sourceType+ ? `${DAILY_CONSOLIDATION_PREFIX}${integration}:${getDailyConsolidationSourceTypeSlug(sourceType)}:${postingDate}`+ : `${DAILY_CONSOLIDATION_PREFIX}${integration}:${postingDate}`;+}++/**+ * True when any enabled journal-represented source type is configured for+ * daily-summary granularity — the v3 trigger for the consolidation cron+ * (alongside the transitional pure-daily `consolidation` flag).+ */+export function hasDailySummarySourceTypes(+ settings: PostingSyncSettings+): boolean {+ return Object.values(settings.sourceTypes).some(+ (config) => config.enabled && config.granularity === "daily-summary"+ );+}++/** Marker operations are recognized by their entityId prefix. */+export function isDailyConsolidationMarker(entityId: string): boolean {+ return entityId.startsWith(DAILY_CONSOLIDATION_PREFIX);+}++/** YYYY-MM-DD in UTC. */+export function getUtcDateString(now: Date = new Date()): string {+ return now.toISOString().slice(0, 10);+}++/**+ * Normalize a posting date read from the database (ISO string or Date,+ * depending on driver type parsers) to YYYY-MM-DD, or null when it is+ * neither.+ */+export function toIsoDateString(value: unknown): string | null {+ if (value instanceof Date) {+ return Number.isNaN(value.getTime())+ ? null+ : value.toISOString().slice(0, 10);+ }+ if (typeof value === "string" && value.length >= 10) {+ return value.slice(0, 10);+ }+ return null;+}++/**+ * Mirror of claimPendingOperations' candidate rule so the consolidation+ * pre-scan only plans work the claim can actually take: Pending rows, plus+ * In Flight rows abandoned longer than the stale window.+ */+export function isClaimableConsolidationOperation(+ operation: Pick<SyncOperation, "status" | "lastAttemptAt">,+ now: Date = new Date()+): boolean {+ if (operation.status === "Pending") return true;+ if (operation.status !== "In Flight") return false;+ if (!operation.lastAttemptAt) return false;++ const lastAttemptMs = new Date(operation.lastAttemptAt).getTime();+ if (Number.isNaN(lastAttemptMs)) return false;+ return now.getTime() - lastAttemptMs > SYNC_OPERATION_STALE_IN_FLIGHT_MS;+}++export type ConsolidationOperation = Pick<+ SyncOperation,+ "id" | "entityId" | "metadata"+>;++export type ConsolidationGroup<T> = {+ batchKey: string;+ postingDate: string;+ /** Source type shared by the group's members; null = legacy unstamped ops. */+ sourceType: string | null;+ operations: T[];+};++export type ConsolidationPartition<T extends ConsolidationOperation> = {+ /** Batch marker rows (entityId prefixed "daily:"). */+ markers: T[];+ /** Reversal pushes — individual syncer path, never consolidated. */+ reversals: T[];+ /**+ * Consolidation members grouped per (source type, posting date) batch key+ * (dates strictly before today). Legacy ops with no sourceType stamp+ * group under the sourceType-less legacy batch key.+ */+ byGroup: Map<string, ConsolidationGroup<T>>;+ /**+ * Pushed individually through the normal syncer path: members of a batch+ * whose marker already Completed (late backdated arrivals) and+ * v3 operations stamped granularity "individual" (they normally drain in+ * the event path; the cron just pushes any it happens to claim).+ */+ individual: T[];+ /** Dated today or later — left In Flight for a later run. */+ held: T[];+ /** Journal row not found — failed. */+ missing: T[];+};++/**+ * Split claimed journalEntry operations into their consolidation buckets.+ * Reversals are detected by enqueue metadata (`reversal: true`) with the+ * ":reversal" entityId suffix as a fallback.+ */+export function partitionConsolidationOperations<+ T extends ConsolidationOperation+>(args: {+ operations: T[];+ postingDateByJournalId: ReadonlyMap<string, string>;+ today: string;+ integration: string;+ /** Batch keys whose marker is already Completed (summary already pushed). */+ consolidatedBatchKeys: ReadonlySet<string>;+}): ConsolidationPartition<T> {+ const partition: ConsolidationPartition<T> = {+ markers: [],+ reversals: [],+ byGroup: new Map(),+ individual: [],+ held: [],+ missing: []+ };++ for (const operation of args.operations) {+ if (isDailyConsolidationMarker(operation.entityId)) {+ partition.markers.push(operation);+ continue;+ }++ const { journalId, reversal } = parseJournalEntrySyncEntityId(+ operation.entityId+ );+ if (operation.metadata?.reversal === true || reversal) {+ partition.reversals.push(operation);+ continue;+ }++ // v3: individual-granularity journal ops never consolidate+ if (operation.metadata?.granularity === "individual") {+ partition.individual.push(operation);+ continue;+ }++ const postingDate = args.postingDateByJournalId.get(journalId);+ if (!postingDate) {+ partition.missing.push(operation);+ continue;+ }++ if (postingDate >= args.today) {+ partition.held.push(operation);+ continue;+ }++ const sourceType =+ typeof operation.metadata?.sourceType === "string"+ ? operation.metadata.sourceType+ : null;+ const batchKey = getDailyConsolidationBatchKey(+ args.integration,+ postingDate,+ sourceType+ );++ if (args.consolidatedBatchKeys.has(batchKey)) {+ partition.individual.push(operation);+ continue;+ }++ const group = partition.byGroup.get(batchKey);+ if (group) {+ group.operations.push(operation);+ } else {+ partition.byGroup.set(batchKey, {+ batchKey,+ postingDate,+ sourceType,+ operations: [operation]+ });+ }+ }++ return partition;+}++// /********************************************************\+// * Reconciliation comparisons (cron, Task 13) *+// \********************************************************/+// Pure helpers for the accounting-reconciliation cron (same import-light+// rationale as the consolidation decisions above).++export const MAX_RECONCILIATION_DRIFT_ENTRIES = 100;++export type ReconciliationDriftEntry =+ | { type: "missing"; externalId: string; journalId: string; amount?: number }+ | {+ type: "mismatch";+ month: string;+ carbonTotal: number;+ providerTotal: number;+ };++export type ReconciliationReport = {+ runAt: string;+ drift: ReconciliationDriftEntry[];+};++/** Sum of positive (debit) line amounts, in cents. */+export function getPositiveCents(+ lines: ReadonlyArray<{ amount: number }>+): number {+ return lines.reduce((sum, line) => {+ const cents = Math.round(line.amount * 100);+ return cents > 0 ? sum + cents : sum;+ }, 0);+}++/**+ * Debit total (cents) of what a consolidated batch actually booked: member+ * lines are netted per account first (zero nets drop), mirroring+ * aggregateJournalEntriesForDate.+ */+export function getNettedPositiveCents(+ lines: ReadonlyArray<{ accountId: string | null; amount: number }>+): number {+ let sum = 0;+ for (const amount of netJournalLinesPerAccount(lines).values()) {+ const cents = Math.round(amount * 100);+ if (cents > 0) sum += cents;+ }+ return sum;+}++/**+ * Compare per-month debit totals (cents). A month drifts when the absolute+ * difference exceeds 0.01 (strictly more than one cent — a single rounding+ * cent is tolerated). Months present on either side participate; a missing+ * side counts as zero.+ */+export function compareMonthlyTotals(args: {+ carbonCentsByMonth: ReadonlyMap<string, number>;+ providerCentsByMonth: ReadonlyMap<string, number>;+}): Array<Extract<ReconciliationDriftEntry, { type: "mismatch" }>> {+ const months = new Set([+ ...args.carbonCentsByMonth.keys(),+ ...args.providerCentsByMonth.keys()+ ]);++ const drift: Array<Extract<ReconciliationDriftEntry, { type: "mismatch" }>> =+ [];++ for (const month of [...months].sort()) {+ const carbonCents = args.carbonCentsByMonth.get(month) ?? 0;+ const providerCents = args.providerCentsByMonth.get(month) ?? 0;+ if (Math.abs(carbonCents - providerCents) > 1) {+ drift.push({+ type: "mismatch",+ month,+ carbonTotal: carbonCents / 100,+ providerTotal: providerCents / 100+ });+ }+ }++ return drift;+}++/**+ * Merge `lastReconciliation` into+ * `metadata.settings.postingSync.lastReconciliation` without clobbering any+ * other key: credentials, syncConfig, sibling settings keys and the stored+ * postingSync fields (enabled, sourceTypes, ...) all survive. Drift is+ * capped at MAX_RECONCILIATION_DRIFT_ENTRIES.+ */+export function mergePostingSyncReconciliation(+ metadata: unknown,+ report: ReconciliationReport+): Record<string, unknown> {+ const base =+ typeof metadata === "object" && metadata !== null+ ? (metadata as Record<string, unknown>)+ : {};+ const settings =+ typeof base.settings === "object" && base.settings !== null+ ? (base.settings as Record<string, unknown>)+ : {};+ const postingSync =+ typeof settings.postingSync === "object" && settings.postingSync !== null+ ? (settings.postingSync as Record<string, unknown>)+ : {};++ return {+ ...base,+ settings: {+ ...settings,+ postingSync: {+ ...postingSync,+ lastReconciliation: {+ runAt: report.runAt,+ drift: report.drift.slice(0, MAX_RECONCILIATION_DRIFT_ENTRIES)+ }+ }+ }+ };+}++// /********************************************************\+// * QBO CDC decisions (cron, Task C9) *+// \********************************************************/+// Pure helpers for the quickbooks-cdc cron (same import-light rationale as+// the consolidation and reconciliation helpers above).++/**+ * QBO CDC entity name → Carbon accounting entity type, limited to the+ * entity types the QBO integration syncs. The CDC call is asked only about+ * these names.+ */+/**+ * Normalize any ISO 8601 string (offsets included — QBO timestamps arrive+ * like "2026-07-08T13:07:59-07:00") to UTC ISO; null when unparseable.+ */+function toUtcIsoString(value: unknown): string | null {+ if (typeof value !== "string" || value.length === 0) return null;+ const parsed = new Date(value);+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();+}++export type PullCursorDecision = {+ /** UTC ISO timestamp for the listChanges call's since parameter. */+ changedSince: string;+ /** True when the wanted cursor predates the provider's lookback cap. */+ clamped: boolean;+ /** Where the pre-clamp cursor came from. */+ source: "cursor" | "connectTime" | "fallback";+};++/**+ * Resolve the since cursor for one pull-sweep run:+ *+ * - Stored cursor `metadata.settings.pullCursor` (advanced by prior runs).+ * - Default: the integration row's `updatedAt` — the closest thing to+ * connect time available (companyIntegration has no createdAt column);+ * it is at-or-after the install, so pre-connect history is never+ * pulled.+ * - Clamp: providers whose change feed is capped (QBO CDC reaches back 30+ * days; `pullLookbackDays` 29 keeps a margin) have older cursors clamped+ * and reported (`clamped`); the pre-window tail is left to two-way owner+ * semantics / a manual backfill to recover. Providers without a cap are+ * never clamped.+ */+export function getPullCursorDecision(args: {+ integrationMetadata: unknown;+ integrationUpdatedAt: string | null;+ maxLookbackDays?: number;+ now?: Date;+}): PullCursorDecision {+ const now = args.now ?? new Date();++ const settings =+ typeof args.integrationMetadata === "object" &&+ args.integrationMetadata !== null+ ? (args.integrationMetadata as { settings?: unknown }).settings+ : undefined;+ const storedCursor = toUtcIsoString(+ typeof settings === "object" && settings !== null+ ? (settings as Record<string, unknown>).pullCursor+ : undefined+ );+ const connectTime = toUtcIsoString(args.integrationUpdatedAt);++ const clampFloor =+ args.maxLookbackDays !== undefined+ ? new Date(+ now.getTime() - args.maxLookbackDays * 24 * 60 * 60_000+ ).toISOString()+ : null;++ const cursor = storedCursor ?? connectTime;+ if (!cursor) {+ return {+ changedSince: clampFloor ?? now.toISOString(),+ clamped: false,+ source: "fallback"+ };+ }++ const source = storedCursor ? ("cursor" as const) : ("connectTime" as const);+ // Both sides are toISOString output, so lexicographic order is+ // chronological order+ if (clampFloor && cursor < clampFloor) {+ return { changedSince: clampFloor, clamped: true, source };+ }+ return { changedSince: cursor, clamped: false, source };+}++/**+ * Cursor advance rule (Celigo: the cursor only moves over provably-covered+ * work): the max of the changedSince actually used and every remote+ * updated-at the provider returned — deleted stubs and dependency-skipped+ * changes included, because log-and-skip is their terminal handling. Never+ * a server time, which could outrun a lagging snapshot. The sweep calls+ * this only after every enqueue succeeded and the drain returned.+ */+export function getAdvancedPullCursor(args: {+ changedSince: string;+ lastUpdatedTimes: ReadonlyArray<string | null>;+}): string {+ let max = toUtcIsoString(args.changedSince) ?? args.changedSince;+ for (const value of args.lastUpdatedTimes) {+ const iso = toUtcIsoString(value);+ if (iso && iso > max) max = iso;+ }+ return max;+}++/**+ * Idempotency scope for one sweep-observed change: `pull:<updatedAt>` is+ * stable across cron retries — the cursor only advances after success, so+ * a retried run re-reads the same window and rebuilds the same keys,+ * absorbing into the existing ledger rows. Changes missing an updatedAt+ * fall back to the run's changedSince (still stable for unclamped runs;+ * live-row absorption and the completed-row cooldown cover the clamped+ * edge, where changedSince shifts with `now`).+ */+export function getPullIdempotencyScope(+ updatedAt: string | null,+ changedSince: string+): string {+ return `pull:${updatedAt ?? changedSince}`;+}++/**+ * Merge `cursor` into `metadata.settings.pullCursor` without clobbering+ * any sibling key — same raw-metadata read-modify-write contract as+ * mergePostingSyncReconciliation, but the cursor is a settings-level key,+ * NOT a postingSync one.+ */+export function mergePullCursor(+ metadata: unknown,+ cursor: string+): Record<string, unknown> {+ const base =+ typeof metadata === "object" && metadata !== null+ ? (metadata as Record<string, unknown>)+ : {};+ const settings =+ typeof base.settings === "object" && base.settings !== null+ ? (base.settings as Record<string, unknown>)+ : {};++ return {+ ...base,+ settings: {+ ...settings,+ pullCursor: cursor+ }+ };+}++// /********************************************************\+// * Outbound-sweep decisions (cron, v4 Pillar B) *+// \********************************************************/+// Pure helpers for the accounting-outbound-sweep cron (same import-light+// rationale as the pull-sweep cursor helpers above).++/**+ * How far back the outbound sweep diffs. Short on purpose: the sweep+ * repairs LOST EVENTS (at most as old as the outage that lost them), not+ * history — pushing a company's pre-integration past is the explicit+ * backfill's job. With a 30-minute cadence, anything inside the window+ * gets hundreds of repair chances before aging out.+ */+export const SWEEP_LOOKBACK_DAYS = 7;++/**+ * Ops parked Warning re-drive at most this many attempts (claiming+ * increments attemptCount) before a human has to act — stops a genuinely+ * broken op from churning every half hour forever.+ */+export const MAX_REDRIVE_ATTEMPTS = 5;++/**+ * Document statuses the outbound sweep treats as posted — the+ * per-provider SYNCABLE_STATUSES minus the transient "Pending"+ * (mid-posting: the post route flips Draft → Pending BEFORE the edge+ * function writes the posting journal, so diffing Pending would race the+ * same way the event path does; the document re-enters the diff as soon+ * as posting lands a terminal status).+ */+export const SWEPT_BILL_STATUSES = [+ "Open",+ "Return",+ "Debit Note Issued",+ "Partially Paid",+ "Paid",+ "Overdue"+] as const;+export const SWEPT_INVOICE_STATUSES = [+ "Submitted",+ "Partially Paid",+ "Paid",+ "Overdue"+] as const;+export const SWEPT_PAYMENT_STATUSES = ["Posted", "Voided"] as const;++/**+ * The sweep window's lower bound: `todayIso - SWEEP_LOOKBACK_DAYS`, raised+ * to the entity's syncFromDate when that is later (never push before the+ * configured start). ISO date strings, lexicographic comparison.+ */+export function getSweepFloorDate(args: {+ todayIso: string;+ syncFromDate?: string | null;+}): string {+ const lookbackFloor = parseDate(args.todayIso)+ .subtract({ days: SWEEP_LOOKBACK_DAYS })+ .toString();+ const syncFrom = args.syncFromDate?.slice(0, 10);+ return syncFrom && syncFrom > lookbackFloor ? syncFrom : lookbackFloor;+}++/**+ * The outbound sweep's document diff rule. Enqueue iff nothing exists+ * remotely (no mapping), nothing is about to run (no live op), and+ * nothing parked it: no rows at all is a pure lost event, and a latest+ * row of Completed is a phantom success (a truthful Completed push+ * implies a mapping). A latest row of Skipped/Warning/Failed/Excluded+ * means the entity is deliberately parked — the capped re-drive rules or+ * a human own it, not the diff (re-enqueueing those every sweep would+ * churn forever).+ */+export function shouldEnqueueMissingDocument(args: {+ hasMapping: boolean;+ hasLiveOperation: boolean;+ latestOperationStatus: string | null;+}): boolean {+ if (args.hasMapping || args.hasLiveOperation) return false;+ return (+ args.latestOperationStatus === null ||+ args.latestOperationStatus === "Completed"+ );+}++// /********************************************************\+// * Tie-out computations (cron, v4 Pillar E) *+// \********************************************************/+// Pure helpers for the accounting-reconciliation cron's per-period ×+// per-account tie-out pass (v3 spec §5). Kept in this import-light module+// so they are unit-testable without booting the Inngest client (same+// rationale as the sweep helpers above); tests live in+// accounting-reconciliation.test.ts.++/**+ * Default tie-out lookback when the company has no+ * `postingSync.syncFromDate` — matches the reconciliation presence window.+ */+export const TIE_OUT_DEFAULT_LOOKBACK_DAYS = 90;++/**+ * Lower bound of the tie-out scope: `postingSync.syncFromDate` when set,+ * else `todayIso - TIE_OUT_DEFAULT_LOOKBACK_DAYS`. ISO date strings.+ */+export function getTieOutScopeStart(args: {+ todayIso: string;+ syncFromDate?: string | null;+}): string {+ const syncFrom = args.syncFromDate?.slice(0, 10);+ if (syncFrom) return syncFrom;+ return parseDate(args.todayIso)+ .subtract({ days: TIE_OUT_DEFAULT_LOOKBACK_DAYS })+ .toString();+}++/**+ * The five tie-out amount buckets a posted journal's debit-signed line+ * amounts land in, based on its sync disposition (spec §5 internal+ * completeness: carbonPosted = synced + docBacked + excluded + pending ++ * blocked).+ */+export type TieOutBucket =+ | "synced"+ | "docBacked"+ | "excluded"+ | "pending"+ | "blocked";++/**+ * Delivery order, LEAST delivered first — the fold order for a journal+ * with both a normal and a :reversal operation.+ */+export const TIE_OUT_BUCKETS_LEAST_DELIVERED_FIRST: readonly TieOutBucket[] = [+ "blocked",+ "pending",+ "excluded",+ "docBacked",+ "synced"+];++export const DOC_BACKED_ERROR_CODE = "DOC_BACKED";++/**+ * Map one journalEntry operation's disposition onto its tie-out bucket:+ *+ * - Completed → synced;+ * - Excluded/DOC_BACKED → docBacked only while the backing document is+ * actually delivered (its own op Completed, or an external mapping+ * exists), else pending — a doc-backed journal is only "in the GL" if+ * the document really synced (spec §5);+ * - other Excluded → excluded;+ * - Pending / In Flight → pending;+ * - Failed / Warning / Skipped → blocked.+ */+export function getOperationTieOutBucket(+ operation: Pick<SyncOperation, "status" | "errorCode">,+ args: { docBackedDelivered: boolean }+): TieOutBucket {+ switch (operation.status) {+ case "Completed":+ return "synced";+ case "Excluded":+ if (operation.errorCode === DOC_BACKED_ERROR_CODE) {+ return args.docBackedDelivered ? "docBacked" : "pending";+ }+ return "excluded";+ case "Pending":+ case "In Flight":+ return "pending";+ default:+ // Failed | Warning | Skipped+ return "blocked";+ }+}++/**+ * Fold a journal's per-operation buckets into ONE bucket for its full+ * line amounts: the LEAST-delivered bucket wins (blocked > pending >+ * excluded > docBacked > synced). A journal with no operations at all is+ * pending — it has been posted but nothing has decided it yet.+ */+export function foldTieOutBuckets(+ buckets: readonly TieOutBucket[]+): TieOutBucket {+ let least: TieOutBucket | null = null;+ for (const bucket of buckets) {+ if (+ least === null ||+ TIE_OUT_BUCKETS_LEAST_DELIVERED_FIRST.indexOf(bucket) <+ TIE_OUT_BUCKETS_LEAST_DELIVERED_FIRST.indexOf(least)+ ) {+ least = bucket;+ }+ }+ return least ?? "pending";+}++/**+ * Latest operation per entityId (by createdAt). Terminal re-dispositions+ * insert new rows for the same tuple over time; the newest row is the+ * journal's current disposition (mirrors getLatestOperationForTuple in+ * the operations service).+ */+export function getLatestOperationsByEntityId<+ T extends Pick<SyncOperation, "entityId" | "createdAt">+>(operations: readonly T[]): Map<string, T> {+ const latest = new Map<string, T>();+ for (const operation of operations) {+ const existing = latest.get(operation.entityId);+ if (!existing || operation.createdAt > existing.createdAt) {+ latest.set(operation.entityId, operation);+ }+ }+ return latest;+}++export type TieOutPeriod = {+ id: string;+ /** YYYY-MM-DD (normalize DATE reads before calling). */+ startDate: string;+ /** YYYY-MM-DD. */+ endDate: string;+};++/**+ * The accounting period whose [startDate, endDate] contains the date+ * (inclusive), or null. ISO date strings compare lexicographically.+ */+export function findAccountingPeriodForDate<T extends TieOutPeriod>(+ periods: readonly T[],+ isoDate: string | null+): T | null {+ if (!isoDate) return null;+ const day = isoDate.slice(0, 10);+ return (+ periods.find(+ (period) =>+ period.startDate.slice(0, 10) <= day &&+ day <= period.endDate.slice(0, 10)+ ) ?? null+ );+}++/** `metadata.backingDocument.entityType` of a DOC_BACKED disposition, or null. */+export function getBackingDocumentEntityType(+ metadata: Record<string, unknown> | null | undefined+): string | null {+ const backing = metadata?.backingDocument;+ if (typeof backing !== "object" || backing === null) return null;+ const entityType = (backing as Record<string, unknown>).entityType;+ return typeof entityType === "string" ? entityType : null;+}++/**+ * A DOC_BACKED journal counts as delivered only while its backing+ * document's own operation is Completed OR the document already carries an+ * external mapping (a truthful Completed push implies one; the mapping+ * also covers documents linked outside the ledger, e.g. backfills).+ */+export function isBackingDocumentDelivered(args: {+ latestOperationStatus: string | null;+ hasExternalMapping: boolean;+}): boolean {+ return args.latestOperationStatus === "Completed" || args.hasExternalMapping;+}++/**+ * Fold account-mapping rows (entityType "account") into a reverse index:+ * remote account ref → Carbon account.id. Both the mapping's externalId+ * (QBO AccountRef.value = provider account id) and its metadata+ * externalCode (Xero AccountCode / Rillet account_code) are indexed —+ * providers address journal lines by different refs. Consolidation+ * mappings are many-to-one (several Carbon accounts → one provider+ * account); the first row wins, so pass rows in a stable order.+ */+export function buildRemoteAccountRefIndex(+ mappings: ReadonlyArray<{+ entityId: string;+ externalId: string | null;+ metadata: unknown;+ }>+): Map<string, string> {+ const index = new Map<string, string>();+ for (const mapping of mappings) {+ const refs: Array<string | null> = [mapping.externalId];+ if (+ typeof mapping.metadata === "object" &&+ mapping.metadata !== null &&+ !Array.isArray(mapping.metadata)+ ) {+ const externalCode = (mapping.metadata as Record<string, unknown>)+ .externalCode;+ if (typeof externalCode === "string") refs.push(externalCode);+ }+ for (const ref of refs) {+ if (!ref) continue;+ if (!index.has(ref)) index.set(ref, mapping.entityId);+ }+ }+ return index;+}++export type TieOutCellCents = {+ carbonPostedCents: number;+ syncedCents: number;+ docBackedCents: number;+ excludedCents: number;+ pendingCents: number;+ blockedCents: number;+ /** null = no provider fetch succeeded for this cell. */+ providerCents: number | null;+};++/**+ * The two tie-out invariants as deltas (cents):+ * internal = carbonPosted − (synced+docBacked+excluded+pending+blocked);+ * external = synced − provider (null while providerCents is null).+ */+export function computeTieOutDeltas(cell: TieOutCellCents): {+ internalDeltaCents: number;+ externalDeltaCents: number | null;+} {+ const accounted =+ cell.syncedCents ++ cell.docBackedCents ++ cell.excludedCents ++ cell.pendingCents ++ cell.blockedCents;+ return {+ internalDeltaCents: cell.carbonPostedCents - accounted,+ externalDeltaCents:+ cell.providerCents === null ? null : cell.syncedCents - cell.providerCents+ };+}diff --git a/packages/jobs/src/inngest/functions/integrations/index.ts b/packages/jobs/src/inngest/functions/integrations/index.tsindex 1da35552ab..0725465cb2 100644--- a/packages/jobs/src/inngest/functions/integrations/index.ts+++ b/packages/jobs/src/inngest/functions/integrations/index.ts@@ -1,4 +1,8 @@export { accountingBackfillFunction } from "./accounting-backfill";+export { accountingConsolidationFunction } from "./accounting-consolidation";+export { accountingOutboundSweepFunction } from "./accounting-outbound-sweep";+export { accountingPullSweepFunction } from "./accounting-pull-sweep";+export { accountingReconciliationFunction } from "./accounting-reconciliation";export { jiraSyncFunction, syncIssueFromJiraSchema } from "./jira";export { linearSyncFunction, syncIssueFromLinearSchema } from "./linear";export { onshapeBackfillFunction } from "./onshape-backfill";diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts b/packages/jobs/src/inngest/functions/integrations/reconcile-executor.tsnew file mode 100644index 0000000000..a32cadbaf6--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/reconcile-executor.ts@@ -0,0 +1,436 @@+/**+ * v5 reconciler executor (spec D2): load state for a batch of refs — one+ * query per concern, never per entity — run the pure decision core over+ * each, and apply the actions through the existing ledger primitives.+ *+ * Callers (the event handler's hint batches, the outbound sweep's window+ * pages) stay batch-shaped end to end: snapshots, ledger state, mappings and+ * the bill backing-journal check are each ONE query per entity type per+ * call. Enqueues carry trigger "reconcile" — state-derived decisions are+ * never cooldown-gated (idempotence replaces the cooldown).+ */+import type { Database } from "@carbon/database";+import {+ PAYMENT_PUSH_PROVIDERS,+ type PostingSyncSettings,+ type ProviderID,+ resolvePostingSyncSettings,+ resolveSyncConfig,+ type SyncContext,+ transitionOperation+} from "@carbon/ee/accounting";+import type { SupabaseClient } from "@supabase/supabase-js";+import {+ enqueueSyncOperations,+ insertTerminalSyncOperations,+ isJournalEntryPostingEnabled,+ resolvePaymentJournalFamily,+ type SyncOperationRequest,+ type TerminalSyncOperationRequest+} from "./accounting-sync-operations";+import {+ computeReconcileDecision,+ type ReconcileEntityInput,+ type ReconcileEntityType,+ type ReconcileLatestOperation,+ type ReconcileRef+} from "./reconcile";++const SNAPSHOT_TABLES: Record<+ ReconcileEntityType,+ { table: string; columns: string }+> = {+ journalEntry: {+ table: "journal",+ columns: "id, status, sourceType, reversalOfId"+ },+ bill: { table: "purchaseInvoice", columns: "id, status, updatedAt" },+ invoice: { table: "salesInvoice", columns: "id, status, updatedAt" },+ payment: { table: "payment", columns: "id, status, updatedAt" },+ customer: { table: "customer", columns: "id, updatedAt" },+ vendor: { table: "supplier", columns: "id, updatedAt" },+ item: { table: "item", columns: "id, updatedAt" },+ purchaseOrder: { table: "purchaseOrder", columns: "id, updatedAt" },+ salesOrder: { table: "salesOrder", columns: "id, updatedAt" }+};++/** Entity types whose decision consults the push mapping. */+const MAPPED_TYPES: ReadonlySet<ReconcileEntityType> = new Set([+ "bill",+ "invoice",+ "customer",+ "vendor",+ "item",+ "purchaseOrder",+ "salesOrder"+]);++export type ReconcileSummary = {+ considered: number;+ enqueued: number;+ recordedTerminal: number;+ redriven: number;+ nothing: number;+ errors: number;+};++const emptySummary = (): ReconcileSummary => ({+ considered: 0,+ enqueued: 0,+ recordedTerminal: 0,+ redriven: 0,+ nothing: 0,+ errors: 0+});++type SnapshotRow = {+ id: string;+ status?: string | null;+ sourceType?: string | null;+ reversalOfId?: string | null;+ updatedAt?: string | null;+};++type LedgerRow = {+ id: string;+ entityId: string;+ status: string;+ errorCode: string | null;+ attemptCount: number;+ createdAt: string;+ metadata: Record<string, unknown> | null;+};++/**+ * Reconcile a batch of refs for one company + provider. Refs may span+ * entity types; state is loaded per type in batches. Returns counts only —+ * the ledger rows ARE the record.+ */+export async function reconcileEntities(args: {+ client: SupabaseClient<Database>;+ database: SyncContext["database"];+ companyId: string;+ providerId: string;+ integrationMetadata: unknown;+ createdBy: string;+ /** Idempotency scope for this reconcile occasion (event id / run id). */+ scope: string;+ refs: ReconcileRef[];+}): Promise<ReconcileSummary> {+ const summary = emptySummary();+ if (args.refs.length === 0) return summary;++ const settings = resolvePostingSyncSettings(args.integrationMetadata);+ const syncConfig = resolveSyncConfig(args.integrationMetadata);+ // Always-on: automated postings sync whenever an accounting integration is+ // connected — the old settings.enabled master gate is gone. The entity flag+ // now defaults true and provider configs force it on.+ const journalEntryPushEnabled = isJournalEntryPostingEnabled(+ args.integrationMetadata+ );++ const byType = new Map<ReconcileEntityType, string[]>();+ for (const ref of args.refs) {+ const ids = byType.get(ref.entityType);+ if (ids) {+ if (!ids.includes(ref.entityId)) ids.push(ref.entityId);+ } else {+ byType.set(ref.entityType, [ref.entityId]);+ }+ }++ const enqueueRequests: SyncOperationRequest[] = [];+ const terminalRequests: TerminalSyncOperationRequest[] = [];+ const redriveOperationIds: string[] = [];++ for (const [entityType, ids] of byType) {+ summary.considered += ids.length;++ const snapshotSource = SNAPSHOT_TABLES[entityType];+ const snapshots = await args.client+ .from(snapshotSource.table as "journal")+ .select(snapshotSource.columns)+ .eq("companyId", args.companyId)+ .in("id", ids);+ if (snapshots.error) {+ throw new Error(+ `Failed to load ${entityType} snapshots: ${snapshots.error.message}`+ );+ }+ const snapshotById = new Map<string, SnapshotRow>(+ ((snapshots.data ?? []) as unknown as SnapshotRow[]).map((row) => [+ row.id,+ row+ ])+ );++ // Ledger state — one query covering plain ids and (for journals) the+ // `:reversal` twins.+ const ledgerEntityIds =+ entityType === "journalEntry"+ ? ids.flatMap((id) => [id, `${id}:reversal`])+ : ids;+ const operations = await args.client+ .from("accountingSyncOperation")+ .select(+ "id, entityId, status, errorCode, attemptCount, createdAt, metadata"+ )+ .eq("companyId", args.companyId)+ .eq("integration", args.providerId)+ .eq("entityType", entityType)+ .eq("direction", "push-to-accounting")+ .in("entityId", ledgerEntityIds);+ if (operations.error) {+ throw new Error(+ `Failed to load ${entityType} operations: ${operations.error.message}`+ );+ }+ const coveredEntityIds = new Set<string>();+ const liveByEntity = new Set<string>();+ const latestByEntity = new Map<string, ReconcileLatestOperation>();+ const targetDocumentByEntity = new Map<string, string>();+ for (const operation of (operations.data ?? []) as LedgerRow[]) {+ coveredEntityIds.add(operation.entityId);+ if (operation.status === "Pending" || operation.status === "In Flight") {+ liveByEntity.add(operation.entityId);+ }+ const latest = latestByEntity.get(operation.entityId);+ if (!latest || operation.createdAt > latest.createdAt) {+ latestByEntity.set(operation.entityId, {+ id: operation.id,+ status: operation.status,+ errorCode: operation.errorCode,+ attemptCount: operation.attemptCount,+ createdAt: operation.createdAt+ });+ const targetDocumentId = operation.metadata?.targetDocumentId;+ if (typeof targetDocumentId === "string") {+ targetDocumentByEntity.set(operation.entityId, targetDocumentId);+ } else {+ targetDocumentByEntity.delete(operation.entityId);+ }+ }+ }++ // Push mappings (documents + master data).+ const mappingByEntity = new Map<+ string,+ { externalId: string | null; lastSyncedAt: string | null }+ >();+ if (MAPPED_TYPES.has(entityType)) {+ const mappings = await args.client+ .from("externalIntegrationMapping")+ .select("entityId, externalId, lastSyncedAt")+ .eq("companyId", args.companyId)+ .eq("integration", args.providerId)+ .eq("entityType", entityType)+ .in("entityId", ids);+ if (mappings.error) {+ throw new Error(+ `Failed to load ${entityType} mappings: ${mappings.error.message}`+ );+ }+ for (const row of mappings.data ?? []) {+ mappingByEntity.set(row.entityId, {+ externalId: row.externalId,+ lastSyncedAt: row.lastSyncedAt+ });+ }+ }++ // Bills parked Warning UNMAPPED_ACCOUNTS: does the posted "Purchase+ // Invoice" journal now exist? One batched join for just those bills.+ const backingJournalByBill = new Set<string>();+ if (entityType === "bill") {+ const parkedBillIds = ids.filter((id) => {+ const latest = latestByEntity.get(id);+ return (+ latest?.status === "Warning" &&+ latest.errorCode === "UNMAPPED_ACCOUNTS"+ );+ });+ if (parkedBillIds.length > 0) {+ const journalLines = await args.database+ .selectFrom("journalLine")+ .innerJoin("journal", "journal.id", "journalLine.journalId")+ .select("journalLine.documentId")+ .distinct()+ .where("journalLine.companyId", "=", args.companyId)+ .where("journalLine.documentId", "in", parkedBillIds)+ .where("journal.sourceType", "=", "Purchase Invoice")+ .where("journal.status", "=", "Posted")+ .execute();+ for (const row of journalLines) {+ if (row.documentId) backingJournalByBill.add(row.documentId);+ }+ }+ }++ // Payments parked Warning UNSYNCED_DOCUMENT: has the settled document+ // (op metadata.targetDocumentId) since gained a provider mapping? One+ // batched lookup across invoice + bill mappings for just those targets.+ const mappedSettledTargets = new Set<string>();+ if (entityType === "payment") {+ const parkedTargets = [+ ...new Set(+ ids.flatMap((id) => {+ const latest = latestByEntity.get(id);+ const target = targetDocumentByEntity.get(id);+ return latest?.status === "Warning" &&+ latest.errorCode === "UNSYNCED_DOCUMENT" &&+ target+ ? [target]+ : [];+ })+ )+ ];+ if (parkedTargets.length > 0) {+ const targetMappings = await args.client+ .from("externalIntegrationMapping")+ .select("entityId")+ .eq("companyId", args.companyId)+ .eq("integration", args.providerId)+ .in("entityType", ["invoice", "bill"])+ .not("externalId", "is", null)+ .in("entityId", parkedTargets);+ if (targetMappings.error) {+ throw new Error(+ `Failed to load settled-document mappings: ${targetMappings.error.message}`+ );+ }+ for (const row of targetMappings.data ?? []) {+ mappedSettledTargets.add(row.entityId);+ }+ }+ }++ const entityPushEnabled = isEntityPushEnabled(syncConfig, entityType);++ for (const entityId of ids) {+ const snapshot = snapshotById.get(entityId) ?? null;++ // Payment-source journals resolve the AR/AP side only when the family+ // modes diverge (matches planJournalPostingOperation exactly).+ let paymentFamily: "ar" | "ap" | null = null;+ if (+ entityType === "journalEntry" &&+ snapshot?.sourceType === "Payment" &&+ settings.families.ar !== settings.families.ap+ ) {+ paymentFamily = await resolvePaymentJournalFamily(args.client, {+ companyId: args.companyId,+ journalId: entityId+ });+ }++ const input: ReconcileEntityInput = {+ entityType,+ entityId,+ snapshot,+ hasMappingWithExternalId:+ mappingByEntity.get(entityId)?.externalId != null,+ lastSyncedAt: mappingByEntity.get(entityId)?.lastSyncedAt ?? null,+ hasLiveOperation: liveByEntity.has(entityId),+ latestOperation: latestByEntity.get(entityId) ?? null,+ ...(entityType === "journalEntry"+ ? {+ journalCoverage: {+ normalCovered: coveredEntityIds.has(entityId),+ reversalCovered: coveredEntityIds.has(`${entityId}:reversal`)+ }+ }+ : {}),+ ...(entityType === "bill"+ ? { hasPostedBackingJournal: backingJournalByBill.has(entityId) }+ : {}),+ ...(entityType === "payment"+ ? {+ settledDocumentMapped: (() => {+ const target = targetDocumentByEntity.get(entityId);+ return target ? mappedSettledTargets.has(target) : false;+ })()+ }+ : {}),+ context: {+ journalEntryPushEnabled,+ entityPushEnabled,+ providerSupportsPaymentPush: PAYMENT_PUSH_PROVIDERS.has(+ args.providerId as ProviderID+ ),+ settings: settings as PostingSyncSettings,+ docSync: {+ invoiceEnabled: syncConfig.entities.invoice.enabled,+ billEnabled: syncConfig.entities.bill.enabled+ },+ inventoryAdjustmentEnabled:+ syncConfig.entities.inventoryAdjustment.enabled,+ paymentFamily+ }+ };++ const decision = computeReconcileDecision(input);+ for (const action of decision.actions) {+ if (action.kind === "enqueue") enqueueRequests.push(action.request);+ else if (action.kind === "record-terminal")+ terminalRequests.push(action.request);+ else if (action.kind === "re-drive")+ redriveOperationIds.push(action.operationId);+ else summary.nothing++;+ }+ }+ }++ const enqueueOutcomes = await enqueueSyncOperations(args.client, {+ companyId: args.companyId,+ integration: args.providerId,+ trigger: "reconcile",+ createdBy: args.createdBy,+ scope: args.scope,+ requests: enqueueRequests+ });+ for (const outcome of enqueueOutcomes) {+ if (outcome.outcome === "enqueued") summary.enqueued++;+ else if (outcome.outcome === "error") summary.errors++;+ }++ const terminalOutcomes = await insertTerminalSyncOperations(args.client, {+ companyId: args.companyId,+ integration: args.providerId,+ trigger: "reconcile",+ createdBy: args.createdBy,+ scope: args.scope,+ requests: terminalRequests+ });+ for (const outcome of terminalOutcomes) {+ if (outcome.outcome === "enqueued") summary.recordedTerminal++;+ else if (outcome.outcome === "error") summary.errors++;+ }++ for (const operationId of redriveOperationIds) {+ const transitioned = await transitionOperation(args.client, {+ id: operationId,+ companyId: args.companyId,+ to: "Pending",+ userId: args.createdBy+ });+ if (transitioned.error) {+ summary.errors++;+ console.warn(+ `[RECONCILE] ${args.companyId}/${args.providerId}: failed to re-drive op ${operationId}: ${transitioned.error}`+ );+ } else {+ summary.redriven++;+ }+ }++ return summary;+}++function isEntityPushEnabled(+ syncConfig: ReturnType<typeof resolveSyncConfig>,+ entityType: ReconcileEntityType+): boolean {+ const config = syncConfig.entities[entityType];+ if (!config) return false;+ return config.enabled && config.direction !== "pull-from-accounting";+}diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile-golden.test.ts b/packages/jobs/src/inngest/functions/integrations/reconcile-golden.test.tsnew file mode 100644index 0000000000..3b8b8bff63--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/reconcile-golden.test.ts@@ -0,0 +1,621 @@+/**+ * v5 golden decision matrix (spec Step A):+ * .ai/specs/2026-08-12-accounting-sync-reconciler-unification.md+ *+ * Pins the translation from the LEGACY decision sites (event-shaped+ * getJournalPostingDecision / getPaymentPushDecision, the sweep's+ * shouldEnqueueMissingDocument + re-drive conditions, the master-data+ * enqueue-always rule bounded by the cooldown) onto the state-shaped+ * computeReconcileDecision. Where the two deliberately differ, the scenario+ * says so explicitly — every difference is a documented fix, never an+ * accident:+ *+ * FIX-1 Draft/mid-posting documents reconcile to nothing (legacy event+ * path enqueued them, producing drain-skip churn and the F5 race).+ * FIX-2 A parked Failed/Warning document re-enqueues only when the row+ * actually changed after the failure (legacy event path retried on+ * ANY touch; the sweep never did).+ * FIX-3 Master data uses updatedAt vs lastSyncedAt instead of the 60s+ * completed-row cooldown (no window to swallow a real change, no+ * window to wait out for a no-op).+ * FIX-4 A Voided payment with prior operations records nothing (v1 has no+ * void echo — the legacy transition enqueue only produced a Skipped+ * park).+ *+ * The journal POLICY routing itself (push vs Excluded vs Warning, metadata,+ * granularity) is shared by construction — both the legacy path and the+ * reconciler call planJournalPostingFromState — so these tests pin the+ * GATE translation (which states produce a plan at all), not the policy+ * table.+ */+import { resolvePostingSyncSettings } from "@carbon/ee/accounting";+import { describe, expect, it } from "vitest";+import {+ getJournalPostingDecision,+ shouldEnqueueMissingDocument+} from "./accounting-sync-operations";+import {+ computeReconcileDecision,+ type ReconcileContext,+ type ReconcileEntityInput+} from "./reconcile";++const settings = resolvePostingSyncSettings({+ settings: { postingSync: { enabled: true } }+});++const baseContext: ReconcileContext = {+ journalEntryPushEnabled: true,+ entityPushEnabled: true,+ providerSupportsPaymentPush: true,+ settings,+ docSync: { invoiceEnabled: true, billEnabled: true },+ inventoryAdjustmentEnabled: false,+ paymentFamily: null+};++function input(+ overrides: Partial<ReconcileEntityInput> & {+ entityType: ReconcileEntityInput["entityType"];+ }+): ReconcileEntityInput {+ return {+ entityId: "entity_1",+ snapshot: null,+ hasMappingWithExternalId: false,+ lastSyncedAt: null,+ hasLiveOperation: false,+ latestOperation: null,+ context: baseContext,+ ...overrides+ };+}++function kinds(decision: ReturnType<typeof computeReconcileDecision>) {+ return decision.actions.map((action) => action.kind);+}++// ── Journals ────────────────────────────────────────────────────────────────++describe("golden: journals", () => {+ it("posted + uncovered ⇔ legacy INSERT-born-Posted enqueue", () => {+ // Legacy gate:+ expect(+ getJournalPostingDecision({+ operation: "INSERT",+ recordId: "je_1",+ new: { status: "Posted", reversalOfId: null },+ old: null+ }).action+ ).toBe("enqueue");++ // Reconcile (Purchase Receipt is push-enabled by policy default):+ const decision = computeReconcileDecision(+ input({+ entityType: "journalEntry",+ entityId: "je_1",+ snapshot: { status: "Posted", sourceType: "Purchase Receipt" },+ journalCoverage: { normalCovered: false, reversalCovered: false }+ })+ );+ expect(kinds(decision)).toEqual(["enqueue"]);+ const action = decision.actions[0];+ if (action?.kind === "enqueue") {+ expect(action.request.entityId).toBe("je_1");+ expect(action.request.metadata).toMatchObject({+ sourceType: "Purchase Receipt"+ });+ }+ });++ it("doc-backed source type ⇔ legacy terminal Excluded", () => {+ const decision = computeReconcileDecision(+ input({+ entityType: "journalEntry",+ entityId: "je_1",+ snapshot: { status: "Posted", sourceType: "Purchase Invoice" },+ journalCoverage: { normalCovered: false, reversalCovered: false }+ })+ );+ expect(kinds(decision)).toEqual(["record-terminal"]);+ const action = decision.actions[0];+ if (action?.kind === "record-terminal") {+ expect(action.request.status).toBe("Excluded");+ expect(action.request.errorCode).toBe("DOC_BACKED");+ }+ });++ it("posted + covered ⇔ legacy same-status-UPDATE skip", () => {+ expect(+ getJournalPostingDecision({+ operation: "UPDATE",+ recordId: "je_1",+ new: { status: "Posted" },+ old: { status: "Posted" }+ }).action+ ).toBe("skip");++ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "journalEntry",+ entityId: "je_1",+ snapshot: { status: "Posted", sourceType: "Purchase Receipt" },+ journalCoverage: { normalCovered: true, reversalCovered: false }+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("reversed + only reversal uncovered ⇔ legacy Reversed-transition enqueue of the :reversal id", () => {+ expect(+ getJournalPostingDecision({+ operation: "UPDATE",+ recordId: "je_1",+ new: { status: "Reversed" },+ old: { status: "Posted" }+ })+ ).toMatchObject({ action: "enqueue", entityId: "je_1:reversal" });++ const decision = computeReconcileDecision(+ input({+ entityType: "journalEntry",+ entityId: "je_1",+ snapshot: { status: "Reversed", sourceType: "Purchase Receipt" },+ journalCoverage: { normalCovered: true, reversalCovered: false }+ })+ );+ expect(kinds(decision)).toEqual(["enqueue"]);+ const action = decision.actions[0];+ if (action?.kind === "enqueue") {+ expect(action.request.entityId).toBe("je_1:reversal");+ expect(action.request.metadata).toMatchObject({ reversal: true });+ }+ });++ it("reversed + fully uncovered produces BOTH dispositions (sweep-heal semantics)", () => {+ const decision = computeReconcileDecision(+ input({+ entityType: "journalEntry",+ entityId: "je_1",+ snapshot: { status: "Reversed", sourceType: "Purchase Receipt" },+ journalCoverage: { normalCovered: false, reversalCovered: false }+ })+ );+ expect(kinds(decision)).toEqual(["enqueue", "enqueue"]);+ });++ it("reversal entry row ⇔ legacy reversalOfId-INSERT skip", () => {+ expect(+ getJournalPostingDecision({+ operation: "INSERT",+ recordId: "je_2",+ new: { status: "Posted", reversalOfId: "je_1" },+ old: null+ }).action+ ).toBe("skip");++ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "journalEntry",+ entityId: "je_2",+ snapshot: {+ status: "Posted",+ sourceType: "Purchase Receipt",+ reversalOfId: "je_1"+ }+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("draft journal ⇔ legacy draft-INSERT skip", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "journalEntry",+ entityId: "je_1",+ snapshot: { status: "Draft", sourceType: "Purchase Receipt" }+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("posting sync disabled ⇔ legacy handler gate skip", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "journalEntry",+ entityId: "je_1",+ snapshot: { status: "Posted", sourceType: "Purchase Receipt" },+ journalCoverage: { normalCovered: false, reversalCovered: false },+ context: { ...baseContext, journalEntryPushEnabled: false }+ })+ )+ )+ ).toEqual(["nothing"]);+ });+});++// ── Documents ───────────────────────────────────────────────────────────────++describe("golden: documents", () => {+ const openBill = { status: "Open", updatedAt: "2026-08-12T01:00:00Z" };++ it("posted + lost event (no ops, no mapping) ⇔ sweep diff enqueue", () => {+ expect(+ shouldEnqueueMissingDocument({+ hasMapping: false,+ hasLiveOperation: false,+ latestOperationStatus: null+ })+ ).toBe(true);++ expect(+ kinds(+ computeReconcileDecision(+ input({ entityType: "bill", snapshot: openBill })+ )+ )+ ).toEqual(["enqueue"]);+ });++ it("phantom success (latest Completed, no mapping) ⇔ sweep diff enqueue", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "bill",+ snapshot: openBill,+ latestOperation: {+ id: "op_1",+ status: "Completed",+ errorCode: null,+ attemptCount: 1,+ createdAt: "2026-08-12T00:00:00Z"+ }+ })+ )+ )+ ).toEqual(["enqueue"]);+ });++ it("mapped ⇔ sweep diff nothing", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "bill",+ snapshot: openBill,+ hasMappingWithExternalId: true+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("live operation ⇔ absorbed", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "bill",+ snapshot: openBill,+ hasLiveOperation: true+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("Warning UNMAPPED_ACCOUNTS + backing journal now posted ⇔ sweep re-drive", () => {+ const decision = computeReconcileDecision(+ input({+ entityType: "bill",+ snapshot: openBill,+ hasPostedBackingJournal: true,+ latestOperation: {+ id: "op_1",+ status: "Warning",+ errorCode: "UNMAPPED_ACCOUNTS",+ attemptCount: 2,+ createdAt: "2026-08-12T00:00:00Z"+ }+ })+ );+ expect(decision.actions).toEqual([+ { kind: "re-drive", operationId: "op_1" }+ ]);+ });++ it("re-drive respects the attempt cap and the missing-journal condition", () => {+ const parked = {+ id: "op_1",+ status: "Warning",+ errorCode: "UNMAPPED_ACCOUNTS",+ attemptCount: 5,+ createdAt: "2026-08-12T00:00:00Z"+ };+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "bill",+ snapshot: { status: "Open", updatedAt: "2026-08-11T00:00:00Z" },+ hasPostedBackingJournal: true,+ latestOperation: parked+ })+ )+ )+ ).toEqual(["nothing"]);+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "bill",+ snapshot: { status: "Open", updatedAt: "2026-08-11T00:00:00Z" },+ hasPostedBackingJournal: false,+ latestOperation: { ...parked, attemptCount: 1 }+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("FIX-1: draft and mid-posting documents reconcile to nothing", () => {+ for (const status of ["Draft", "Pending"]) {+ expect(+ kinds(+ computeReconcileDecision(+ input({ entityType: "bill", snapshot: { status } })+ )+ )+ ).toEqual(["nothing"]);+ }+ });++ it("FIX-2: a parked Failed document re-enqueues only when edited after the failure", () => {+ const failed = {+ id: "op_1",+ status: "Failed",+ errorCode: null,+ attemptCount: 1,+ createdAt: "2026-08-12T00:00:00Z"+ };+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "bill",+ snapshot: { status: "Open", updatedAt: "2026-08-12T01:00:00Z" },+ latestOperation: failed+ })+ )+ )+ ).toEqual(["enqueue"]);+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "bill",+ snapshot: { status: "Open", updatedAt: "2026-08-11T00:00:00Z" },+ latestOperation: failed+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("push disabled ⇔ config-gate nothing", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "invoice",+ snapshot: { status: "Submitted" },+ context: { ...baseContext, entityPushEnabled: false }+ })+ )+ )+ ).toEqual(["nothing"]);+ });+});++// ── Payments ────────────────────────────────────────────────────────────────++describe("golden: payments", () => {+ it("posted + no ops ⇔ legacy Posted-transition enqueue / sweep no-op-rows rule", () => {+ // Legacy oracle (getPaymentPushDecision, deleted with v5): a transition+ // to Posted enqueued the payment row id — state-shaped, that is a+ // Posted payment with no recorded push operation.+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "payment",+ entityId: "pay_1",+ snapshot: { status: "Posted" }+ })+ )+ )+ ).toEqual(["enqueue"]);+ });++ it("posted with a recorded op ⇔ covered", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "payment",+ snapshot: { status: "Posted" },+ latestOperation: {+ id: "op_1",+ status: "Skipped",+ errorCode: null,+ attemptCount: 1,+ createdAt: "2026-08-12T00:00:00Z"+ }+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("draft ⇔ legacy draft-INSERT skip", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({ entityType: "payment", snapshot: { status: "Draft" } })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("provider without payment push ⇔ nothing", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "payment",+ snapshot: { status: "Posted" },+ context: { ...baseContext, providerSupportsPaymentPush: false }+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("re-drives a payment parked UNSYNCED_DOCUMENT once its settled document is mapped", () => {+ // The dependency-chain heal: invoice fails -> payment parks -> invoice+ // syncs -> the payment must follow without a human retry (mirror of+ // the bill UNMAPPED_ACCOUNTS re-drive).+ const parked = {+ id: "op_1",+ status: "Warning",+ errorCode: "UNSYNCED_DOCUMENT",+ attemptCount: 3,+ createdAt: "2026-08-12T00:00:00Z"+ };+ expect(+ computeReconcileDecision(+ input({+ entityType: "payment",+ snapshot: { status: "Posted" },+ latestOperation: parked,+ settledDocumentMapped: true+ })+ ).actions+ ).toEqual([{ kind: "re-drive", operationId: "op_1" }]);++ // Still unmapped -> stays parked; attempt cap respected+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "payment",+ snapshot: { status: "Posted" },+ latestOperation: parked,+ settledDocumentMapped: false+ })+ )+ )+ ).toEqual(["nothing"]);+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "payment",+ snapshot: { status: "Posted" },+ latestOperation: { ...parked, attemptCount: 5 },+ settledDocumentMapped: true+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("FIX-4: a Voided payment with prior ops records nothing (no void echo in v1)", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "payment",+ snapshot: { status: "Voided" },+ latestOperation: {+ id: "op_1",+ status: "Completed",+ errorCode: null,+ attemptCount: 1,+ createdAt: "2026-08-12T00:00:00Z"+ }+ })+ )+ )+ ).toEqual(["nothing"]);+ });+});++// ── Master data ─────────────────────────────────────────────────────────────++describe("golden: master data", () => {+ it("no mapping ⇔ legacy enqueue-on-any-write", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "customer",+ snapshot: { updatedAt: "2026-08-12T01:00:00Z" }+ })+ )+ )+ ).toEqual(["enqueue"]);+ });++ it("FIX-3: unchanged since last sync ⇔ nothing (replaces the 60s cooldown)", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "customer",+ snapshot: { updatedAt: "2026-08-12T00:00:00Z" },+ hasMappingWithExternalId: true,+ lastSyncedAt: "2026-08-12T00:30:00Z"+ })+ )+ )+ ).toEqual(["nothing"]);+ });++ it("FIX-3: changed after last sync ⇔ enqueue immediately (no cooldown window to swallow it)", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({+ entityType: "customer",+ snapshot: { updatedAt: "2026-08-12T01:00:00Z" },+ hasMappingWithExternalId: true,+ lastSyncedAt: "2026-08-12T00:30:00Z"+ })+ )+ )+ ).toEqual(["enqueue"]);+ });++ it("deleted row ⇔ legacy DELETE skip", () => {+ expect(+ kinds(+ computeReconcileDecision(+ input({ entityType: "customer", snapshot: null })+ )+ )+ ).toEqual(["nothing"]);+ });+});diff --git a/packages/jobs/src/inngest/functions/integrations/reconcile.ts b/packages/jobs/src/inngest/functions/integrations/reconcile.tsnew file mode 100644index 0000000000..7312d90fcf--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/reconcile.ts@@ -0,0 +1,416 @@+/**+ * v5 reconciler decision core (spec:+ * .ai/specs/2026-08-12-accounting-sync-reconciler-unification.md, D1).+ *+ * ONE pure, state-shaped answer to "what should happen for this entity right+ * now?" — subsuming the decision logic that previously lived in five places+ * (the event path's per-table branches, the cooldown/transition routing, and+ * the sweep's document/payment diffs and re-drive rules). The event handler,+ * the outbound sweep, and any future caller are just callers: they load+ * state, ask, and apply.+ *+ * Import-light on purpose (no Inngest, no @carbon/auth): the golden decision+ * matrix (reconcile-golden.test.ts) exercises this exhaustively without+ * booting anything.+ *+ * Level-triggered semantics: the decision never looks at what CHANGED (no+ * event deltas, no old/new rows) — only at what IS. Idempotence follows: the+ * same state always produces the same decision, and a decision whose work is+ * already recorded produces "nothing". That is what makes lost events, burst+ * duplicates, and cooldown races unrepresentable rather than specially+ * handled.+ */+import type { PostingSyncSettings } from "@carbon/ee/accounting";+import {+ MAX_REDRIVE_ATTEMPTS,+ planJournalPostingFromState,+ SWEPT_BILL_STATUSES,+ SWEPT_INVOICE_STATUSES,+ SWEPT_PAYMENT_STATUSES,+ type SyncOperationRequest,+ shouldEnqueueMissingDocument,+ type TerminalSyncOperationRequest+} from "./accounting-sync-operations";++/** Entity types the outbound reconciler covers. */+export type ReconcileEntityType =+ | "journalEntry"+ | "bill"+ | "invoice"+ | "payment"+ | "customer"+ | "vendor"+ | "item"+ | "purchaseOrder"+ | "salesOrder";++export type ReconcileRef = {+ entityType: ReconcileEntityType;+ entityId: string;+};++/** The newest ledger operation for the entity's push tuple. */+export type ReconcileLatestOperation = {+ id: string;+ status: string;+ errorCode: string | null;+ attemptCount: number;+ createdAt: string;+};++export type ReconcileEntityInput = {+ entityType: ReconcileEntityType;+ entityId: string;+ /**+ * Current row state, per type:+ * - journalEntry: { status, sourceType, reversalOfId }+ * - bill/invoice/payment: { status, updatedAt? }+ * - master data: { updatedAt? }+ * Null = the row does not exist (deleted; DELETE sync is unimplemented).+ */+ snapshot: {+ status?: string | null;+ sourceType?: string | null;+ reversalOfId?: string | null;+ updatedAt?: string | null;+ } | null;+ /** externalIntegrationMapping state for the entity (push identity). */+ hasMappingWithExternalId: boolean;+ lastSyncedAt: string | null;+ /** A Pending/In Flight push op exists for the tuple. */+ hasLiveOperation: boolean;+ /** Newest push op for the tuple (by createdAt), live or terminal. */+ latestOperation: ReconcileLatestOperation | null;+ /**+ * journalEntry only: whether ANY op row exists for the plain id and for+ * the `${id}:reversal` id (spec I1 coverage — one disposition each).+ */+ journalCoverage?: { normalCovered: boolean; reversalCovered: boolean };+ /**+ * bill only: a posted "Purchase Invoice" journal exists for this bill —+ * the input the account-costed replay needs (the re-drive condition).+ */+ hasPostedBackingJournal?: boolean;+ /**+ * payment only: the document the parked payment settles+ * (latest op's metadata.targetDocumentId) NOW has a provider mapping —+ * the UNSYNCED_DOCUMENT re-drive condition.+ */+ settledDocumentMapped?: boolean;+ context: ReconcileContext;+};++export type ReconcileContext = {+ /** journalEntry posting enabled for this integration (always-on when an+ * integration is connected; resolved by isJournalEntryPostingEnabled). */+ journalEntryPushEnabled: boolean;+ /** THIS entity type's resolved config: enabled and not pull-only. */+ entityPushEnabled: boolean;+ /** Rillet true — the only provider with outbound payment push. */+ providerSupportsPaymentPush: boolean;+ /** Inputs the journal policy core needs (planJournalPostingFromState). */+ settings: PostingSyncSettings;+ docSync: { invoiceEnabled: boolean; billEnabled: boolean };+ inventoryAdjustmentEnabled: boolean;+ /** Resolved by the executor only for Payment-source journals when the+ * AR/AP family modes diverge (otherwise the side cannot matter). */+ paymentFamily: "ar" | "ap" | null;+};++export type ReconcileAction =+ | { kind: "enqueue"; request: SyncOperationRequest }+ | { kind: "record-terminal"; request: TerminalSyncOperationRequest }+ | { kind: "re-drive"; operationId: string }+ | { kind: "nothing"; reason: string };++export type ReconcileDecision = { actions: ReconcileAction[] };++const nothing = (reason: string): ReconcileDecision => ({+ actions: [{ kind: "nothing", reason }]+});++const MASTER_ENTITY_TYPES: ReadonlySet<string> = new Set([+ "customer",+ "vendor",+ "item",+ "purchaseOrder",+ "salesOrder"+]);++export function computeReconcileDecision(+ input: ReconcileEntityInput+): ReconcileDecision {+ if (!input.snapshot) {+ return nothing("entity not found (deleted rows are not synced)");+ }++ switch (input.entityType) {+ case "journalEntry":+ return reconcileJournal(input);+ case "bill":+ case "invoice":+ return reconcileDocument(input);+ case "payment":+ return reconcilePayment(input);+ default:+ if (MASTER_ENTITY_TYPES.has(input.entityType)) {+ return reconcileMasterData(input);+ }+ return nothing(`entity type '${input.entityType}' is not reconciled`);+ }+}++/**+ * Journals (spec I1): every Posted/Reversed journal carries exactly one+ * recorded disposition per push identity (the plain id, and `:reversal` for+ * Reversed journals). Missing dispositions route through the SAME policy+ * core the event path and backfill use (planJournalPostingFromState) — push+ * ops enqueue, policy exclusions record terminally.+ *+ * A journal row that IS a reversal entry (reversalOfId set) is never its own+ * push identity — the original journal's `:reversal` disposition carries it.+ */+function reconcileJournal(input: ReconcileEntityInput): ReconcileDecision {+ const snapshot = input.snapshot;+ if (!snapshot) return nothing("entity not found");++ if (snapshot.reversalOfId != null) {+ return nothing(+ "reversal entry — represented by the original journal's :reversal disposition"+ );+ }+ if (snapshot.status !== "Posted" && snapshot.status !== "Reversed") {+ return nothing(+ `journal status '${snapshot.status ?? "unknown"}' is not posted`+ );+ }+ if (!input.context.journalEntryPushEnabled) {+ return nothing("posting sync (journalEntry) is disabled");+ }++ const coverage = input.journalCoverage ?? {+ normalCovered: false,+ reversalCovered: false+ };++ const actions: ReconcileAction[] = [];++ const plan = (reversal: boolean): void => {+ const planned = planJournalPostingFromState({+ journalId: input.entityId,+ sourceType: snapshot.sourceType ?? null,+ reversal,+ settings: input.context.settings,+ docSync: input.context.docSync,+ paymentFamily: input.context.paymentFamily,+ inventoryAdjustmentEntitySyncEnabled:+ input.context.inventoryAdjustmentEnabled+ });+ if (planned.action === "push") {+ actions.push({ kind: "enqueue", request: planned.request });+ } else if (planned.action === "terminal") {+ actions.push({ kind: "record-terminal", request: planned.request });+ }+ };++ if (!coverage.normalCovered) plan(false);+ if (snapshot.status === "Reversed" && !coverage.reversalCovered) plan(true);++ if (actions.length === 0) {+ return nothing("journal disposition already recorded");+ }+ return { actions };+}++/**+ * Documents (bills, invoices). Posted-set statuses only — the transient+ * mid-posting "Pending" is deliberately not reconciled (the posting edge+ * function's own status flip re-raises the hint seconds later, after the+ * posting journal exists; this removes the F5 race at the source instead of+ * parking a premature Warning).+ *+ * Order of rules:+ * 1. Re-drive: a bill parked Warning UNMAPPED_ACCOUNTS whose posted+ * "Purchase Invoice" journal NOW exists flips back to Pending (capped).+ * 2. Missing remotely: shouldEnqueueMissingDocument (no mapping + no live op+ * + latest null/Completed — the lost-event and phantom-success classes).+ * 3. Changed since a Failed/Warning attempt: the document was edited after+ * the failure recorded — a genuinely new attempt is warranted (fix-the-+ * data-and-save retries without waiting for a human or the re-drive).+ * 4. Otherwise nothing — parked dispositions belong to humans/policy.+ */+function reconcileDocument(input: ReconcileEntityInput): ReconcileDecision {+ const snapshot = input.snapshot;+ if (!snapshot) return nothing("entity not found");++ if (!input.context.entityPushEnabled) {+ return nothing(`${input.entityType} push is disabled in the sync config`);+ }++ const postedStatuses: readonly string[] =+ input.entityType === "bill" ? SWEPT_BILL_STATUSES : SWEPT_INVOICE_STATUSES;+ if (!snapshot.status || !postedStatuses.includes(snapshot.status)) {+ return nothing(+ `${input.entityType} status '${snapshot.status ?? "unknown"}' is not posted`+ );+ }++ const latest = input.latestOperation;++ if (+ input.entityType === "bill" &&+ !input.hasLiveOperation &&+ latest?.status === "Warning" &&+ latest.errorCode === "UNMAPPED_ACCOUNTS" &&+ input.hasPostedBackingJournal === true &&+ latest.attemptCount < MAX_REDRIVE_ATTEMPTS+ ) {+ return { actions: [{ kind: "re-drive", operationId: latest.id }] };+ }++ if (+ shouldEnqueueMissingDocument({+ hasMapping: input.hasMappingWithExternalId,+ hasLiveOperation: input.hasLiveOperation,+ latestOperationStatus: latest?.status ?? null+ })+ ) {+ return {+ actions: [+ {+ kind: "enqueue",+ request: {+ entityType: input.entityType,+ entityId: input.entityId,+ direction: "push-to-accounting"+ }+ }+ ]+ };+ }++ if (+ !input.hasLiveOperation &&+ latest !== null &&+ (latest?.status === "Failed" || latest?.status === "Warning") &&+ snapshot.updatedAt != null &&+ snapshot.updatedAt > latest.createdAt+ ) {+ return {+ actions: [+ {+ kind: "enqueue",+ request: {+ entityType: input.entityType,+ entityId: input.entityId,+ direction: "push-to-accounting"+ }+ }+ ]+ };+ }++ return nothing(+ input.hasMappingWithExternalId+ ? "document already represented remotely"+ : "document disposition is parked (human retry or re-drive owns it)"+ );+}++/**+ * Payments (Phase G — Rillet only). Strictest rule: only a Posted/Voided+ * payment with NO push operation at all enqueues (payment mapping ids are+ * composite, so a mapping-based phantom check does not apply; ineligible+ * payments park as Skipped on first drain and leave the set). A Voided+ * payment that already has operations records nothing — v1 has no void+ * echo (the syncer parks voids as Skipped by design).+ */+function reconcilePayment(input: ReconcileEntityInput): ReconcileDecision {+ const snapshot = input.snapshot;+ if (!snapshot) return nothing("entity not found");++ if (!input.context.providerSupportsPaymentPush) {+ return nothing("provider has no outbound payment push");+ }+ const posted: readonly string[] = SWEPT_PAYMENT_STATUSES;+ if (!snapshot.status || !posted.includes(snapshot.status)) {+ return nothing(+ `payment status '${snapshot.status ?? "unknown"}' is not posted`+ );+ }++ // Re-drive (mirror of the bill UNMAPPED_ACCOUNTS rule): a payment parked+ // because its settled document had not synced flips back to Pending once+ // that document has a provider mapping — the fix-arrives-later path the+ // dependency chain creates (invoice fails → payment parks → invoice+ // heals → payment must follow without a human).+ const latest = input.latestOperation;+ if (+ !input.hasLiveOperation &&+ latest?.status === "Warning" &&+ latest.errorCode === "UNSYNCED_DOCUMENT" &&+ input.settledDocumentMapped === true &&+ latest.attemptCount < MAX_REDRIVE_ATTEMPTS+ ) {+ return { actions: [{ kind: "re-drive", operationId: latest.id }] };+ }++ if (input.hasLiveOperation || input.latestOperation !== null) {+ return nothing("payment already has a recorded push operation");+ }++ return {+ actions: [+ {+ kind: "enqueue",+ request: {+ entityType: "payment",+ entityId: input.entityId,+ direction: "push-to-accounting"+ }+ }+ ]+ };+}++/**+ * Master data (customer/vendor/item/PO/SO). State-shaped change detection:+ * enqueue when nothing exists remotely, or when the row changed since the+ * last successful sync (updatedAt > mapping.lastSyncedAt). This REPLACES+ * the 60s completed-row cooldown with something strictly better: an+ * unchanged just-synced entity reconciles to nothing (no window to expire),+ * and a changed one enqueues immediately (no window to swallow it). The+ * drain's fast-bailout remains the backstop for false positives.+ */+function reconcileMasterData(input: ReconcileEntityInput): ReconcileDecision {+ const snapshot = input.snapshot;+ if (!snapshot) return nothing("entity not found");++ if (!input.context.entityPushEnabled) {+ return nothing(`${input.entityType} push is disabled in the sync config`);+ }+ if (input.hasLiveOperation) {+ return nothing("a live operation already covers this entity");+ }+ if (+ input.hasMappingWithExternalId &&+ input.lastSyncedAt != null &&+ snapshot.updatedAt != null &&+ snapshot.updatedAt <= input.lastSyncedAt+ ) {+ return nothing("unchanged since the last successful sync");+ }++ return {+ actions: [+ {+ kind: "enqueue",+ request: {+ entityType: input.entityType,+ entityId: input.entityId,+ direction: "push-to-accounting"+ }+ }+ ]+ };+}diff --git a/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts b/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.tsindex 65ccd7ee9a..5e91b1a1b9 100644--- a/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts+++ b/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts@@ -11,7 +11,12 @@* - If entity has remote ID but no local mapping -> Pull from accounting* - If entity has both -> Use the entity config's "owner" to determine direction*- * Includes cooldown protection to prevent redundant syncs of the same entity.+ * Every requested sync routes through the "accountingSyncOperation" ledger:+ * an enqueue step records one operation per entity + direction (re-triggers+ * are absorbed into the live row, and event/webhook triggers respect the 60s+ * completed-row cooldown inside the operations service — the mapping-table+ * cooldown check that used to live here), then a drain step claims Pending+ * operations and runs the entity syncers.*/import { getCarbonServiceRole } from "@carbon/auth/client.server";import {@@ -19,92 +24,99 @@ import {getPostgresConnectionPool} from "@carbon/database/client";import {- type AccountingEntity,type AccountingEntityType,AccountingSyncSchema,- type BatchSyncResult,createMappingService,getAccountingIntegration,getProviderIntegration,- SyncFactory+ type SyncOperationTrigger} from "@carbon/ee/accounting";-import { getLogger } from "@carbon/logger";import { groupBy } from "@carbon/utils";import { PostgresDriver } from "kysely";import { inngest } from "../../client";+import {+ type DrainSummary,+ drainSyncOperations,+ enqueueSyncOperations,+ getSyncOperationActor,+ type SyncOperationRequest+} from "./accounting-sync-operations";const log = getLogger("jobs", "sync-external-accounting");-// Cooldown period in milliseconds to prevent redundant syncs-// If an entity was synced within this period, skip syncing it again-const SYNC_COOLDOWN_MS = 60000; // 1 minute-const PayloadSchema = AccountingSyncSchema.extend({syncDirection: AccountingSyncSchema.shape.syncDirection});+/**+ * Map the payload's syncType onto the ledger trigger: webhooks keep their+ * own trigger; scheduled/trigger syncs are machine re-triggers and enqueue+ * as "event". Both trigger kinds respect the completed-row cooldown+ * enforced inside enqueueSyncOperation.+ */+function getLedgerTrigger(+ syncType: "webhook" | "scheduled" | "trigger"+): SyncOperationTrigger {+ return syncType === "webhook" ? "webhook" : "event";+}+export const syncExternalAccountingFunction = inngest.createFunction({ id: "sync-external-accounting", retries: 1 },{ event: "carbon/sync-external-accounting" },- async ({ event, step, logger }) => {+ async ({ event, step, runId }) => {const payload = PayloadSchema.parse(event.data);const client = getCarbonServiceRole();- const integration = await getAccountingIntegration(- client,- payload.companyId,- payload.provider- );-- const provider = getProviderIntegration(- client,- payload.companyId,- integration.id,- integration.metadata- );+ // Scopes the ledger idempotency keys to this delivery: Inngest retries+ // reuse the same event id (absorbed), later deliveries get fresh keys+ const enqueueScope = event.id ?? runId;+ // NOTE: the pool from getPostgresConnectionPool is a process-lifetime+ // singleton (see lib/postgres) — do NOT end it per invocation.const pool = getPostgresConnectionPool(10);const kysely = getPostgresClient(pool, PostgresDriver);- const mappingService = createMappingService(kysely, payload.companyId);- const results = {- success: [] as BatchSyncResult[],- failed: [] as { entities: AccountingEntity[]; error: string }[]+ // Step 1: resolve each entity's effective direction and enqueue one+ // ledger operation per entity + direction+ type EnqueueStepSummary = {+ enqueued: number;+ cooldownSkipped: number;+ disabled: string[];+ errors: { entityId: string; error: string }[];};- try {- const group = groupBy(payload.entities, (e) => e.entityType);+ const enqueueSummary = (await step.run(+ "enqueue-sync-operations",+ async () => {+ const integration = await getAccountingIntegration(+ client,+ payload.companyId,+ payload.provider+ );- for (const [entityType, entities] of Object.entries(group)) {- const type = entityType as AccountingEntityType;- const entityConfig = provider.getSyncConfig(type);+ const provider = getProviderIntegration(+ client,+ payload.companyId,+ integration.id,+ integration.metadata+ );- if (!entityConfig?.enabled) {- logger.info(`Sync disabled for ${entityType}, skipping`);- continue;- }+ const mappingService = createMappingService(kysely, payload.companyId);- try {- logger.info(- `Starting sync for ${entities.length} ${entityType} entities`,- {- direction: payload.syncDirection,- configDirection: entityConfig.direction- }- );+ const requests: SyncOperationRequest[] = [];+ const disabled: string[] = [];++ const group = groupBy(payload.entities, (e) => e.entityType);- const syncer = SyncFactory.getSyncer({- database: kysely,- companyId: payload.companyId,- provider,- config: entityConfig,- entityType: type- });+ for (const [entityType, entities] of Object.entries(group)) {+ const type = entityType as AccountingEntityType;+ const entityConfig = provider.getSyncConfig(type);- if (entities.length === 0) {- logger.info(`No entities to sync for type ${entityType}`);+ if (!entityConfig?.enabled) {+ log.info(`Sync disabled for ${entityType}, skipping`);+ disabled.push(entityType);continue;}@@ -114,201 +126,127 @@ export const syncExternalAccountingFunction = inngest.createFunction(? entityConfig.direction // Use the entity's configured direction: payload.syncDirection;- if (effectiveDirection === "push-to-accounting") {- // Filter out entities that were synced recently (cooldown)- const entitiesToSync = await filterByCooldown(- mappingService,- type,- entities,- provider.id- );-- if (entitiesToSync.length === 0) {- logger.info(- `All ${entityType} entities were synced recently, skipping`+ for (const entity of entities) {+ if (effectiveDirection === "push-to-accounting") {+ requests.push({+ entityType: type,+ entityId: entity.entityId,+ direction: "push-to-accounting"+ });+ } else if (effectiveDirection === "pull-from-accounting") {+ requests.push({+ entityType: type,+ entityId: entity.entityId,+ direction: "pull-from-accounting"+ });+ } else {+ // Two-way: determine the direction per entity based on+ // whether a mapping exists and which system owns the record+ const mapping = await mappingService.getByEntity(+ type,+ entity.entityId,+ provider.id);- continue;- }-- const result = await syncer.pushBatchToAccounting(- entitiesToSync.map((e) => e.entityId)- );- logger.info("Push sync result", { entityType, result });- results.success.push(result);- } else if (effectiveDirection === "pull-from-accounting") {- // Filter out entities that were synced recently (cooldown)- const entitiesToSync = await filterByCooldown(- mappingService,- type,- entities,- provider.id- );-- if (entitiesToSync.length === 0) {- logger.info(- `All ${entityType} entities were synced recently, skipping`- );- continue;+ if (mapping && entityConfig.owner === "accounting") {+ requests.push({+ entityType: type,+ entityId: mapping.externalId,+ direction: "pull-from-accounting"+ });+ } else {+ // No mapping exists (likely a Carbon-only entity that+ // needs pushing) or Carbon owns the record+ requests.push({+ entityType: type,+ entityId: entity.entityId,+ direction: "push-to-accounting"+ });+ }}+ }+ }- const result = await syncer.pullBatchFromAccounting(- entitiesToSync.map((e) => e.entityId)- );-- logger.info("Pull sync result", { entityType, result });- results.success.push(result);- } else if (effectiveDirection === "two-way") {- // For two-way sync, we need to determine direction per-entity- // based on whether it has a local ID, remote ID, or both- const twoWayResult = await handleTwoWaySync(- syncer,- mappingService,- type,- entities,- provider.id,- entityConfig.owner- );+ const outcomes = await enqueueSyncOperations(client, {+ companyId: payload.companyId,+ integration: payload.provider,+ trigger: getLedgerTrigger(payload.syncType),+ createdBy: getSyncOperationActor(integration),+ scope: enqueueScope,+ requests+ });++ const summary: EnqueueStepSummary = {+ enqueued: 0,+ cooldownSkipped: 0,+ disabled,+ errors: []+ };- logger.info("Two-way sync result", {- entityType,- ...twoWayResult+ for (const outcome of outcomes) {+ if (outcome.outcome === "enqueued") {+ summary.enqueued++;+ } else if (outcome.outcome === "cooldown") {+ summary.cooldownSkipped++;+ } else {+ summary.errors.push({+ entityId: outcome.entityId,+ error: outcome.error ?? "Failed to enqueue sync operation"});- results.success.push(twoWayResult.pushed);- results.success.push(twoWayResult.pulled);}- } catch (error) {- logger.error(`Failed to process ${entityType} entities`, { error });-- results.failed.push({- entities: entities,- error: error instanceof Error ? error.message : "Unknown error"- });}- }- } catch (error) {- logger.error("Sync task failed", { error });- }-- return results;- }-);-/**- * Filter entities that were synced within the cooldown period.- * Returns only entities that are eligible for syncing.- */-async function filterByCooldown(- mappingService: ReturnType<typeof createMappingService>,- entityType: AccountingEntityType,- entities: AccountingEntity[],- integration: string-): Promise<AccountingEntity[]> {- const now = Date.now();- const eligibleEntities: AccountingEntity[] = [];-- for (const entity of entities) {- const mapping = await mappingService.getByEntity(- entityType,- entity.entityId,- integration- );-- // If no mapping exists or lastSyncedAt is old enough, include it- if (!mapping?.lastSyncedAt) {- eligibleEntities.push(entity);- continue;- }-- const lastSyncedAt = new Date(mapping.lastSyncedAt).getTime();- if (now - lastSyncedAt > SYNC_COOLDOWN_MS) {- eligibleEntities.push(entity);- } else {- log.debug(- `Skipping ${entityType} ${entity.entityId} - synced ${- now - lastSyncedAt- }ms ago`+ return summary;+ }+ )) as EnqueueStepSummary;++ log.info("Enqueued sync operations", { enqueueSummary });++ // Step 2: drain — claim Pending operations (including UI retries and+ // stale In Flight rows) and run the entity syncers. A throw re-runs+ // the step; claim/complete are idempotent so retries cannot duplicate+ // work.+ const drainSummary = (await step.run("drain-sync-operations", async () => {+ const integration = await getAccountingIntegration(+ client,+ payload.companyId,+ payload.provider);- }- }-- return eligibleEntities;-}-/**- * Handle two-way sync by determining the appropriate direction for each entity.- *- * Logic:- * - If entity has entityId (Carbon ID) but no remote mapping -> Push to accounting- * - If entity has entityId that is actually a remote ID (no local entity) -> Pull from accounting- * - If entity has both local and remote -> Use "owner" config to determine winner- */-async function handleTwoWaySync(- syncer: ReturnType<typeof SyncFactory.getSyncer>,- mappingService: ReturnType<typeof createMappingService>,- entityType: AccountingEntityType,- entities: AccountingEntity[],- integration: string,- owner: "carbon" | "accounting"-): Promise<{ pushed: BatchSyncResult; pulled: BatchSyncResult }> {- const toPush: string[] = [];- const toPull: string[] = [];- const now = Date.now();-- for (const entity of entities) {- // Check if this entity was synced recently- const mapping = await mappingService.getByEntity(- entityType,- entity.entityId,- integration- );+ const provider = getProviderIntegration(+ client,+ payload.companyId,+ integration.id,+ integration.metadata+ );- if (mapping?.lastSyncedAt) {- const lastSyncedAt = new Date(mapping.lastSyncedAt).getTime();- if (now - lastSyncedAt <= SYNC_COOLDOWN_MS) {- log.debug(- `Skipping two-way sync for ${entityType} ${entity.entityId} - synced recently`- );- continue;- }+ return drainSyncOperations({+ client,+ database: kysely,+ companyId: payload.companyId,+ integration: payload.provider,+ provider,+ integrationMetadata: integration.metadata+ });+ })) as DrainSummary;++ for (const group of drainSummary.groups) {+ log.info("Sync result", {+ entityType: group.entityType,+ direction: group.direction,+ result: group.result+ });}- if (mapping) {- // Entity exists in both systems - use owner to determine direction- if (owner === "carbon") {- toPush.push(entity.entityId);- } else {- // owner === "accounting"- toPull.push(mapping.externalId);+ return {+ success: drainSummary.groups.map((g) => g.result),+ enqueue: enqueueSummary,+ drain: {+ claimed: drainSummary.claimed,+ completed: drainSummary.completed,+ failed: drainSummary.failed,+ skipped: drainSummary.skipped}- } else {- // No mapping exists - this is likely a Carbon-only entity that needs pushing- // Or it could be a remote ID that needs pulling- // For now, assume entityId is a Carbon ID and push it- toPush.push(entity.entityId);- }+ };}-- // Execute push and pull operations- const pushResult =- toPush.length > 0- ? await syncer.pushBatchToAccounting(toPush)- : {- results: [],- successCount: 0,- errorCount: 0,- skippedCount: 0- };-- const pullResult =- toPull.length > 0- ? await syncer.pullBatchFromAccounting(toPull)- : {- results: [],- successCount: 0,- errorCount: 0,- skippedCount: 0- };-- return { pushed: pushResult, pulled: pullResult };-}+);diff --git a/packages/jobs/src/inngest/functions/notifications/content.ts b/packages/jobs/src/inngest/functions/notifications/content.tsindex da3a677be3..ed498bb837 100644--- a/packages/jobs/src/inngest/functions/notifications/content.ts+++ b/packages/jobs/src/inngest/functions/notifications/content.ts@@ -1184,7 +1184,7 @@ async function buildEventContent(};}- // The only kind whose text comes from the payload — it reads nothing.+ // The only kinds whose text comes from the payload — they read nothing.case NotificationEvent.Workflow: {return {description: opts?.title ?? "A workflow ran",@@ -1192,6 +1192,15 @@ async function buildEventContent(};}+ // Payload-carried like Workflow: documentId is a provider id (e.g.+ // "rillet"), not a readable document, so there is nothing to look up.+ case NotificationEvent.IntegrationSync: {+ return {+ description: opts?.title ?? "Accounting sync needs attention",+ details: opts?.body ? [{ label: "Detail", value: opts.body }] : []+ };+ }+default:return null;}diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.tsindex c9a0db938b..a972f0a95e 100644--- a/packages/jobs/src/inngest/functions/notifications/notify.ts+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts@@ -188,7 +188,10 @@ const defaultDestinations: Partial<[NotificationEvent.Workflow]: [NotificationDestination.InApp,NotificationDestination.Email- ]+ ],+ // In-app only: the outbound sweep re-fires while failures persist, and an+ // email per sweep cycle would be noise.+ [NotificationEvent.IntegrationSync]: [NotificationDestination.InApp]};export const notifyFunction = inngest.createFunction(diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.tsindex 99531384ee..a26adc658e 100644--- a/packages/jobs/src/inngest/index.ts+++ b/packages/jobs/src/inngest/index.ts@@ -30,6 +30,10 @@ import {import { extractDocumentFunction } from "./functions/extraction";import {accountingBackfillFunction,+ accountingConsolidationFunction,+ accountingOutboundSweepFunction,+ accountingPullSweepFunction,+ accountingReconciliationFunction,jiraSyncFunction,linearSyncFunction,onshapeBackfillFunction,@@ -141,6 +145,10 @@ export const functions = [linearSyncFunction,paperlessPartsFunction,accountingBackfillFunction,+ accountingConsolidationFunction,+ accountingOutboundSweepFunction,+ accountingReconciliationFunction,+ accountingPullSweepFunction,onshapeBackfillFunction,onshapeRevisionSyncFunction,syncExternalAccountingFunction,diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex 8da6810452..61c5c960a2 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -551,11 +551,14 @@ export type Events = {data: {companyId: string;provider: string;+ syncType?: "webhook" | "scheduled" | "trigger";syncDirection: "push-to-accounting" | "pull-from-accounting" | "two-way";entities: Array<{entityType: string;entityId: string;+ operation?: "create" | "update" | "delete" | "sync";}>;+ metadata?: Record<string, unknown>;};};diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 030a023aed..7ee78a87d6 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "Ein Lieferant ist ein Unternehmen oder eine Person, die dir Teile oder Dienstleistungen verkauft."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— zuletzt überprüft {0}"+msgid ", {residual}% residual"msgstr ", {residual}% Restbetrag"@@ -56,6 +60,10 @@ msgstr "{0} Konten"msgid "{0} ago"msgstr "vor {0}"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} Zellen mit Deltas"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} Kunden mit einem Saldo"@@ -81,6 +89,15 @@ msgstr "{0} Aufträge erstellt"msgid "{0} lines to map"msgstr "{0} Zeilen zum Zuordnen"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} von {1} Buchungskonten zugeordnet"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} von {maxSlots} Provider-Slots verwendet"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} Bestellungen"@@ -101,6 +118,11 @@ msgstr "{0} Lieferanten mit einem Saldo"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} nicht beprobte Entitäten werden freigegeben. Beprobte Annahmen bleiben verfügbar und beprobte Fehler bleiben abgelehnt."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} nicht zugeordnete Konten werden mit {1} Anbieterkonten abgeglichen."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} unveröffentlichte Dokumente"@@ -109,6 +131,11 @@ msgstr "{0} unveröffentlichte Dokumente"msgid "{0} uploaded successfully"msgstr "{0} erfolgreich hochgeladen"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} Werte"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} Werte fehlen"@@ -134,6 +161,9 @@ msgstr "{done} von {total} Phasen abgeschlossen"msgid "{from}–{to} of {count}"msgstr "{from}–{to} von {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} von {count} Operationen"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# Zeile} other {# Zeilen}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB-Limit"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} Monate mit abweichenden Summen"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} Journale fehlen im Provider"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} fehlende Journale und {mismatchCount} Monate mit Abweichungen"+msgid "{name} deleted"msgstr "{name} gelöscht"@@ -198,6 +237,9 @@ msgstr "↩ {0} umgeleitet von veralteten {1}"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Fügen Sie eine Lieferantenkomponente hinzu</0> für diesen Artikel, um einen bevorzugten Lieferanten festzulegen."+msgid "0 operations"+msgstr "0 Operationen"+msgid "0-4 weeks"msgstr "0-4 Wochen"@@ -813,6 +855,9 @@ msgstr "Kundenbetreuer"msgid "Account Manager"msgstr "Kontoführer"+msgid "Account Mapping"+msgstr "Kontenzuordnung"+msgid "Account Number"msgstr "Kontonummer"@@ -870,6 +915,9 @@ msgstr "Forderungen aus Lieferungen und Leistungen"msgid "Accounts receivable for amounts owed by customers"msgstr "Forderungen aus Lieferungen und Leistungen für Beträge, die Kunden schulden."+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Konten, auf die Buchungsstandardwerte oder Journalverlauf verweisen und die noch keine Provider-Zuordnung haben."+msgid "Accumulated Depreciation"msgstr "Kumulierte Abschreibung"@@ -1128,6 +1176,9 @@ msgstr "Sendung hinzufügen"msgid "Add Shipping"msgstr "Versand hinzufügen"+msgid "Add slot"+msgstr "Slot hinzufügen"+msgid "Add Spare Part"msgstr "Ersatzteil hinzufügen"@@ -1219,6 +1270,9 @@ msgstr "Einigen Sie sich auf den Umfang"msgid "Agree who owns what and set a working rhythm"msgstr "Vereinbaren Sie, wer wofür verantwortlich ist, und legen Sie einen Arbeitsrhythmus fest"+msgid "AI couldn't confidently match any accounts"+msgstr "KI konnte keine Konten sicher zuordnen"+msgid "AI Tokens"msgstr "KI-Token"@@ -1228,6 +1282,10 @@ msgstr "Umfang abstimmen"msgid "All"msgstr "Alle"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "Alle {0} Zellen gleichen sich ab"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "Alle {total} Phasen sind abgeschlossen. Großartig — Ihr Team ist einsatzbereit."@@ -1264,9 +1322,15 @@ msgstr "Alle Standorte"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Alle Mitglieder der ausgewählten Gruppen und ausgewählten Personen können Anfragen genehmigen"+msgid "All posting accounts are mapped"+msgstr "Alle Buchungskonten sind zugeordnet"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "Alle Zeilen importiert — {inserted} eingefügt, {updated} aktualisiert."+msgid "All slotted dimension values are mapped"+msgstr "Alle eingeplanten Dimensionswerte sind zugeordnet"+msgid "All Suppliers"msgstr "Alle Lieferanten"@@ -1464,6 +1528,9 @@ msgstr "Beliebiger Artikeltyp"msgid "Anything not explicitly listed in scope above"msgstr "Alles, was oben nicht explizit im Umfang aufgeführt ist"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "Kreditorenalterung"@@ -1540,6 +1607,9 @@ msgstr "Preisregeln anwenden"msgid "Apply Rules On Top"msgstr "Wenden Sie Regeln Oben An"+msgid "Apply suggestions"+msgstr "Vorschläge anwenden"+msgid "Apply To"msgstr "Anwenden auf"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "AR / AP Darstellung"+msgid "AR Aging"msgstr "Debitorenalterung"@@ -1594,6 +1670,9 @@ msgstr "Forderungen ausstehend"msgid "AR Overdue"msgstr "AR Überfällig"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "Archiv"@@ -2146,6 +2225,9 @@ msgstr "Anlage"msgid "Attachments"msgstr "Anhänge"+msgid "Attempts"+msgstr "Versuche"+msgid "Attribute"msgstr "Attribut"@@ -2194,6 +2276,9 @@ msgstr "Automatische Freigabe muss aktiviert sein, um einen Job automatisch zu smsgid "Auto Start Job"msgstr "Auftrag automatisch starten"+msgid "Auto-create"+msgstr "Automatisch erstellen"+msgid "Auto-generated QR Code"msgstr "Automatisch generierter QR-Code"@@ -2440,6 +2525,9 @@ msgstr "Buchen Sie einen Anruf mit Carbon"msgid "Book Depreciation"msgstr "Abschreibung buchen"+msgid "Books lock date (manual)"+msgstr "Büchersperrungsdatum (manuell)"+msgid "Both"msgstr "Beide"@@ -2671,6 +2759,9 @@ msgstr "Carbon"msgid "Carbon + you"msgstr "Carbon + Sie"+msgid "Carbon account"+msgstr "Carbon-Konto"+msgid "Carbon client is not available"msgstr "Carbon-Client ist nicht verfügbar"@@ -2695,9 +2786,19 @@ msgstr "Carbon-Logo"msgid "Carbon only"msgstr "Nur Carbon"+msgid "Carbon Posted"+msgstr "Carbon gebucht"++msgid "Carbon value"+msgstr "Carbon-Wert"+msgid "Carbon Value"msgstr "Carbon-Wert"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon wird KI verwenden, um für jedes Ihrer {0} nicht zugeordneten Konten ein Anbieterkonto vorzuschlagen. Vorschläge sind ein Ausgangspunkt — Sie können diese überprüfen, bevor etwas gespeichert wird."+msgid "Carbon-only"msgstr "Nur Carbon"@@ -3112,6 +3213,13 @@ msgstr "Fertigstellungs-Barcode"msgid "Completion Time"msgstr "Abschlusszeit"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "berechnet {0}"++msgid "Computed At"+msgstr "Berechnet am"+msgid "Condensed P&L with margins and key subtotals"msgstr "Komprimierte Gewinn- und Verlustrechnung mit Margen und wichtigen Zwischensummen"@@ -3209,6 +3317,9 @@ msgstr "Bestätigen {0}"msgid "Confirm & release"msgstr "Bestätigen & Freigeben"+msgid "Confirm all"+msgstr "Alle bestätigen"+msgid "Confirm and sign the scope"msgstr "Umfang bestätigen und unterzeichnen"@@ -3661,6 +3772,9 @@ msgstr "Dokumente konnten nicht geladen werden"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Verwandte Dokumente konnten nicht geladen werden. Aktualisieren Sie die Seite, bevor Sie ein neues erstellen, um Duplikate zu vermeiden."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "Die Dimensionsziele des Providers konnten nicht geladen werden — überprüfen Sie die Verbindung und laden Sie neu."+msgid "Couldn't reschedule the job. Please try again."msgstr "Der Auftrag konnte nicht umgeplant werden. Bitte versuchen Sie es erneut."@@ -4210,6 +4324,9 @@ msgstr "Täglich"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Tägliche Check-ins, während sich Ihr Team im Live-System einarbeitet"+msgid "Daily summary"+msgstr "Tägliche Zusammenfassung"+msgid "Daily Usage"msgstr "Tägliche Nutzung"@@ -4926,6 +5043,12 @@ msgstr "Dimension"msgid "Dimension"msgstr "Dimension"+msgid "Dimension slots"+msgstr "Dimensions-Slots"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Dimensionswerte in gebuchten Journalen, die noch keine Provider-Zuordnung haben."+msgid "dimensions"msgstr "Dimensionen"@@ -5026,6 +5149,9 @@ msgstr "Dispositionen"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "Möchten Sie die aktuellen Berechtigungen des Benutzers mit den Standardberechtigungen für diesen Mitarbeitertyp überschreiben?"+msgid "Doc-Backed"+msgstr "Dokumentgestützt"+msgid "Docs"msgstr "Dokumentation"@@ -5050,6 +5176,9 @@ msgstr "Dokument:"msgid "Documents"msgstr "Dokumente"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Dokumente leitet Rechnungen, Eingangsrechnungen und Zahlungen als native Anbieterurkunden weiter; deren Journale werden als durch das Dokument abgedeckt erfasst. Es werden auch von dem Anbieter erfasste Zahlungen zurück in Carbon importiert, um die zugehörige Rechnung oder den Eingangsbeleg zu schließen und ein Carbon GL-Journal zu buchen. Aus erfasst sie als bewusst ausgeschlossen."+msgid "Don't Cancel"msgstr "Nicht abbrechen"@@ -5975,6 +6104,12 @@ msgstr "Ausnahmezertifikat"msgid "Exemption Reason"msgstr "Ausnahmegrunde"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Existierende Zuordnungen. Wählen Sie ein anderes Provider-Konto zum Neuzuordnen."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Vorhandene Zuordnungen. Wählen Sie eine andere Provider-Option zum Neu-Zuordnen."+msgid "Expand"msgstr "Erweitern"@@ -6111,9 +6246,15 @@ msgstr "Erweiterte Preis"msgid "External"msgstr "Extern"+msgid "External Delta"+msgstr "Externe Differenz"+msgid "External document"msgstr "Externes Dokument"+msgid "External ID"+msgstr "Externe ID"+msgid "External link"msgstr "Externer Link"@@ -6830,6 +6971,9 @@ msgstr "Generierte IDs sind deaktiviert"msgid "Generated IDs are enabled"msgstr "Generierte IDs sind aktiviert"+msgid "Generating suggestions…"+msgstr "Vorschläge werden generiert…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Gehen Sie live auf Carbon: ein System, das Angebote, Einkauf, Shopfloor, Bestand und Finanzen ausführt und die aktuellen Tools ersetzt."@@ -7113,6 +7257,9 @@ msgstr "Historischer Kurs (Eigenkapital)"msgid "History"msgstr "Verlauf"+msgid "Hold the journal as a warning to fix."+msgstr "Das Journal als Warnung zum Beheben halten."+msgid "Holiday"msgstr "Feiertag"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "Ideen, Vorschläge oder Probleme?"+msgid "Idempotency key"+msgstr "Idempotenz-Schlüssel"+msgid "Identifiers"msgstr "Bezeichner"@@ -7549,6 +7699,9 @@ msgstr "Anweisungen"msgid "Instructions are inherited from the procedure."msgstr "Anweisungen werden vom Verfahren geerbt."+msgid "Integration"+msgstr "Integration"+msgid "Integration not found"msgstr "Integration nicht gefunden"@@ -7585,6 +7738,9 @@ msgstr "Zinsertrag oder -aufwand aus Bankaktivitäten"msgid "Internal"msgstr "Intern"+msgid "Internal Delta"+msgstr "Interne Differenz"+msgid "Internal notes"msgstr "Interne Notizen"@@ -7967,6 +8123,9 @@ msgstr "Journaleinträge mit Datum in dieser Periode, die noch im Entwurf sind,msgid "Journal Entry"msgstr "Journaleintrag"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "Journale mit Datum am oder vor diesem Datum werden als gesperrt behandelt. Mit dem vom Provider gemeldeten Sperrungsdatum zusammengeführt, wenn beide existieren."+msgid "Just one"msgstr "Nur eine"@@ -8067,6 +8226,12 @@ msgstr "Sprache"msgid "Last 6 Months"msgstr "Letzte 6 Monate"+msgid "Last attempt"+msgstr "Letzter Versuch"++msgid "Last Attempt"+msgstr "Letzter Versuch"+msgid "Last Calibration"msgstr "Letzte Kalibrierung"@@ -8558,6 +8723,12 @@ msgstr "Herstellerteilnummer"msgid "Manufacturing"msgstr "Herstellung"+msgid "Map accounts"+msgstr "Konten zuordnen"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Ordnen Sie Carbon-Konten dem Kontenrahmen des Providers zu. Gebuchte Journale werden mithilfe des zugeordneten Provider-Kontocodes gesendet."+msgid "Map Extracted Invoice Lines"msgstr "Extrahierte Rechnungspositionen zuordnen"@@ -8570,6 +8741,12 @@ msgstr "Zeilen jetzt zuordnen"msgid "Map your current process, systems, and data"msgstr "Ordnen Sie Ihren aktuellen Prozess, Ihre Systeme und Daten"+msgid "Mapped accounts"+msgstr "Zugeordnete Konten"++msgid "Mapped values"+msgstr "Zugeordnete Werte"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "Markiere „{0}\" als bestanden?"@@ -8640,6 +8817,12 @@ msgstr "Beliebige abgleichen"msgid "Match any (OR)"msgstr "Beliebige abgleichen (ODER)"+msgid "Match by code"+msgstr "Nach Code zuordnen"++msgid "Match by name"+msgstr "Nach Namen abgleichen"+msgid "Match none"msgstr "Keine Übereinstimmung"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Nachricht"+msgid "Metadata"+msgstr "Metadaten"+msgid "Method"msgstr "Methode"@@ -8856,6 +9042,12 @@ msgstr "Minuten/1000 Stück"msgid "Minutes/Piece"msgstr "Minuten/Stück"+msgid "Mismatch"+msgstr "Abweichung"++msgid "Missing"+msgstr "Fehlend"+msgid "Missing Information"msgstr "Fehlende Informationen"@@ -9372,6 +9564,10 @@ msgstr "Nein"msgid "No {0} found"msgstr "Keine {0} gefunden"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "Keine {0} Synchronisierungsoperationen"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "Noch keine {0}"@@ -9382,6 +9578,9 @@ msgstr "Keine Fähigkeiten hinzugefügt"msgid "No Access"msgstr "Kein Zugriff"+msgid "No accounts mapped yet"+msgstr "Noch keine Konten zugeordnet"+msgid "No action needed"msgstr "Keine Aktion erforderlich"@@ -9470,6 +9669,12 @@ msgstr "Keine Tage frei geplant"msgid "No default attachments yet."msgstr "Noch keine Standardanhänge vorhanden."+msgid "No dimension slots configured"+msgstr "Keine Dimensions-Slots konfiguriert"++msgid "No dimension values mapped yet"+msgstr "Noch keine Dimensionswerte zugeordnet"+msgid "No draft make method for this item yet."msgstr "Noch keine Entwurfsmethode für dieses Element."@@ -9635,6 +9840,9 @@ msgstr "Noch keine Zahlungen."msgid "No planning data"msgstr "Keine Planungsdaten"+msgid "No posted journals in this period for this account"+msgstr "Keine gebuchten Journale in diesem Zeitraum für dieses Konto"+msgid "No pricing for selected quantity"msgstr "Keine Preisgestaltung für die ausgewählte Menge"@@ -9716,6 +9924,9 @@ msgstr "Keine Lagereinheit"msgid "No suppliers yet"msgstr "Noch keine Lieferanten"+msgid "No sync operations yet"+msgstr "Noch keine Synchronisierungsoperationen"+msgid "No time entries for this week"msgstr "Keine Zeiteinträge für diese Woche"@@ -9728,6 +9939,12 @@ msgstr "Keine Werkzeuge für diesen Schritt"msgid "No transactions in this period"msgstr "Keine Transaktionen in diesem Zeitraum"+msgid "No unmapped accounts match a provider code"+msgstr "Keine nicht zugeordneten Konten entsprechen einem Provider-Code"++msgid "No unmapped values match a provider option name"+msgstr "Keine nicht zugeordneten Werte entsprechen einem Provider-Optionsnamen"+msgid "No value needed"msgstr "Kein Wert erforderlich"@@ -9803,6 +10020,9 @@ msgstr "Nicht genug Aufträge zur Deckung der Menge"msgid "Not reached"msgstr "Nicht erreicht"+msgid "Not recorded"+msgstr "Nicht erfasst"+msgid "Not referenced anywhere yet."msgstr "Noch nirgendwo referenziert."@@ -9891,6 +10111,9 @@ msgstr "OEM (Original Equipment Manufacturer)"msgid "of"msgstr "von"+msgid "Off — handled outside the sync"+msgstr "Aus — außerhalb der Synchronisierung behandelt"+msgid "Off — released revisions stay editable"msgstr "Aus — veröffentlichte Versionen bleiben bearbeitbar"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "Packzettel"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "Gleichen Sie Beträge auf die Dezimalstellen der Währung an, sodass 300 als 300,00 angezeigt wird und Zahlenspalten ausgerichtet bleiben. Deaktivieren Sie diese Option, um nur aussagekräftige Ziffern anzuzeigen. Gedruckte Dokumente und gespeicherte Beträge sind davon nicht beeinflusst."msgid "Page"msgstr "Seite"@@ -10418,6 +10641,12 @@ msgstr "Übergeordnete Lagereinheit"msgid "Pareto by Type"msgstr "Pareto nach Typ"+msgid "Park as error"+msgstr "Als Fehler zwischenspeichern"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Legen Sie das Journal mit einer Warnung beiseite, bis der Wert zugeordnet ist"+msgid "part"msgstr "Teile"@@ -10478,6 +10707,9 @@ msgstr "Zahlungskurs"msgid "Payables"msgstr "Kreditorenkonten (Standard)"+msgid "Payables (AP)"+msgstr "Verbindlichkeiten (AP)"+msgid "Payables (default)"msgstr "Zahlungsbedingung"@@ -10574,6 +10806,9 @@ msgstr "Periodenschließung"msgid "Period End"msgstr "Periodenende"+msgid "Period lock policy"+msgstr "Zeitraumsperrrichtlinie"+msgid "Periodic depreciation expense for fixed assets"msgstr "Kommissionierung bietet verfolgten Einheiten mit frühestem Verfallsdatum zuerst an, sodass das am schnellsten ablaufende Lager standardmäßig zuerst ausgeht."@@ -10613,6 +10848,9 @@ msgstr "Physische Drucker verfügbar zur Zuweisung."msgid "Pick"msgstr "Auswählen"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Wählen Sie eine Carbon-Dimension und das Provider-Ziel aus, auf das sie publiziert wird. Auto-create fügt beim Versenden fehlende Provider-Optionen nach Namen hinzu."+msgid "Pick a column to sort by"msgstr "Wählen Sie eine Spalte zum Sortieren"@@ -10834,6 +11072,9 @@ msgstr "Gepostet von"msgid "Posted By"msgstr "Gepostet von"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "Gebuchte Journale mit diesen Quellentypen werden immer synchronisiert. Die tägliche Zusammenfassung gruppiert die Journale eines Tages in einen Anbieter pro Konto."+msgid "Posted once, corrected {corrections} times."msgstr "Einmal verbucht, {corrections} mal korrigiert."@@ -11124,6 +11365,12 @@ msgstr "Eigenschaften"msgid "Property"msgstr "Eigenschaft"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Vorgeschlagene Zuordnungen, bei denen die Carbon-Kontonummer genau dem Provider-Accountcode entspricht."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Vorgeschlagene Übereinstimmungen, bei denen der Name des Carbon-Dimensionswerts genau dem Namen einer Provider-Option entspricht."+msgid "Protect the go-live date"msgstr "Schützen Sie das Go-Live-Datum"@@ -11133,6 +11380,15 @@ msgstr "Schulungszeit schützen und teilnehmen"msgid "Provide process knowledge and inputs"msgstr "Prozesswissen und Eingaben bereitstellen"+msgid "Provider"+msgstr "Provider"++msgid "Provider account"+msgstr "Anbieterkonto"++msgid "Provider option"+msgstr "Provider-Option"+msgid "Public"msgstr "Öffentlich"@@ -11146,9 +11402,15 @@ msgstr "Version {0} veröffentlichen?"msgid "Published by Carbon"msgstr "Veröffentlicht von Carbon"+msgid "Pull"+msgstr "Abrufen"+msgid "Pull From"msgstr "Aus entnehmen"+msgid "Pull from accounting"+msgstr "Aus der Buchhaltung abrufen"+msgid "Pull from Inventory"msgstr "Aus Bestand entnehmen"@@ -11272,9 +11534,21 @@ msgstr "Einkaufsrechnungen"msgid "Purchasing Unit of Measure"msgstr "Einkaufsmaßeinheit"+msgid "Push"+msgstr "Senden"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "Es mit neuem Datum zum ersten offenen Tag verschieben und das ursprüngliche Datum in der Erzählung behalten."+msgid "Push record changes to external systems the moment they happen."msgstr "Übertragen Sie Datensatzänderungen in dem Moment an externe Systeme, in dem sie auftreten."+msgid "Push the journal without the dimension"+msgstr "Publizieren Sie das Journal ohne die Dimension"++msgid "Push to accounting"+msgstr "Zur Buchhaltung senden"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "QR-Code zum Erstellen eines {0} für diesen Kanban"@@ -11481,9 +11755,15 @@ msgstr "Rohstoffe"msgid "Raw Materials (default)"msgstr "Rohstoffe (Standard)"+msgid "Re-date to first open day"+msgstr "Auf ersten offenen Tag umbuchen"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Erneute Eingabe zwischen Angebotserstellung, Produktion und Finanzen"+msgid "Re-send"+msgstr "Erneut senden"+msgid "Reactivate"msgstr "Reaktivieren"@@ -11505,6 +11785,9 @@ msgstr "Lesbare ID mit Revision"msgid "Reading the document..."msgstr "Das Dokument wird gelesen..."+msgid "Ready"+msgstr "Bereit"+msgid "Ready for Quote"msgstr "Bereit für Angebot"@@ -11577,6 +11860,9 @@ msgstr "Eingänge, Versände, Verkaufsrechnungen, Kaufrechnungen, Zahlungen undmsgid "Receivables"msgstr "Debitorenkonten (Standard)"+msgid "Receivables (AR)"+msgstr "Forderungen (AR)"+msgid "Receivables (default)"msgstr "Abstimmung einer Bestellung mit dem Empfangenen und Rechnungsgestellten — implizit in Carbon über die Zeilenmengen und GR/IR-Bilanz."@@ -11635,6 +11921,9 @@ msgstr "Kürzlich erstellt"msgid "Reconcile"msgstr "Abstimmen"+msgid "Reconciliation found discrepancies with the provider"+msgstr "Bei der Abstimmung wurden Abweichungen mit dem Anbieter gefunden"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Abschreibungsdauer"@@ -11813,6 +12102,9 @@ msgstr "Zeile entfernen"msgid "Remove slide"msgstr "Folie entfernen"+msgid "Remove slot"+msgstr "Slot entfernen"+msgid "Remove sort by column"msgstr "Sortierung nach Spalte entfernen"@@ -12047,6 +12339,9 @@ msgstr "Außerdienststellung eines Vermögenswerts durch Verschrottung oder Verkmsgid "Retry"msgstr "Erneut versuchen"+msgid "Retry all"+msgstr "Alle erneut versuchen"+msgid "Return Home"msgstr "Zur Startseite zurück"@@ -12098,6 +12393,9 @@ msgstr "Überprüfen Sie die Änderungen jedes Elements, und bestätigen Sie danmsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Überprüfen Sie die Bilanz und die Gewinn- und Verlustrechnung der Periode und bestätigen Sie, dass die Zahlen korrekt aussehen. Dies ist eine manuelle Genehmigung – markieren Sie sie als erledigt, sobald Sie diese überprüft haben."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Überprüfen Sie die vorgeschlagenen Zuordnungen vor dem Anwenden. Dies sind Schätzungen — bestätigen Sie, dass jede richtig ist."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Überprüfen Sie die folgenden Warnungen und posten Sie dann die Anzahl, um die Anpassungen anzuwenden."@@ -12153,6 +12451,9 @@ msgstr "RFQ-Nummer"msgid "RFQs"msgstr "Anfragen"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Carbon-Dimensionen in gepushten Journalen mitführen. Jeder Slot ordnet eine Carbon-Dimension einem Analytics-Ziel des Providers zu; die Wertzuordnung unten ordnet einzelne Dimensionswerte Provider-Optionen zu."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Anwendungen speichern"msgid "Save contacts"msgstr "Kontakte speichern"+msgid "Save dimension settings"+msgstr "Dimensionseinstellungen speichern"+msgid "Save Method"msgstr "Methode speichern"@@ -12759,6 +13063,9 @@ msgstr "Kundentypen auswählen"msgid "Select customers"msgstr "Kunden auswählen"+msgid "Select dimension"+msgstr "Dimension wählen"+msgid "Select Employee"msgstr "Mitarbeiter auswählen"@@ -12795,6 +13102,15 @@ msgstr "Methode auswählen..."msgid "Select Printer"msgstr "Drucker auswählen"+msgid "Select provider account"+msgstr "Anbieterkonto auswählen"++msgid "Select provider target"+msgstr "Provider-Ziel wählen"++msgid "Select provider value"+msgstr "Provider-Wert wählen"+msgid "Select Quantities"msgstr "Mengen auswählen"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "Synchronisierungsoptionen anzeigen"msgid "Show Trailing Zeros"-msgstr ""+msgstr "Nachgestellte Nullen anzeigen"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "Anzeige in {parentCurrency}"msgid "Showing the first 500 lines"msgstr "Die ersten 500 Zeilen werden angezeigt"+msgid "Showing the newest 200 journals"+msgstr "Die neuesten 200 Journale werden angezeigt"+msgid "Showing the top 1,000 groups by amount"msgstr "Die Top 1.000 Gruppen nach Betrag werden angezeigt"@@ -13383,6 +13702,9 @@ msgstr "Quellenliste"msgid "Source Method"msgstr "Quellmethode"+msgid "Source types"+msgstr "Quellentypen"+msgid "Source Version"msgstr "Quellversion"@@ -13721,6 +14043,15 @@ msgstr "Nachfolgeteil"msgid "Suffix"msgstr "Suffix"+msgid "Suggest mappings"+msgstr "Zuordnungen vorschlagen"++msgid "Suggest mappings with AI"+msgstr "Zuordnungen mit KI vorschlagen"++msgid "Suggest with AI"+msgstr "Mit KI vorschlagen"+msgid "Suggested orders you haven't placed yet."msgstr "Vorgeschlagene Bestellungen, die Sie noch nicht aufgegeben haben."@@ -13926,6 +14257,18 @@ msgstr "Das Ändern des Mitarbeitertyps hier ändert nicht ihre bestehenden Beremsgid "Sync"msgstr "Synchronisieren"+msgid "Sync Activity"+msgstr "Synchronisierungsaktivität"++msgid "Sync operation"+msgstr "Synchronisierungsoperation"++msgid "Sync Tie-Out"+msgstr "Sync-Abgleich"++msgid "Synced"+msgstr "Synchronisiert"+msgid "System"msgstr "System"@@ -14599,6 +14942,9 @@ msgstr "Das Verfahren, das Techniker befolgen, wenn diese Wartung durchgeführtmsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "Die Prozesse, die dieses Arbeitszentrum ausführen kann; wird in Prozessauswahlern beim Planen von Operationen angezeigt und beschränkt, welche Aufträge durch dieses Arbeitszentrum geleitet werden können."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "Der Provider bietet keine Dimensionsziele. Aktivieren Sie die Funktion zuerst beim Provider (z. B. Tracking-Kategorien, Klassenverfolgung oder Felder)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Die Mengenumbruchspunkte, zu denen diese Zeile bepreist wird; jede Spalte führt ihren eigenen Preis pro Einheit für Käufer-Lieferanten-Verhandlungen und für die Umwandlung in nachgelagerte Dokumente."@@ -15077,6 +15423,9 @@ msgstr "Donnerstag"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Lieferungen direkt mit einer Rechnung verknüpfen ohne erneute Eingabe"+msgid "Tie-out"+msgstr "Abgleich"+msgid "Tie-Out"msgstr "Abstimmung"@@ -15533,9 +15882,18 @@ msgstr "Auftrag von Verkaufsauftrag trennen?"msgid "Unlock"msgstr "Entsperren"+msgid "Unmapped accounts"+msgstr "Nicht zugeordnete Konten"++msgid "Unmapped dimension values"+msgstr "Nicht zugeordnete Dimensionswerte"+msgid "Unmapped Extracted Lines"msgstr "Nicht zugeordnete extrahierte Zeilen"+msgid "Unmapped values"+msgstr "Nicht zugeordnete Werte"+msgid "Unmatched"msgstr "Nicht abgestimmt"@@ -16077,6 +16435,9 @@ msgstr "Vorschlag anzeigen"msgid "View Suppliers"msgstr "Lieferanten anzeigen"+msgid "View tie-out"+msgstr "Abgleich anzeigen"+msgid "View Traceability Graph"msgstr "Rückverfolgbarkeitsgraph anzeigen"@@ -16283,6 +16644,9 @@ msgstr "Welche Daten"msgid "What drove inventory up or down, by any dimension"msgstr "Was den Bestand nach oben oder unten getrieben hat, nach beliebiger Dimension"+msgid "What happens when a journal is dated in a locked period."+msgstr "Was passiert, wenn ein Journal in einem gesperrten Zeitraum datiert ist."+msgid "What is {translatedTerm}?"msgstr "{translatedTerm} ist was?"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 84c1c0a3ee..4016b86ad5 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr " A supplier is a business or person who sells you parts or services."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— last checked {0}"+msgid ", {residual}% residual"msgstr ", {residual}% residual"@@ -56,6 +60,10 @@ msgstr "{0} accounts"msgid "{0} ago"msgstr "{0} ago"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} cells with deltas"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} customers with a balance"@@ -81,6 +89,15 @@ msgstr "{0} jobs created"msgid "{0} lines to map"msgstr "{0} lines to map"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} of {1} posting accounts mapped"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} of {maxSlots} provider slots used"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} orders"@@ -101,6 +118,11 @@ msgstr "{0} suppliers with a balance"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} unmapped accounts will be matched against {1} provider accounts."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} unposted documents"@@ -109,6 +131,11 @@ msgstr "{0} unposted documents"msgid "{0} uploaded successfully"msgstr "{0} uploaded successfully"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} values"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} values missing"@@ -134,6 +161,9 @@ msgstr "{done} of {total} phases complete"msgid "{from}–{to} of {count}"msgstr "{from}–{to} of {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} of {count} operations"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# line} other {# lines}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB limit"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} months with mismatched totals"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} journals missing in the provider"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} missing journals and {mismatchCount} mismatched months"+msgid "{name} deleted"msgstr "{name} deleted"@@ -198,6 +237,9 @@ msgstr "↩ {0} redirected from superseded {1}"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Add a supplier part</0> for this item to set a preferred supplier."+msgid "0 operations"+msgstr "0 operations"+msgid "0-4 weeks"msgstr "0-4 weeks"@@ -813,6 +855,9 @@ msgstr "Account manager"msgid "Account Manager"msgstr "Account Manager"+msgid "Account Mapping"+msgstr "Account Mapping"+msgid "Account Number"msgstr "Account Number"@@ -870,6 +915,9 @@ msgstr "Accounts Receivable"msgid "Accounts receivable for amounts owed by customers"msgstr "Accounts receivable for amounts owed by customers"+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgid "Accumulated Depreciation"msgstr "Accumulated Depreciation"@@ -1128,6 +1176,9 @@ msgstr "Add Shipment"msgid "Add Shipping"msgstr "Add Shipping"+msgid "Add slot"+msgstr "Add slot"+msgid "Add Spare Part"msgstr "Add Spare Part"@@ -1219,6 +1270,9 @@ msgstr "Agree on the scope"msgid "Agree who owns what and set a working rhythm"msgstr "Agree who owns what and set a working rhythm"+msgid "AI couldn't confidently match any accounts"+msgstr "AI couldn't confidently match any accounts"+msgid "AI Tokens"msgstr "AI Tokens"@@ -1228,6 +1282,10 @@ msgstr "Align on scope"msgid "All"msgstr "All"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "All {0} cells tie out"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "All {total} phases are done. Nice work — your team is up and running."@@ -1264,9 +1322,15 @@ msgstr "All Locations"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "All members of selected groups and selected individuals will be able to approve requests"+msgid "All posting accounts are mapped"+msgstr "All posting accounts are mapped"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "All rows imported — {inserted} inserted, {updated} updated."+msgid "All slotted dimension values are mapped"+msgstr "All slotted dimension values are mapped"+msgid "All Suppliers"msgstr "All Suppliers"@@ -1464,6 +1528,9 @@ msgstr "Any item type"msgid "Anything not explicitly listed in scope above"msgstr "Anything not explicitly listed in scope above"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "AP Aging"@@ -1540,6 +1607,9 @@ msgstr "Apply pricing rules"msgid "Apply Rules On Top"msgstr "Apply Rules On Top"+msgid "Apply suggestions"+msgstr "Apply suggestions"+msgid "Apply To"msgstr "Apply To"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "AR / AP representation"+msgid "AR Aging"msgstr "AR Aging"@@ -1594,6 +1670,9 @@ msgstr "AR Outstanding"msgid "AR Overdue"msgstr "AR Overdue"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "Archive"@@ -2146,6 +2225,9 @@ msgstr "Attachment"msgid "Attachments"msgstr "Attachments"+msgid "Attempts"+msgstr "Attempts"+msgid "Attribute"msgstr "Attribute"@@ -2194,6 +2276,9 @@ msgstr "Auto release must be enabled to start a job automatically"msgid "Auto Start Job"msgstr "Auto Start Job"+msgid "Auto-create"+msgstr "Auto-create"+msgid "Auto-generated QR Code"msgstr "Auto-generated QR Code"@@ -2440,6 +2525,9 @@ msgstr "Book a call with Carbon"msgid "Book Depreciation"msgstr "Book Depreciation"+msgid "Books lock date (manual)"+msgstr "Books lock date (manual)"+msgid "Both"msgstr "Both"@@ -2671,6 +2759,9 @@ msgstr "Carbon"msgid "Carbon + you"msgstr "Carbon + you"+msgid "Carbon account"+msgstr "Carbon account"+msgid "Carbon client is not available"msgstr "Carbon client is not available"@@ -2695,9 +2786,19 @@ msgstr "Carbon Logo"msgid "Carbon only"msgstr "Carbon only"+msgid "Carbon Posted"+msgstr "Carbon Posted"++msgid "Carbon value"+msgstr "Carbon value"+msgid "Carbon Value"msgstr "Carbon Value"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgid "Carbon-only"msgstr "Carbon-only"@@ -3112,6 +3213,13 @@ msgstr "Completion Barcode"msgid "Completion Time"msgstr "Completion Time"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "computed {0}"++msgid "Computed At"+msgstr "Computed At"+msgid "Condensed P&L with margins and key subtotals"msgstr "Condensed P&L with margins and key subtotals"@@ -3209,6 +3317,9 @@ msgstr "Confirm {0}"msgid "Confirm & release"msgstr "Confirm & release"+msgid "Confirm all"+msgstr "Confirm all"+msgid "Confirm and sign the scope"msgstr "Confirm and sign the scope"@@ -3661,6 +3772,9 @@ msgstr "Couldn't load documents"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "Couldn't load the provider's dimension targets — check the connection and reload."+msgid "Couldn't reschedule the job. Please try again."msgstr "Couldn't reschedule the job. Please try again."@@ -4210,6 +4324,9 @@ msgstr "Daily"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Daily check-ins while your team finds its feet on the live system"+msgid "Daily summary"+msgstr "Daily summary"+msgid "Daily Usage"msgstr "Daily Usage"@@ -4926,6 +5043,12 @@ msgstr "dimension"msgid "Dimension"msgstr "Dimension"+msgid "Dimension slots"+msgstr "Dimension slots"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Dimension values on posted journals that have no provider mapping yet."+msgid "dimensions"msgstr "dimensions"@@ -5026,6 +5149,9 @@ msgstr "Dispositions"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"+msgid "Doc-Backed"+msgstr "Doc-Backed"+msgid "Docs"msgstr "Docs"@@ -5050,6 +5176,9 @@ msgstr "Document:"msgid "Documents"msgstr "Documents"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgid "Don't Cancel"msgstr "Don't Cancel"@@ -5975,6 +6104,12 @@ msgstr "Exemption Certificate"msgid "Exemption Reason"msgstr "Exemption Reason"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Existing mappings. Pick a different provider account to re-map."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Existing mappings. Pick a different provider option to re-map."+msgid "Expand"msgstr "Expand"@@ -6111,9 +6246,15 @@ msgstr "Extended Price"msgid "External"msgstr "External"+msgid "External Delta"+msgstr "External Delta"+msgid "External document"msgstr "External document"+msgid "External ID"+msgstr "External ID"+msgid "External link"msgstr "External link"@@ -6830,6 +6971,9 @@ msgstr "Generated IDs are disabled"msgid "Generated IDs are enabled"msgstr "Generated IDs are enabled"+msgid "Generating suggestions…"+msgstr "Generating suggestions…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."@@ -7113,6 +7257,9 @@ msgstr "Historical Rate (Equity)"msgid "History"msgstr "History"+msgid "Hold the journal as a warning to fix."+msgstr "Hold the journal as a warning to fix."+msgid "Holiday"msgstr "Holiday"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "Ideas, suggestions or problems?"+msgid "Idempotency key"+msgstr "Idempotency key"+msgid "Identifiers"msgstr "Identifiers"@@ -7549,6 +7699,9 @@ msgstr "Instructions"msgid "Instructions are inherited from the procedure."msgstr "Instructions are inherited from the procedure."+msgid "Integration"+msgstr "Integration"+msgid "Integration not found"msgstr "Integration not found"@@ -7585,6 +7738,9 @@ msgstr "Interest income or expense from banking activities"msgid "Internal"msgstr "Internal"+msgid "Internal Delta"+msgstr "Internal Delta"+msgid "Internal notes"msgstr "Internal notes"@@ -7967,6 +8123,9 @@ msgstr "Journal entries dated in this period that are still Draft must be postedmsgid "Journal Entry"msgstr "Journal Entry"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgid "Just one"msgstr "Just one"@@ -8067,6 +8226,12 @@ msgstr "Language"msgid "Last 6 Months"msgstr "Last 6 Months"+msgid "Last attempt"+msgstr "Last attempt"++msgid "Last Attempt"+msgstr "Last Attempt"+msgid "Last Calibration"msgstr "Last Calibration"@@ -8558,6 +8723,12 @@ msgstr "Manufacturer Part Number"msgid "Manufacturing"msgstr "Manufacturing"+msgid "Map accounts"+msgstr "Map accounts"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgid "Map Extracted Invoice Lines"msgstr "Map Extracted Invoice Lines"@@ -8570,6 +8741,12 @@ msgstr "Map Lines Now"msgid "Map your current process, systems, and data"msgstr "Map your current process, systems, and data"+msgid "Mapped accounts"+msgstr "Mapped accounts"++msgid "Mapped values"+msgstr "Mapped values"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "Mark \"{0}\" as passed?"@@ -8640,6 +8817,12 @@ msgstr "Match any"msgid "Match any (OR)"msgstr "Match any (OR)"+msgid "Match by code"+msgstr "Match by code"++msgid "Match by name"+msgstr "Match by name"+msgid "Match none"msgstr "Match none"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Message"+msgid "Metadata"+msgstr "Metadata"+msgid "Method"msgstr "Method"@@ -8856,6 +9042,12 @@ msgstr "Minutes/1000 Pieces"msgid "Minutes/Piece"msgstr "Minutes/Piece"+msgid "Mismatch"+msgstr "Mismatch"++msgid "Missing"+msgstr "Missing"+msgid "Missing Information"msgstr "Missing Information"@@ -9372,6 +9564,10 @@ msgstr "No"msgid "No {0} found"msgstr "No {0} found"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "No {0} sync operations"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "No {0} yet"@@ -9382,6 +9578,9 @@ msgstr "No abilities added"msgid "No Access"msgstr "No Access"+msgid "No accounts mapped yet"+msgstr "No accounts mapped yet"+msgid "No action needed"msgstr "No action needed"@@ -9470,6 +9669,12 @@ msgstr "No days off scheduled"msgid "No default attachments yet."msgstr "No default attachments yet."+msgid "No dimension slots configured"+msgstr "No dimension slots configured"++msgid "No dimension values mapped yet"+msgstr "No dimension values mapped yet"+msgid "No draft make method for this item yet."msgstr "No draft make method for this item yet."@@ -9635,6 +9840,9 @@ msgstr "No payments yet."msgid "No planning data"msgstr "No planning data"+msgid "No posted journals in this period for this account"+msgstr "No posted journals in this period for this account"+msgid "No pricing for selected quantity"msgstr "No pricing for selected quantity"@@ -9716,6 +9924,9 @@ msgstr "No storage unit"msgid "No suppliers yet"msgstr "No suppliers yet"+msgid "No sync operations yet"+msgstr "No sync operations yet"+msgid "No time entries for this week"msgstr "No time entries for this week"@@ -9728,6 +9939,12 @@ msgstr "No tools for this step"msgid "No transactions in this period"msgstr "No transactions in this period"+msgid "No unmapped accounts match a provider code"+msgstr "No unmapped accounts match a provider code"++msgid "No unmapped values match a provider option name"+msgstr "No unmapped values match a provider option name"+msgid "No value needed"msgstr "No value needed"@@ -9803,6 +10020,9 @@ msgstr "Not enough jobs to cover quantity"msgid "Not reached"msgstr "Not reached"+msgid "Not recorded"+msgstr "Not recorded"+msgid "Not referenced anywhere yet."msgstr "Not referenced anywhere yet."@@ -9891,6 +10111,9 @@ msgstr "OEM (original equipment manufacturer)"msgid "of"msgstr "of"+msgid "Off — handled outside the sync"+msgstr "Off — handled outside the sync"+msgid "Off — released revisions stay editable"msgstr "Off — released revisions stay editable"@@ -10418,6 +10641,12 @@ msgstr "Parent Storage Unit"msgid "Pareto by Type"msgstr "Pareto by Type"+msgid "Park as error"+msgstr "Park as error"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Park the journal with a warning until the value is mapped"+msgid "part"msgstr "part"@@ -10478,6 +10707,9 @@ msgstr "Pay Rate"msgid "Payables"msgstr "Payables"+msgid "Payables (AP)"+msgstr "Payables (AP)"+msgid "Payables (default)"msgstr "Payables (default)"@@ -10574,6 +10806,9 @@ msgstr "Period close"msgid "Period End"msgstr "Period End"+msgid "Period lock policy"+msgstr "Period lock policy"+msgid "Periodic depreciation expense for fixed assets"msgstr "Periodic depreciation expense for fixed assets"@@ -10613,6 +10848,9 @@ msgstr "Physical printers available for assignment."msgid "Pick"msgstr "Pick"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgid "Pick a column to sort by"msgstr "Pick a column to sort by"@@ -10834,6 +11072,9 @@ msgstr "Posted by"msgid "Posted By"msgstr "Posted By"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgid "Posted once, corrected {corrections} times."msgstr "Posted once, corrected {corrections} times."@@ -11124,6 +11365,12 @@ msgstr "Properties"msgid "Property"msgstr "Property"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Proposed matches where the Carbon account number equals the provider account code exactly."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgid "Protect the go-live date"msgstr "Protect the go-live date"@@ -11133,6 +11380,15 @@ msgstr "Protect training time and attend"msgid "Provide process knowledge and inputs"msgstr "Provide process knowledge and inputs"+msgid "Provider"+msgstr "Provider"++msgid "Provider account"+msgstr "Provider account"++msgid "Provider option"+msgstr "Provider option"+msgid "Public"msgstr "Public"@@ -11146,9 +11402,15 @@ msgstr "Publish Version {0}?"msgid "Published by Carbon"msgstr "Published by Carbon"+msgid "Pull"+msgstr "Pull"+msgid "Pull From"msgstr "Pull From"+msgid "Pull from accounting"+msgstr "Pull from accounting"+msgid "Pull from Inventory"msgstr "Pull from Inventory"@@ -11272,9 +11534,21 @@ msgstr "Purchasing Invoices"msgid "Purchasing Unit of Measure"msgstr "Purchasing Unit of Measure"+msgid "Push"+msgstr "Push"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "Push it re-dated to the first open day, keeping the original date in the narration."+msgid "Push record changes to external systems the moment they happen."msgstr "Push record changes to external systems the moment they happen."+msgid "Push the journal without the dimension"+msgstr "Push the journal without the dimension"++msgid "Push to accounting"+msgstr "Push to accounting"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "QR Code to create a {0} for this kanban"@@ -11481,9 +11755,15 @@ msgstr "Raw Materials"msgid "Raw Materials (default)"msgstr "Raw Materials (default)"+msgid "Re-date to first open day"+msgstr "Re-date to first open day"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Re-keying between quoting, the floor, and finance"+msgid "Re-send"+msgstr "Re-send"+msgid "Reactivate"msgstr "Reactivate"@@ -11505,6 +11785,9 @@ msgstr "Readable id with revision"msgid "Reading the document..."msgstr "Reading the document..."+msgid "Ready"+msgstr "Ready"+msgid "Ready for Quote"msgstr "Ready for Quote"@@ -11577,6 +11860,9 @@ msgstr "Receipts, shipments, sales invoices, purchase invoices, payments, and crmsgid "Receivables"msgstr "Receivables"+msgid "Receivables (AR)"+msgstr "Receivables (AR)"+msgid "Receivables (default)"msgstr "Receivables (default)"@@ -11635,6 +11921,9 @@ msgstr "Recently Created"msgid "Reconcile"msgstr "Reconcile"+msgid "Reconciliation found discrepancies with the provider"+msgstr "Reconciliation found discrepancies with the provider"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."@@ -11813,6 +12102,9 @@ msgstr "Remove row"msgid "Remove slide"msgstr "Remove slide"+msgid "Remove slot"+msgstr "Remove slot"+msgid "Remove sort by column"msgstr "Remove sort by column"@@ -12047,6 +12339,9 @@ msgstr "Retiring an asset from service by scrapping or sale, booking any gain ormsgid "Retry"msgstr "Retry"+msgid "Retry all"+msgstr "Retry all"+msgid "Return Home"msgstr "Return Home"@@ -12098,6 +12393,9 @@ msgstr "Review each item's changes, then confirm — releasing can't be undone."msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Review the warnings below, then post the count to apply the adjustments."@@ -12153,6 +12451,9 @@ msgstr "RFQ Number"msgid "RFQs"msgstr "RFQs"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Save applications"msgid "Save contacts"msgstr "Save contacts"+msgid "Save dimension settings"+msgstr "Save dimension settings"+msgid "Save Method"msgstr "Save Method"@@ -12759,6 +13063,9 @@ msgstr "Select customer types"msgid "Select customers"msgstr "Select customers"+msgid "Select dimension"+msgstr "Select dimension"+msgid "Select Employee"msgstr "Select Employee"@@ -12795,6 +13102,15 @@ msgstr "Select method..."msgid "Select Printer"msgstr "Select Printer"+msgid "Select provider account"+msgstr "Select provider account"++msgid "Select provider target"+msgstr "Select provider target"++msgid "Select provider value"+msgstr "Select provider value"+msgid "Select Quantities"msgstr "Select Quantities"@@ -13239,6 +13555,9 @@ msgstr "Showing in {parentCurrency}"msgid "Showing the first 500 lines"msgstr "Showing the first 500 lines"+msgid "Showing the newest 200 journals"+msgstr "Showing the newest 200 journals"+msgid "Showing the top 1,000 groups by amount"msgstr "Showing the top 1,000 groups by amount"@@ -13383,6 +13702,9 @@ msgstr "Source list"msgid "Source Method"msgstr "Source Method"+msgid "Source types"+msgstr "Source types"+msgid "Source Version"msgstr "Source Version"@@ -13721,6 +14043,15 @@ msgstr "Successor Part"msgid "Suffix"msgstr "Suffix"+msgid "Suggest mappings"+msgstr "Suggest mappings"++msgid "Suggest mappings with AI"+msgstr "Suggest mappings with AI"++msgid "Suggest with AI"+msgstr "Suggest with AI"+msgid "Suggested orders you haven't placed yet."msgstr "Suggested orders you haven't placed yet."@@ -13926,6 +14257,18 @@ msgstr "Switching the employee's type here doesn't change their existing permissmsgid "Sync"msgstr "Sync"+msgid "Sync Activity"+msgstr "Sync Activity"++msgid "Sync operation"+msgstr "Sync operation"++msgid "Sync Tie-Out"+msgstr "Sync Tie-Out"++msgid "Synced"+msgstr "Synced"+msgid "System"msgstr "System"@@ -14599,6 +14942,9 @@ msgstr "The procedure technicians follow when this maintenance is performed; repmsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."@@ -15077,6 +15423,9 @@ msgstr "Thursday"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Tie shipments through to an invoice with no re-keying"+msgid "Tie-out"+msgstr "Tie-out"+msgid "Tie-Out"msgstr "Tie-Out"@@ -15533,9 +15882,18 @@ msgstr "Unlink job from sales order?"msgid "Unlock"msgstr "Unlock"+msgid "Unmapped accounts"+msgstr "Unmapped accounts"++msgid "Unmapped dimension values"+msgstr "Unmapped dimension values"+msgid "Unmapped Extracted Lines"msgstr "Unmapped Extracted Lines"+msgid "Unmapped values"+msgstr "Unmapped values"+msgid "Unmatched"msgstr "Unmatched"@@ -16077,6 +16435,9 @@ msgstr "View Suggestion"msgid "View Suppliers"msgstr "View Suppliers"+msgid "View tie-out"+msgstr "View tie-out"+msgid "View Traceability Graph"msgstr "View Traceability Graph"@@ -16283,6 +16644,9 @@ msgstr "What data"msgid "What drove inventory up or down, by any dimension"msgstr "What drove inventory up or down, by any dimension"+msgid "What happens when a journal is dated in a locked period."+msgstr "What happens when a journal is dated in a locked period."+msgid "What is {translatedTerm}?"msgstr "What is {translatedTerm}?"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex a81bb02fd2..7b1be28166 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "Un proveedor es una empresa o persona que te vende piezas o servicios."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— última verificación {0}"+msgid ", {residual}% residual"msgstr ", {residual}% residual"@@ -56,6 +60,10 @@ msgstr "{0} cuentas"msgid "{0} ago"msgstr "{0} hace"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} celdas con diferencias"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} clientes con saldo"@@ -81,6 +89,15 @@ msgstr "{0} trabajos creados"msgid "{0} lines to map"msgstr "{0} líneas para mapear"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} de {1} cuentas de contabilización asignadas"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} de {maxSlots} espacios de proveedor utilizados"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} pedidos"@@ -101,6 +118,11 @@ msgstr "{0} proveedores con saldo"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} entidades no muestreadas serán liberadas a Disponible. Los pases muestreados permanecen Disponibles y los fallos muestreados permanecen Rechazados."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} cuentas no mapeadas serán emparejadas contra {1} cuentas del proveedor."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} documentos no contabilizados"@@ -109,6 +131,11 @@ msgstr "{0} documentos no contabilizados"msgid "{0} uploaded successfully"msgstr "{0} cargado exitosamente"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} valores"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} valores faltantes"@@ -134,6 +161,9 @@ msgstr "{done} de {total} fases completadas"msgid "{from}–{to} of {count}"msgstr "{from}–{to} de {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} de {count} operaciones"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# línea} other {# líneas}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB límite"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} meses con totales no coincidentes"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} diarios faltantes en el proveedor"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} diarios faltantes y {mismatchCount} meses no coincidentes"+msgid "{name} deleted"msgstr "{name} eliminado"@@ -198,6 +237,9 @@ msgstr "↩ {0} redirigido desde {1} obsoleto"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Agregue una parte de proveedor</0> para este artículo para establecer un proveedor preferido."+msgid "0 operations"+msgstr "0 operaciones"+msgid "0-4 weeks"msgstr "0-4 semanas"@@ -813,6 +855,9 @@ msgstr "Gerente de cuenta"msgid "Account Manager"msgstr "Gerente de Cuenta"+msgid "Account Mapping"+msgstr "Asignación de Cuentas"+msgid "Account Number"msgstr "Número de Cuenta"@@ -870,6 +915,9 @@ msgstr "Cuentas por cobrar"msgid "Accounts receivable for amounts owed by customers"msgstr "Cuentas por cobrar para montos adeudados por clientes."+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Cuentas referenciadas por defectos de registro o historial de diarios que aún no tienen asignación de proveedor."+msgid "Accumulated Depreciation"msgstr "Depreciación acumulada"@@ -1128,6 +1176,9 @@ msgstr "Agregar Envío"msgid "Add Shipping"msgstr "Agregar Envío"+msgid "Add slot"+msgstr "Añadir espacio"+msgid "Add Spare Part"msgstr "Agregar Pieza de Repuesto"@@ -1219,6 +1270,9 @@ msgstr "Acordar sobre el alcance"msgid "Agree who owns what and set a working rhythm"msgstr "Acuerda quién es responsable de qué y establece un ritmo de trabajo"+msgid "AI couldn't confidently match any accounts"+msgstr "La IA no pudo emparejar con confianza ninguna cuenta"+msgid "AI Tokens"msgstr "Tokens de IA"@@ -1228,6 +1282,10 @@ msgstr "Alinear en el alcance"msgid "All"msgstr "Todos"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "Todas las {0} celdas cierran"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "Todas las {total} fases están completadas. Buen trabajo — tu equipo está en funcionamiento."@@ -1264,9 +1322,15 @@ msgstr "Todas las Ubicaciones"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Todos los miembros de los grupos seleccionados e individuos seleccionados podrán aprobar solicitudes"+msgid "All posting accounts are mapped"+msgstr "Todas las cuentas de registro están asignadas"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "Todas las filas importadas — {inserted} insertadas, {updated} actualizadas."+msgid "All slotted dimension values are mapped"+msgstr "Todos los valores de dimensión asignados están mapeados"+msgid "All Suppliers"msgstr "Todos los proveedores"@@ -1464,6 +1528,9 @@ msgstr "Cualquier tipo de artículo"msgid "Anything not explicitly listed in scope above"msgstr "Cualquier cosa no explícitamente listada en el alcance anterior"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "Análisis de Antigüedad de CxP"@@ -1540,6 +1607,9 @@ msgstr "Aplicar reglas de precios"msgid "Apply Rules On Top"msgstr "Aplicar reglas en la parte superior"+msgid "Apply suggestions"+msgstr "Aplicar sugerencias"+msgid "Apply To"msgstr "Aplicar a"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "Representación de AR / AP"+msgid "AR Aging"msgstr "Análisis de Antigüedad de CxC"@@ -1594,6 +1670,9 @@ msgstr "Cuentas por Cobrar Pendientes"msgid "AR Overdue"msgstr "AR Vencido"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "Archivo"@@ -2146,6 +2225,9 @@ msgstr "Adjunto"msgid "Attachments"msgstr "Adjuntos"+msgid "Attempts"+msgstr "Intentos"+msgid "Attribute"msgstr "Atributo"@@ -2194,6 +2276,9 @@ msgstr "La liberación automática debe estar habilitada para iniciar un trabajomsgid "Auto Start Job"msgstr "Iniciar Trabajo Automáticamente"+msgid "Auto-create"+msgstr "Crear automáticamente"+msgid "Auto-generated QR Code"msgstr "Código QR generado automáticamente"@@ -2440,6 +2525,9 @@ msgstr "Reserva una llamada con Carbon"msgid "Book Depreciation"msgstr "Depreciación de Libro"+msgid "Books lock date (manual)"+msgstr "Fecha de bloqueo de libros (manual)"+msgid "Both"msgstr "Ambos"@@ -2671,6 +2759,9 @@ msgstr "Carbon"msgid "Carbon + you"msgstr "Carbon + tú"+msgid "Carbon account"+msgstr "Cuenta de Carbon"+msgid "Carbon client is not available"msgstr "El cliente de Carbon no está disponible"@@ -2695,9 +2786,19 @@ msgstr "Logo de Carbon"msgid "Carbon only"msgstr "Solo de Carbon"+msgid "Carbon Posted"+msgstr "Carbon Registrado"++msgid "Carbon value"+msgstr "Valor Carbon"+msgid "Carbon Value"msgstr "Valor de Carbon"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon utilizará IA para adivinar una cuenta de proveedor para cada una de sus {0} cuentas no mapeadas. Las sugerencias son un punto de partida — puede revisarlas antes de que se guarde algo."+msgid "Carbon-only"msgstr "Solo de Carbon"@@ -3112,6 +3213,13 @@ msgstr "Código de Barras de Finalización"msgid "Completion Time"msgstr "Tiempo de Finalización"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "calculado {0}"++msgid "Computed At"+msgstr "Calculado en"+msgid "Condensed P&L with margins and key subtotals"msgstr "Estado de Resultados Condensado con márgenes y subtotales clave"@@ -3209,6 +3317,9 @@ msgstr "Confirmar {0}"msgid "Confirm & release"msgstr "Confirmar y liberar"+msgid "Confirm all"+msgstr "Confirmar todo"+msgid "Confirm and sign the scope"msgstr "Confirmar y firmar el alcance"@@ -3661,6 +3772,9 @@ msgstr "No se pudieron cargar los documentos"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "No se pudieron cargar los documentos relacionados. Actualice antes de crear uno nuevo para evitar duplicados."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "No se pudo cargar los destinos de dimensión del proveedor — comprueba la conexión y recarga."+msgid "Couldn't reschedule the job. Please try again."msgstr "No se pudo reprogramar el trabajo. Por favor, inténtelo de nuevo."@@ -4210,6 +4324,9 @@ msgstr "Diariamente"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Controles diarios mientras tu equipo se adapta al sistema en vivo"+msgid "Daily summary"+msgstr "Resumen diario"+msgid "Daily Usage"msgstr "Uso Diario"@@ -4926,6 +5043,12 @@ msgstr "dimensión"msgid "Dimension"msgstr "Dimensión"+msgid "Dimension slots"+msgstr "Espacios de dimensión"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Valores de dimensión en diarios publicados que aún no tienen mapeo de proveedor."+msgid "dimensions"msgstr "dimensiones"@@ -5026,6 +5149,9 @@ msgstr "Disposiciones"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "¿Deseas sobrescribir los permisos actuales del usuario con los permisos predeterminados para este tipo de empleado?"+msgid "Doc-Backed"+msgstr "Respaldado por Documento"+msgid "Docs"msgstr "Documentos"@@ -5050,6 +5176,9 @@ msgstr "Documento:"msgid "Documents"msgstr "Documentos"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Documentos envía facturas, facturas de gasto y pagos como documentos nativos del proveedor; sus diarios se registran como cubiertos por el documento. También extrae pagos registrados en el proveedor a Carbon, cerrando la factura o factura de gasto correspondiente y registrando un diario GL de Carbon. Desactivado los registra como deliberadamente excluidos."+msgid "Don't Cancel"msgstr "No Cancelar"@@ -5975,6 +6104,12 @@ msgstr "Certificado de Exención"msgid "Exemption Reason"msgstr "Motivo de Exención"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Asignaciones existentes. Selecciona una cuenta de proveedor diferente para reasignar."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Mapeos existentes. Elige una opción de proveedor diferente para remapear."+msgid "Expand"msgstr "Expandir"@@ -6111,9 +6246,15 @@ msgstr "Precio Extendido"msgid "External"msgstr "Externo"+msgid "External Delta"+msgstr "Diferencia Externa"+msgid "External document"msgstr "Documento externo"+msgid "External ID"+msgstr "ID Externo"+msgid "External link"msgstr "Enlace externo"@@ -6830,6 +6971,9 @@ msgstr "Los IDs generados están deshabilitados"msgid "Generated IDs are enabled"msgstr "Los IDs generados están habilitados"+msgid "Generating suggestions…"+msgstr "Generando sugerencias…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Ponte en marcha en Carbon: un sistema que ejecuta cotizaciones, compras, planta de producción, inventario y finanzas, reemplazando las herramientas actuales."@@ -7113,6 +7257,9 @@ msgstr "Tasa Histórica (Patrimonio)"msgid "History"msgstr "Historial"+msgid "Hold the journal as a warning to fix."+msgstr "Mantener el diario como advertencia para corregir."+msgid "Holiday"msgstr "Día festivo"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "¿Ideas, sugerencias o problemas?"+msgid "Idempotency key"+msgstr "Clave de Idempotencia"+msgid "Identifiers"msgstr "Identificadores"@@ -7549,6 +7699,9 @@ msgstr "Instrucciones"msgid "Instructions are inherited from the procedure."msgstr "Las instrucciones se heredan del procedimiento."+msgid "Integration"+msgstr "Integración"+msgid "Integration not found"msgstr "Integración no encontrada"@@ -7585,6 +7738,9 @@ msgstr "Ingresos o gastos por intereses de actividades bancarias"msgid "Internal"msgstr "Interno"+msgid "Internal Delta"+msgstr "Diferencia Interna"+msgid "Internal notes"msgstr "Notas internas"@@ -7967,6 +8123,9 @@ msgstr "Los asientos de diario fechados en este período que aún están en Borrmsgid "Journal Entry"msgstr "Asiento de Diario"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "Los diarios con fecha en o antes de esta fecha se tratan como bloqueados. Se fusionan con la fecha de bloqueo reportada por el proveedor cuando ambas existen."+msgid "Just one"msgstr "Solo uno"@@ -8067,6 +8226,12 @@ msgstr "Idioma"msgid "Last 6 Months"msgstr "Últimos 6 Meses"+msgid "Last attempt"+msgstr "Último intento"++msgid "Last Attempt"+msgstr "Último Intento"+msgid "Last Calibration"msgstr "Última Calibración"@@ -8558,6 +8723,12 @@ msgstr "Número de Parte del Fabricante"msgid "Manufacturing"msgstr "Fabricación"+msgid "Map accounts"+msgstr "Asignar cuentas"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Asigna cuentas de Carbon al catálogo de cuentas del proveedor. Los diarios registrados se envían utilizando el código de cuenta de proveedor asignado."+msgid "Map Extracted Invoice Lines"msgstr "Mapear Líneas de Factura Extraídas"@@ -8570,6 +8741,12 @@ msgstr "Mapear líneas ahora"msgid "Map your current process, systems, and data"msgstr "Mapea tu proceso actual, sistemas y datos"+msgid "Mapped accounts"+msgstr "Cuentas Asignadas"++msgid "Mapped values"+msgstr "Valores mapeados"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "¿Marcar \"{0}\" como aprobado?"@@ -8640,6 +8817,12 @@ msgstr "Coincidir con cualquiera"msgid "Match any (OR)"msgstr "Coincidir con cualquiera (O)"+msgid "Match by code"+msgstr "Coincidir por código"++msgid "Match by name"+msgstr "Coincidir por nombre"+msgid "Match none"msgstr "No coincide ninguno"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Mensaje"+msgid "Metadata"+msgstr "Metadatos"+msgid "Method"msgstr "Método"@@ -8856,6 +9042,12 @@ msgstr "Minutos/1000 Piezas"msgid "Minutes/Piece"msgstr "Minutos/Pieza"+msgid "Mismatch"+msgstr "No Coincide"++msgid "Missing"+msgstr "Faltante"+msgid "Missing Information"msgstr "Información Faltante"@@ -9372,6 +9564,10 @@ msgstr "No"msgid "No {0} found"msgstr "No {0} encontrado"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "Sin operaciones de sincronización de {0}"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "Sin {0} aún"@@ -9382,6 +9578,9 @@ msgstr "Sin habilidades añadidas"msgid "No Access"msgstr "Sin acceso"+msgid "No accounts mapped yet"+msgstr "Aún no hay cuentas asignadas"+msgid "No action needed"msgstr "Sin acción necesaria"@@ -9470,6 +9669,12 @@ msgstr "Sin días libres programados"msgid "No default attachments yet."msgstr "Sin adjuntos predeterminados aún."+msgid "No dimension slots configured"+msgstr "No hay espacios de dimensión configurados"++msgid "No dimension values mapped yet"+msgstr "Aún no hay valores de dimensión mapeados"+msgid "No draft make method for this item yet."msgstr "Sin método de fabricación en borrador para este elemento aún."@@ -9635,6 +9840,9 @@ msgstr "Sin pagos aún."msgid "No planning data"msgstr "Sin datos de planificación"+msgid "No posted journals in this period for this account"+msgstr "Sin diarios registrados en este período para esta cuenta"+msgid "No pricing for selected quantity"msgstr "Sin precios para la cantidad seleccionada"@@ -9716,6 +9924,9 @@ msgstr "Sin unidad de almacenamiento"msgid "No suppliers yet"msgstr "Sin proveedores aún"+msgid "No sync operations yet"+msgstr "Sin operaciones de sincronización aún"+msgid "No time entries for this week"msgstr "No hay entradas de tiempo para esta semana"@@ -9728,6 +9939,12 @@ msgstr "Sin herramientas para este paso"msgid "No transactions in this period"msgstr "No hay transacciones en este período"+msgid "No unmapped accounts match a provider code"+msgstr "Ninguna cuenta no asignada coincide con un código de proveedor"++msgid "No unmapped values match a provider option name"+msgstr "Ningún valor sin mapear coincide con el nombre de una opción de proveedor"+msgid "No value needed"msgstr "No se necesita valor"@@ -9803,6 +10020,9 @@ msgstr "No hay suficientes trabajos para cubrir la cantidad"msgid "Not reached"msgstr "No alcanzado"+msgid "Not recorded"+msgstr "No registrado"+msgid "Not referenced anywhere yet."msgstr "Sin referencias aún."@@ -9891,6 +10111,9 @@ msgstr "OEM (fabricante de equipos originales)"msgid "of"msgstr "de"+msgid "Off — handled outside the sync"+msgstr "Off — manejado fuera de la sincronización"+msgid "Off — released revisions stay editable"msgstr "Desactivado — las revisiones lanzadas permanecen editables"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "Albarán de Empaque"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "Rellenar los montos a las posiciones decimales de su moneda, de modo que 300 aparece como 300.00 y las columnas de cifras permanecen alineadas. Desactive esto para mostrar solo los dígitos que tienen valor. Los documentos impresos y los montos almacenados no se ven afectados de ninguna manera."msgid "Page"msgstr "Página"@@ -10418,6 +10641,12 @@ msgstr "Unidad de Almacenamiento Principal"msgid "Pareto by Type"msgstr "Pareto por Tipo"+msgid "Park as error"+msgstr "Estacionar como error"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Aparcar el diario con una advertencia hasta que el valor esté mapeado"+msgid "part"msgstr "piezas"@@ -10478,6 +10707,9 @@ msgstr "Tasa de Pago"msgid "Payables"msgstr "Cuentas por Pagar (predeterminada)"+msgid "Payables (AP)"+msgstr "Cuentas por pagar (AP)"+msgid "Payables (default)"msgstr "término de pago"@@ -10574,6 +10806,9 @@ msgstr "Cierre de período"msgid "Period End"msgstr "Fin del Período"+msgid "Period lock policy"+msgstr "Política de Bloqueo de Período"+msgid "Periodic depreciation expense for fixed assets"msgstr "La selección ofrece entidades rastreadas en orden de vencimiento más antiguo primero, por lo que el inventario que expira más pronto se agota primero de forma predeterminada."@@ -10613,6 +10848,9 @@ msgstr "Impresoras físicas disponibles para asignación."msgid "Pick"msgstr "Seleccionar"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Elige una dimensión Carbon y el destino del proveedor al que se publica. Crear automáticamente añade opciones de proveedor faltantes por nombre en el momento del envío."+msgid "Pick a column to sort by"msgstr "Elige una columna para ordenar"@@ -10834,6 +11072,9 @@ msgstr "Publicado por"msgid "Posted By"msgstr "Publicado por"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "Los diarios publicados con estos tipos de origen siempre se sincronizan. El resumen diario agrupa los diarios de un día en una entrada de proveedor por cuenta."+msgid "Posted once, corrected {corrections} times."msgstr "Publicado una vez, corregido {corrections} veces."@@ -11124,6 +11365,12 @@ msgstr "Propiedades"msgid "Property"msgstr "Propiedad"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Coincidencias propuestas donde el número de cuenta de Carbon es exactamente igual al código de cuenta del proveedor."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Coincidencias propuestas donde el nombre del valor de dimensión Carbon es igual al nombre de la opción del proveedor exactamente."+msgid "Protect the go-live date"msgstr "Proteger la fecha de puesta en marcha"@@ -11133,6 +11380,15 @@ msgstr "Protege el tiempo de capacitación y asiste"msgid "Provide process knowledge and inputs"msgstr "Proporcionar conocimiento del proceso e información"+msgid "Provider"+msgstr "Proveedor"++msgid "Provider account"+msgstr "Cuenta del proveedor"++msgid "Provider option"+msgstr "Opción de proveedor"+msgid "Public"msgstr "Público"@@ -11146,9 +11402,15 @@ msgstr "¿Publicar versión {0}?"msgid "Published by Carbon"msgstr "Publicado por Carbon"+msgid "Pull"+msgstr "Extraer"+msgid "Pull From"msgstr "Extraer de"+msgid "Pull from accounting"+msgstr "Extraer de contabilidad"+msgid "Pull from Inventory"msgstr "Extraer del Inventario"@@ -11272,9 +11534,21 @@ msgstr "Facturas de Compra"msgid "Purchasing Unit of Measure"msgstr "Unidad de Medida de Compra"+msgid "Push"+msgstr "Enviar"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "Enviarlo con nueva fecha al primer día abierto, manteniendo la fecha original en la narración."+msgid "Push record changes to external systems the moment they happen."msgstr "Envía cambios de registros a sistemas externos en el momento en que ocurren."+msgid "Push the journal without the dimension"+msgstr "Enviar el diario sin la dimensión"++msgid "Push to accounting"+msgstr "Enviar a contabilidad"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "Código QR para crear un {0} para este kanban"@@ -11481,9 +11755,15 @@ msgstr "Materias Primas"msgid "Raw Materials (default)"msgstr "Materias Primas (predeterminado)"+msgid "Re-date to first open day"+msgstr "Redatar al primer día abierto"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Re-ingreso de datos entre cotización, piso de producción y finanzas"+msgid "Re-send"+msgstr "Reenviar"+msgid "Reactivate"msgstr "Reactivar"@@ -11505,6 +11785,9 @@ msgstr "ID legible con revisión"msgid "Reading the document..."msgstr "Leyendo el documento..."+msgid "Ready"+msgstr "Listo"+msgid "Ready for Quote"msgstr "Listo para cotizar"@@ -11577,6 +11860,9 @@ msgstr "Los recibos, envíos, facturas de venta, facturas de compra, pagos y notmsgid "Receivables"msgstr "Cuentas por Cobrar (predeterminada)"+msgid "Receivables (AR)"+msgstr "Cuentas por cobrar (AR)"+msgid "Receivables (default)"msgstr "Conciliación de una orden de compra con lo que se recibió y se facturó — implícito en Carbon, a través de las cantidades de línea y el balance GR/IR."@@ -11635,6 +11921,9 @@ msgstr "Creado Recientemente"msgid "Reconcile"msgstr "Reconciliar"+msgid "Reconciliation found discrepancies with the provider"+msgstr "La reconciliación encontró discrepancias con el proveedor"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Período de Recuperación"@@ -11813,6 +12102,9 @@ msgstr "Eliminar fila"msgid "Remove slide"msgstr "Eliminar diapositiva"+msgid "Remove slot"+msgstr "Eliminar espacio"+msgid "Remove sort by column"msgstr "Eliminar ordenamiento por columna"@@ -12047,6 +12339,9 @@ msgstr "Retirar un activo de servicio mediante desecho o venta, registrando cualmsgid "Retry"msgstr "Reintentar"+msgid "Retry all"+msgstr "Reintentar todo"+msgid "Return Home"msgstr "Volver al Inicio"@@ -12098,6 +12393,9 @@ msgstr "Revisa los cambios de cada elemento y confirma — liberar no se puede dmsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Revise el balance general y el estado de resultados del período y confirme que las cifras se ven correctas. Este es un visto bueno manual — marque como hecho una vez que los haya revisado."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Revise los emparejamientos sugeridos antes de aplicarlos. Estos son una mejor suposición — confirme que cada uno es correcto."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Revise las advertencias a continuación, luego registre el conteo para aplicar los ajustes."@@ -12153,6 +12451,9 @@ msgstr "Número de RFQ"msgid "RFQs"msgstr "RFQs"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Llevar dimensiones Carbon junto en diarios enviados. Cada espacio mapea una dimensión Carbon a un destino de análisis del proveedor; el mapeo de valores a continuación empareja valores de dimensión individuales con opciones de proveedor."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Guardar aplicaciones"msgid "Save contacts"msgstr "Guardar contactos"+msgid "Save dimension settings"+msgstr "Guardar configuración de dimensión"+msgid "Save Method"msgstr "Guardar Método"@@ -12759,6 +13063,9 @@ msgstr "Seleccionar tipos de cliente"msgid "Select customers"msgstr "Seleccionar clientes"+msgid "Select dimension"+msgstr "Seleccionar dimensión"+msgid "Select Employee"msgstr "Seleccionar Empleado"@@ -12795,6 +13102,15 @@ msgstr "Seleccionar método..."msgid "Select Printer"msgstr "Seleccionar Impresora"+msgid "Select provider account"+msgstr "Seleccionar cuenta del proveedor"++msgid "Select provider target"+msgstr "Seleccionar destino del proveedor"++msgid "Select provider value"+msgstr "Seleccionar valor del proveedor"+msgid "Select Quantities"msgstr "Seleccionar Cantidades"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "Mostrar opciones de sincronización"msgid "Show Trailing Zeros"-msgstr ""+msgstr "Mostrar Ceros Finales"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "Mostrando en {parentCurrency}"msgid "Showing the first 500 lines"msgstr "Mostrando las primeras 500 líneas"+msgid "Showing the newest 200 journals"+msgstr "Mostrando los 200 diarios más recientes"+msgid "Showing the top 1,000 groups by amount"msgstr "Mostrando los 1,000 grupos principales por cantidad"@@ -13383,6 +13702,9 @@ msgstr "Lista de origen"msgid "Source Method"msgstr "Método de Origen"+msgid "Source types"+msgstr "Tipos de origen"+msgid "Source Version"msgstr "Versión de Origen"@@ -13721,6 +14043,15 @@ msgstr "Pieza Sucesora"msgid "Suffix"msgstr "Sufijo"+msgid "Suggest mappings"+msgstr "Sugerir emparejamientos"++msgid "Suggest mappings with AI"+msgstr "Sugerir emparejamientos con IA"++msgid "Suggest with AI"+msgstr "Sugerir con IA"+msgid "Suggested orders you haven't placed yet."msgstr "Pedidos sugeridos que aún no ha realizado."@@ -13926,6 +14257,18 @@ msgstr "Cambiar el tipo de empleado aquí no cambia sus permisos existentes; elmsgid "Sync"msgstr "Sincronizar"+msgid "Sync Activity"+msgstr "Actividad de sincronización"++msgid "Sync operation"+msgstr "Operación de sincronización"++msgid "Sync Tie-Out"+msgstr "Sincronización de Cierre"++msgid "Synced"+msgstr "Sincronizado"+msgid "System"msgstr "Sistema"@@ -14599,6 +14942,9 @@ msgstr "El procedimiento que siguen los técnicos cuando se realiza este mantenimsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "Los procesos que este centro de trabajo puede ejecutar; aparece en selectores de proceso al programar operaciones, y limita qué trabajos pueden fluir a través de este centro de trabajo."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "El proveedor no ofrece destinos de dimensión. Habilita la función en el proveedor primero (p. ej. categorías de seguimiento, seguimiento de clases o campos)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Los puntos de ruptura de cantidad a los que se cotiza esta línea; cada columna lleva su propio precio por unidad para la negociación comprador-proveedor y para la conversión a documentos posteriores."@@ -15077,6 +15423,9 @@ msgstr "Jueves"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Vincular envíos a una factura sin re-ingreso de datos"+msgid "Tie-out"+msgstr "Cierre"+msgid "Tie-Out"msgstr "Conciliación"@@ -15533,9 +15882,18 @@ msgstr "¿Desenlazar trabajo de la orden de venta?"msgid "Unlock"msgstr "Desbloquear"+msgid "Unmapped accounts"+msgstr "Cuentas no asignadas"++msgid "Unmapped dimension values"+msgstr "Valores de dimensión sin mapear"+msgid "Unmapped Extracted Lines"msgstr "Líneas Extraídas Sin Asignar"+msgid "Unmapped values"+msgstr "Valores sin mapear"+msgid "Unmatched"msgstr "Sin emparejar"@@ -16077,6 +16435,9 @@ msgstr "Ver Sugerencia"msgid "View Suppliers"msgstr "Ver Proveedores"+msgid "View tie-out"+msgstr "Ver cierre"+msgid "View Traceability Graph"msgstr "Ver Gráfico de Trazabilidad"@@ -16283,6 +16644,9 @@ msgstr "Qué datos"msgid "What drove inventory up or down, by any dimension"msgstr "Qué impulsó el inventario hacia arriba o hacia abajo, por cualquier dimensión"+msgid "What happens when a journal is dated in a locked period."+msgstr "¿Qué sucede cuando un diario está fechado en un período cerrado?"+msgid "What is {translatedTerm}?"msgstr "¿Qué es {translatedTerm}?"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex c1b6d1313a..24be449164 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "Un fournisseur est une entreprise ou une personne qui vous vend des pièces ou des services."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— dernier vérification {0}"+msgid ", {residual}% residual"msgstr ", {residual}% résiduel"@@ -56,6 +60,10 @@ msgstr "{0} comptes"msgid "{0} ago"msgstr "{0} il y a"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} cellules avec écarts"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} clients avec un solde"@@ -81,6 +89,15 @@ msgstr "{0} tâches créées"msgid "{0} lines to map"msgstr "{0} lignes à mapper"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} sur {1} comptes de comptabilisation mappés"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} sur {maxSlots} emplacements de fournisseur utilisés"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} commandes"@@ -101,6 +118,11 @@ msgstr "{0} fournisseurs avec un solde"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} entités non échantillonnées seront libérées en Disponible. Les passes échantillonnées restent Disponible et les défaillances échantillonnées restent Rejetées."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} comptes non mappés seront appariés à {1} comptes de fournisseur."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} documents non comptabilisés"@@ -109,6 +131,11 @@ msgstr "{0} documents non comptabilisés"msgid "{0} uploaded successfully"msgstr "{0} téléchargé avec succès"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} valeurs"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} valeurs manquantes"@@ -134,6 +161,9 @@ msgstr "{done} sur {total} phases terminées"msgid "{from}–{to} of {count}"msgstr "{from}–{to} sur {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} sur {count} opérations"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# ligne} other {# lignes}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB limite"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} mois avec des totaux non concordants"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} journaux manquants chez le fournisseur"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} journaux manquants et {mismatchCount} mois non concordants"+msgid "{name} deleted"msgstr "{name} supprimé"@@ -198,6 +237,9 @@ msgstr "↩ {0} redirigé depuis {1} obsolète"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Ajoutez une pièce fournisseur</0> pour cet article pour définir un fournisseur préféré."+msgid "0 operations"+msgstr "0 opération"+msgid "0-4 weeks"msgstr "0-4 semaines"@@ -813,6 +855,9 @@ msgstr "Responsable de compte"msgid "Account Manager"msgstr "Gestionnaire de compte"+msgid "Account Mapping"+msgstr "Mappage des comptes"+msgid "Account Number"msgstr "Numéro de compte"@@ -870,6 +915,9 @@ msgstr "Comptes débiteurs"msgid "Accounts receivable for amounts owed by customers"msgstr "Comptes débiteurs pour les montants dus par les clients."+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Comptes référencés par les valeurs par défaut de comptabilisation ou l'historique des journaux qui n'ont pas encore de mappage fournisseur."+msgid "Accumulated Depreciation"msgstr "Amortissement cumulé"@@ -1128,6 +1176,9 @@ msgstr "Ajouter un envoi"msgid "Add Shipping"msgstr "Ajouter l'expédition"+msgid "Add slot"+msgstr "Ajouter un emplacement"+msgid "Add Spare Part"msgstr "Ajouter une pièce de rechange"@@ -1219,6 +1270,9 @@ msgstr "Convenir sur la portée"msgid "Agree who owns what and set a working rhythm"msgstr "Convenir de qui est responsable de quoi et établir un rythme de travail"+msgid "AI couldn't confidently match any accounts"+msgstr "L'IA n'a pas pu apparier avec confiance aucun compte"+msgid "AI Tokens"msgstr "Jetons IA"@@ -1228,6 +1282,10 @@ msgstr "Aligner sur la portée"msgid "All"msgstr "Tous"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "Toutes les {0} cellules correspondent"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "Toutes les {total} phases sont terminées. Bravo — votre équipe est opérationnelle."@@ -1264,9 +1322,15 @@ msgstr "Tous les Emplacements"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Tous les membres des groupes sélectionnés et les individus sélectionnés pourront approuver les demandes"+msgid "All posting accounts are mapped"+msgstr "Tous les comptes de comptabilisation sont mappés"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "Toutes les lignes importées — {inserted} insérées, {updated} mises à jour."+msgid "All slotted dimension values are mapped"+msgstr "Toutes les valeurs de dimension assignées sont mappées"+msgid "All Suppliers"msgstr "Tous les fournisseurs"@@ -1464,6 +1528,9 @@ msgstr "Tout type d'article"msgid "Anything not explicitly listed in scope above"msgstr "Tout ce qui n'est pas explicitement listé dans le périmètre ci-dessus"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "Analyse AP"@@ -1540,6 +1607,9 @@ msgstr "Appliquer les règles de tarification"msgid "Apply Rules On Top"msgstr "Appliquer les règles en premier"+msgid "Apply suggestions"+msgstr "Appliquer les suggestions"+msgid "Apply To"msgstr "Appliquer à"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "NQA (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "Représentation AR / AP"+msgid "AR Aging"msgstr "Analyse AR"@@ -1594,6 +1670,9 @@ msgstr "Créances clients en attente"msgid "AR Overdue"msgstr "AR En retard"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "Archiver"@@ -2146,6 +2225,9 @@ msgstr "Pièce jointe"msgid "Attachments"msgstr "Pièces jointes"+msgid "Attempts"+msgstr "Tentatives"+msgid "Attribute"msgstr "Attribut"@@ -2194,6 +2276,9 @@ msgstr "La libération automatique doit être activée pour démarrer un travailmsgid "Auto Start Job"msgstr "Démarrage automatique du travail"+msgid "Auto-create"+msgstr "Création automatique"+msgid "Auto-generated QR Code"msgstr "Code QR généré automatiquement"@@ -2440,6 +2525,9 @@ msgstr "Réserver un appel avec Carbon"msgid "Book Depreciation"msgstr "Amortissement comptable"+msgid "Books lock date (manual)"+msgstr "Date de verrouillage des livres (manuel)"+msgid "Both"msgstr "Les deux"@@ -2671,6 +2759,9 @@ msgstr "Carbone"msgid "Carbon + you"msgstr "Carbon + vous"+msgid "Carbon account"+msgstr "Compte Carbon"+msgid "Carbon client is not available"msgstr "Le client Carbon n'est pas disponible"@@ -2695,9 +2786,19 @@ msgstr "Logo Carbon"msgid "Carbon only"msgstr "Carbone uniquement"+msgid "Carbon Posted"+msgstr "Enregistré dans Carbon"++msgid "Carbon value"+msgstr "Valeur Carbon"+msgid "Carbon Value"msgstr "Valeur Carbon"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon utilisera l'IA pour deviner un compte de fournisseur pour chacun de vos {0} comptes non mappés. Les suggestions sont un point de départ — vous pouvez les examiner avant que rien ne soit enregistré."+msgid "Carbon-only"msgstr "Carbone uniquement"@@ -3112,6 +3213,13 @@ msgstr "Code-barres d'achèvement"msgid "Completion Time"msgstr "Temps d'exécution"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "calculé {0}"++msgid "Computed At"+msgstr "Calculé le"+msgid "Condensed P&L with margins and key subtotals"msgstr "Compte de résultat condensé avec marges et sous-totaux clés"@@ -3209,6 +3317,9 @@ msgstr "Confirmer {0}"msgid "Confirm & release"msgstr "Confirmer et publier"+msgid "Confirm all"+msgstr "Confirmer tout"+msgid "Confirm and sign the scope"msgstr "Confirmer et signer l'étendue"@@ -3661,6 +3772,9 @@ msgstr "Impossible de charger les documents"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Impossible de charger les documents associés. Actualisez avant d'en créer un nouveau pour éviter les doublons."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "Impossible de charger les cibles de dimension du fournisseur — vérifiez la connexion et rechargez."+msgid "Couldn't reschedule the job. Please try again."msgstr "Impossible de reprogrammer le travail. Veuillez réessayer."@@ -4210,6 +4324,9 @@ msgstr "Quotidien"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Vérifications quotidiennes pendant que votre équipe prend ses marques sur le système en direct"+msgid "Daily summary"+msgstr "Résumé quotidien"+msgid "Daily Usage"msgstr "Utilisation quotidienne"@@ -4926,6 +5043,12 @@ msgstr "dimension"msgid "Dimension"msgstr "Dimension"+msgid "Dimension slots"+msgstr "Emplacements de dimension"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Valeurs de dimension sur les journaux postés qui n'ont pas encore de mappage de fournisseur."+msgid "dimensions"msgstr "dimensions"@@ -5026,6 +5149,9 @@ msgstr "Dispositions"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "Voulez-vous remplacer les permissions actuelles de l'utilisateur par les permissions par défaut pour ce type d'employé ?"+msgid "Doc-Backed"+msgstr "Adossé à un document"+msgid "Docs"msgstr "Documentation"@@ -5050,6 +5176,9 @@ msgstr "Document :"msgid "Documents"msgstr "Documents"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Documents envoie les factures, les factures fournisseur et les paiements en tant que documents fournisseur natifs ; leurs journaux sont enregistrés comme couverts par le document. Il tire également les paiements enregistrés chez le fournisseur dans Carbon, ferme la facture ou la facture fournisseur correspondante et enregistre un journal GL Carbon. Off les enregistre comme volontairement exclus."+msgid "Don't Cancel"msgstr "Ne pas annuler"@@ -5975,6 +6104,12 @@ msgstr "Certificat d'Exonération"msgid "Exemption Reason"msgstr "Motif d'Exonération"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Mappages existants. Choisissez un compte fournisseur différent pour remapper."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Mappages existants. Choisissez une option de fournisseur différente pour remapper."+msgid "Expand"msgstr "Développer"@@ -6111,9 +6246,15 @@ msgstr "Prix étendu"msgid "External"msgstr "Externe"+msgid "External Delta"+msgstr "Écart externe"+msgid "External document"msgstr "Document externe"+msgid "External ID"+msgstr "ID externe"+msgid "External link"msgstr "Lien externe"@@ -6830,6 +6971,9 @@ msgstr "Les IDs générés sont désactivés"msgid "Generated IDs are enabled"msgstr "Les IDs générés sont activés"+msgid "Generating suggestions…"+msgstr "Génération des suggestions…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Passer en direct sur Carbon : un seul système pour les devis, les achats, l'atelier, l'inventaire et la finance, remplaçant les outils actuels."@@ -7113,6 +7257,9 @@ msgstr "Taux Historique (Capitaux Propres)"msgid "History"msgstr "Historique"+msgid "Hold the journal as a warning to fix."+msgstr "Mettre le journal en attente comme avertissement pour correction."+msgid "Holiday"msgstr "Jour férié"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "Des idées, des suggestions ou des problèmes ?"+msgid "Idempotency key"+msgstr "Clé d'idempotence"+msgid "Identifiers"msgstr "Identifiants"@@ -7549,6 +7699,9 @@ msgstr "Instructions"msgid "Instructions are inherited from the procedure."msgstr "Les instructions sont héritées de la procédure."+msgid "Integration"+msgstr "Intégration"+msgid "Integration not found"msgstr "Intégration introuvable"@@ -7585,6 +7738,9 @@ msgstr "Revenu ou charge d'intérêt provenant d'activités bancaires"msgid "Internal"msgstr "Interne"+msgid "Internal Delta"+msgstr "Écart interne"+msgid "Internal notes"msgstr "Notes internes"@@ -7967,6 +8123,9 @@ msgstr "Les écritures de journal datées de cette période qui sont encore Broumsgid "Journal Entry"msgstr "Écriture de journal"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "Les journaux datés à cette date ou avant sont traités comme verrouillés. Fusionnés avec la date de verrouillage rapportée par le fournisseur quand les deux existent."+msgid "Just one"msgstr "Un seul"@@ -8067,6 +8226,12 @@ msgstr "Langue"msgid "Last 6 Months"msgstr "6 derniers mois"+msgid "Last attempt"+msgstr "Dernière tentative"++msgid "Last Attempt"+msgstr "Dernière tentative"+msgid "Last Calibration"msgstr "Dernier étalonnage"@@ -8558,6 +8723,12 @@ msgstr "Numéro de pièce du fabricant"msgid "Manufacturing"msgstr "Fabrication"+msgid "Map accounts"+msgstr "Mapper les comptes"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Mappez les comptes Carbon au plan comptable du fournisseur. Les journaux comptabilisés sont poussés en utilisant le code de compte fournisseur mappé."+msgid "Map Extracted Invoice Lines"msgstr "Mapper les lignes de facture extraites"@@ -8570,6 +8741,12 @@ msgstr "Mapper les lignes maintenant"msgid "Map your current process, systems, and data"msgstr "Cartographiez votre processus actuel, vos systèmes et vos données"+msgid "Mapped accounts"+msgstr "Comptes mappés"++msgid "Mapped values"+msgstr "Valeurs mappées"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "Marquer « {0} » comme réussi ?"@@ -8640,6 +8817,12 @@ msgstr "Correspondre à au moins un"msgid "Match any (OR)"msgstr "Correspondre à l'un (OU)"+msgid "Match by code"+msgstr "Correspondance par code"++msgid "Match by name"+msgstr "Correspondance par nom"+msgid "Match none"msgstr "Ne correspond à aucun"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Message"+msgid "Metadata"+msgstr "Métadonnées"+msgid "Method"msgstr "Méthode"@@ -8856,6 +9042,12 @@ msgstr "Minutes/1000 Pièces"msgid "Minutes/Piece"msgstr "Minutes/Pièce"+msgid "Mismatch"+msgstr "Non-concordance"++msgid "Missing"+msgstr "Manquant"+msgid "Missing Information"msgstr "Informations manquantes"@@ -9372,6 +9564,10 @@ msgstr "Non"msgid "No {0} found"msgstr "Aucun {0} trouvé"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "Aucune opération de synchronisation {0}"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "Pas encore de {0}"@@ -9382,6 +9578,9 @@ msgstr "Aucune compétence ajoutée"msgid "No Access"msgstr "Aucun accès"+msgid "No accounts mapped yet"+msgstr "Aucun compte mappé pour le moment"+msgid "No action needed"msgstr "Aucune action requise"@@ -9470,6 +9669,12 @@ msgstr "Aucun jour de congé prévu"msgid "No default attachments yet."msgstr "Aucune pièce jointe par défaut pour le moment."+msgid "No dimension slots configured"+msgstr "Aucun emplacement de dimension configuré"++msgid "No dimension values mapped yet"+msgstr "Aucune valeur de dimension mappée pour le moment"+msgid "No draft make method for this item yet."msgstr "Aucune méthode de fabrication de brouillon pour cet article pour le moment."@@ -9635,6 +9840,9 @@ msgstr "Aucun paiement pour le moment."msgid "No planning data"msgstr "Aucune donnée de planification"+msgid "No posted journals in this period for this account"+msgstr "Aucun journal enregistré pour ce compte au cours de cette période"+msgid "No pricing for selected quantity"msgstr "Aucun tarif pour la quantité sélectionnée"@@ -9716,6 +9924,9 @@ msgstr "Aucune unité de stockage"msgid "No suppliers yet"msgstr "Aucun fournisseur pour le moment"+msgid "No sync operations yet"+msgstr "Aucune opération de synchronisation pour le moment"+msgid "No time entries for this week"msgstr "Aucune entrée de temps pour cette semaine"@@ -9728,6 +9939,12 @@ msgstr "Pas d'outils pour cette étape"msgid "No transactions in this period"msgstr "Aucune transaction au cours de cette période"+msgid "No unmapped accounts match a provider code"+msgstr "Aucun compte non mappé ne correspond à un code fournisseur"++msgid "No unmapped values match a provider option name"+msgstr "Aucune valeur non mappée ne correspond à un nom d'option de fournisseur"+msgid "No value needed"msgstr "Aucune valeur requise"@@ -9803,6 +10020,9 @@ msgstr "Pas assez de tâches pour couvrir la quantité"msgid "Not reached"msgstr "Non atteint"+msgid "Not recorded"+msgstr "Non enregistré"+msgid "Not referenced anywhere yet."msgstr "Non référencé nulle part pour le moment."@@ -9891,6 +10111,9 @@ msgstr "OEM (fabricant d'équipement d'origine)"msgid "of"msgstr "de"+msgid "Off — handled outside the sync"+msgstr "Off — géré en dehors de la synchronisation"+msgid "Off — released revisions stay editable"msgstr "Désactivé — les révisions publiées restent modifiables"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "Bon de livraison"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "Complétez les montants selon les décimales de leur devise, de sorte que 300 s'affiche comme 300.00 et que les colonnes de chiffres restent alignées. Désactivez cette option pour afficher uniquement les chiffres significatifs. Les documents imprimés et les montants stockés ne sont affectés d'aucune manière."msgid "Page"msgstr "Page"@@ -10418,6 +10641,12 @@ msgstr "Unité de stockage parent"msgid "Pareto by Type"msgstr "Pareto par Type"+msgid "Park as error"+msgstr "Parquer comme erreur"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Archiver le journal avec un avertissement jusqu'à ce que la valeur soit mappée"+msgid "part"msgstr "pièces"@@ -10478,6 +10707,9 @@ msgstr "Taux de paiement"msgid "Payables"msgstr "Comptes Créditeurs (par défaut)"+msgid "Payables (AP)"+msgstr "Comptes fournisseurs (AP)"+msgid "Payables (default)"msgstr "condition de paiement"@@ -10574,6 +10806,9 @@ msgstr "Clôture de période"msgid "Period End"msgstr "Fin de période"+msgid "Period lock policy"+msgstr "Politique de verrouillage des périodes"+msgid "Periodic depreciation expense for fixed assets"msgstr "Le prélèvement offre des entités suivies dans l'ordre d'expiration le plus proche d'abord, de sorte que le stock qui expire le plus tôt est épuisé en premier par défaut."@@ -10613,6 +10848,9 @@ msgstr "Imprimantes physiques disponibles pour l'attribution."msgid "Pick"msgstr "Prélever"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Choisissez une dimension Carbon et la cible du fournisseur à laquelle elle est postée. La création automatique ajoute les options de fournisseur manquantes par nom au moment de la poussée."+msgid "Pick a column to sort by"msgstr "Choisir une colonne pour trier"@@ -10834,6 +11072,9 @@ msgstr "Publié par"msgid "Posted By"msgstr "Publié par"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "Les journaux publiés avec ces types de sources se synchronisent toujours. Le résumé quotidien regroupe les journaux d'une journée en une seule entrée de fournisseur par compte."+msgid "Posted once, corrected {corrections} times."msgstr "Posté une fois, corrigé {corrections} fois."@@ -11124,6 +11365,12 @@ msgstr "Propriétés"msgid "Property"msgstr "Propriété"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Correspondances proposées où le numéro de compte Carbon est exactement égal au code de compte fournisseur."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Correspondances proposées où le nom de la valeur de dimension Carbon est exactement égal au nom d'une option de fournisseur."+msgid "Protect the go-live date"msgstr "Protéger la date de mise en production"@@ -11133,6 +11380,15 @@ msgstr "Protégez le temps de formation et participez"msgid "Provide process knowledge and inputs"msgstr "Fournir les connaissances et les données du processus"+msgid "Provider"+msgstr "Fournisseur"++msgid "Provider account"+msgstr "Compte du fournisseur"++msgid "Provider option"+msgstr "Option de fournisseur"+msgid "Public"msgstr "Public"@@ -11146,9 +11402,15 @@ msgstr "Publier la version {0} ?"msgid "Published by Carbon"msgstr "Publié par Carbon"+msgid "Pull"+msgstr "Récupérer"+msgid "Pull From"msgstr "Prélever de"+msgid "Pull from accounting"+msgstr "Récupérer de la comptabilité"+msgid "Pull from Inventory"msgstr "Prélever du stock"@@ -11272,9 +11534,21 @@ msgstr "Factures d'achat"msgid "Purchasing Unit of Measure"msgstr "Unité de mesure d'achat"+msgid "Push"+msgstr "Envoyer"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "Repousser sa date au premier jour ouvert, en conservant la date d'origine dans la narration."+msgid "Push record changes to external systems the moment they happen."msgstr "Poussez les modifications d'enregistrements vers des systèmes externes au moment où elles se produisent."+msgid "Push the journal without the dimension"+msgstr "Pousser le journal sans la dimension"++msgid "Push to accounting"+msgstr "Envoyer vers la comptabilité"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "Code QR pour créer un {0} pour ce kanban"@@ -11481,9 +11755,15 @@ msgstr "Matières Premières"msgid "Raw Materials (default)"msgstr "Matières Premières (par défaut)"+msgid "Re-date to first open day"+msgstr "Redater au premier jour ouvert"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Ressaisie entre les devis, l'atelier et la finance"+msgid "Re-send"+msgstr "Renvoyer"+msgid "Reactivate"msgstr "Réactiver"@@ -11505,6 +11785,9 @@ msgstr "ID lisible avec révision"msgid "Reading the document..."msgstr "Lecture du document..."+msgid "Ready"+msgstr "Prêt"+msgid "Ready for Quote"msgstr "Prêt pour devis"@@ -11577,6 +11860,9 @@ msgstr "Les reçus, expéditions, factures de vente, factures d'achat, paiementsmsgid "Receivables"msgstr "Comptes Clients (par défaut)"+msgid "Receivables (AR)"+msgstr "Comptes clients (AR)"+msgid "Receivables (default)"msgstr "Rapprochement d'une commande d'achat avec ce qui a été reçu et facturé — implicite dans Carbon, via les quantités de ligne et le solde GR/IR."@@ -11635,6 +11921,9 @@ msgstr "Récemment créé"msgid "Reconcile"msgstr "Rapprocher"+msgid "Reconciliation found discrepancies with the provider"+msgstr "La rapprochement a détecté des écarts avec le fournisseur"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Durée d'Amortissement"@@ -11813,6 +12102,9 @@ msgstr "Supprimer la ligne"msgid "Remove slide"msgstr "Supprimer la diapositive"+msgid "Remove slot"+msgstr "Supprimer l'emplacement"+msgid "Remove sort by column"msgstr "Supprimer le tri par colonne"@@ -12047,6 +12339,9 @@ msgstr "Mise hors service d'un actif par mise au rebut ou par vente, en comptabimsgid "Retry"msgstr "Réessayer"+msgid "Retry all"+msgstr "Réessayer tous"+msgid "Return Home"msgstr "Retour à l'accueil"@@ -12098,6 +12393,9 @@ msgstr "Examinez les changements de chaque article, puis confirmez — la publicmsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Examinez le bilan et le compte de résultat de la période et confirmez que les chiffres semblent corrects. Ceci est une approbation manuelle — marquez-la comme terminée une fois que vous les avez examinés."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Passez en revue les correspondances suggérées avant d'appliquer. Ce sont une meilleure conjecture — confirmez que chacune est correcte."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Examinez les avertissements ci-dessous, puis validez le comptage pour appliquer les ajustements."@@ -12153,6 +12451,9 @@ msgstr "Numéro de RFQ"msgid "RFQs"msgstr "Appels d'offres"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Faites voyager les dimensions Carbon sur les journaux poussés. Chaque emplacement mappe une dimension Carbon à une cible d'analyse du fournisseur ; le mappage des valeurs ci-dessous associe les valeurs de dimension individuelles aux options du fournisseur."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Enregistrer les applications"msgid "Save contacts"msgstr "Enregistrer les contacts"+msgid "Save dimension settings"+msgstr "Enregistrer les paramètres de dimension"+msgid "Save Method"msgstr "Enregistrer la méthode"@@ -12759,6 +13063,9 @@ msgstr "Sélectionner les types de clients"msgid "Select customers"msgstr "Sélectionner les clients"+msgid "Select dimension"+msgstr "Sélectionner une dimension"+msgid "Select Employee"msgstr "Sélectionner un employé"@@ -12795,6 +13102,15 @@ msgstr "Sélectionner une méthode..."msgid "Select Printer"msgstr "Sélectionner l'imprimante"+msgid "Select provider account"+msgstr "Sélectionner le compte du fournisseur"++msgid "Select provider target"+msgstr "Sélectionner la cible du fournisseur"++msgid "Select provider value"+msgstr "Sélectionner la valeur du fournisseur"+msgid "Select Quantities"msgstr "Sélectionner les quantités"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "Afficher les options de synchronisation"msgid "Show Trailing Zeros"-msgstr ""+msgstr "Afficher les zéros de fin"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "Affichage en {parentCurrency}"msgid "Showing the first 500 lines"msgstr "Affichage des 500 premières lignes"+msgid "Showing the newest 200 journals"+msgstr "Affichage des 200 journaux les plus récents"+msgid "Showing the top 1,000 groups by amount"msgstr "Affichage des 1 000 meilleurs groupes par montant"@@ -13383,6 +13702,9 @@ msgstr "Liste source"msgid "Source Method"msgstr "Méthode source"+msgid "Source types"+msgstr "Types de source"+msgid "Source Version"msgstr "Version source"@@ -13721,6 +14043,15 @@ msgstr "Pièce successeur"msgid "Suffix"msgstr "Suffixe"+msgid "Suggest mappings"+msgstr "Suggérer des mappages"++msgid "Suggest mappings with AI"+msgstr "Suggérer des mappages avec l'IA"++msgid "Suggest with AI"+msgstr "Suggérer avec l'IA"+msgid "Suggested orders you haven't placed yet."msgstr "Commandes suggérées que vous n'avez pas encore passées."@@ -13926,6 +14257,18 @@ msgstr "Changer le type d'employé ici ne change pas ses permissions existantes;msgid "Sync"msgstr "Synchroniser"+msgid "Sync Activity"+msgstr "Activité de synchronisation"++msgid "Sync operation"+msgstr "Opération de synchronisation"++msgid "Sync Tie-Out"+msgstr "Rapprochement de synchronisation"++msgid "Synced"+msgstr "Synchronisé"+msgid "System"msgstr "Système"@@ -14599,6 +14942,9 @@ msgstr "La procédure que les techniciens suivent lors de l'exécution de cet enmsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "Les processus que ce centre de travail peut exécuter; apparaît dans les sélecteurs de processus lors de la planification des opérations, et limite les travaux qui peuvent traverser ce centre de travail."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "Le fournisseur n'offre aucune cible de dimension. Activez d'abord la fonctionnalité dans le fournisseur (par exemple, les catégories de suivi, le suivi de classe ou les champs)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Les points d'arrêt de quantité à laquelle cette ligne est tarifée; chaque colonne porte son propre prix par unité pour la négociation acheteur-fournisseur et la conversion en documents aval."@@ -15077,6 +15423,9 @@ msgstr "Jeudi"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Lier les expéditions à une facture sans ressaisie"+msgid "Tie-out"+msgstr "Rapprochement"+msgid "Tie-Out"msgstr "Rapprochement"@@ -15533,9 +15882,18 @@ msgstr "Dissocier la commande de la commande client ?"msgid "Unlock"msgstr "Déverrouiller"+msgid "Unmapped accounts"+msgstr "Comptes non mappés"++msgid "Unmapped dimension values"+msgstr "Valeurs de dimension non mappées"+msgid "Unmapped Extracted Lines"msgstr "Lignes extraites non mappées"+msgid "Unmapped values"+msgstr "Valeurs non mappées"+msgid "Unmatched"msgstr "Non rapproché"@@ -16077,6 +16435,9 @@ msgstr "Afficher la suggestion"msgid "View Suppliers"msgstr "Afficher les fournisseurs"+msgid "View tie-out"+msgstr "Afficher le rapprochement"+msgid "View Traceability Graph"msgstr "Afficher le graphique de traçabilité"@@ -16283,6 +16644,9 @@ msgstr "Quelles données"msgid "What drove inventory up or down, by any dimension"msgstr "Ce qui a poussé l'inventaire à la hausse ou à la baisse, par toute dimension"+msgid "What happens when a journal is dated in a locked period."+msgstr "Que se passe-t-il quand un journal est daté dans une période verrouillée ?"+msgid "What is {translatedTerm}?"msgstr "Qu'est-ce que {translatedTerm} ?"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 5507b0beb8..6e356af6c7 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "एक आपूर्तिकर्ता एक व्यवसाय या व्यक्ति है जो आपको पार्ट्स या सेवाएं बेचता है।"+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— अंतिम जांच {0}"+msgid ", {residual}% residual"msgstr ", {residual}% अवशेष"@@ -56,6 +60,10 @@ msgstr "{0} खाते"msgid "{0} ago"msgstr "{0} पहले"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} अंतर वाली कोशिकाएँ"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} ग्राहकों के साथ शेष"@@ -81,6 +89,15 @@ msgstr "{0} नौकरियाँ बनाई गई"msgid "{0} lines to map"msgstr "{0} लाइनें मैप करने के लिए"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} में से {1} पोस्टिंग खातों को मैप किया गया"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} में से {maxSlots} प्रदाता स्लॉट उपयोग किए गए"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} ऑर्डर"@@ -101,6 +118,11 @@ msgstr "{0} आपूर्तिकर्ता शेष के साथ"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} नमूना न किए गए इकाइयों को उपलब्ध में जारी किया जाएगा। नमूना किए गए पास उपलब्ध रहेंगे और नमूना किए गए विफलताएं अस्वीकृत रहेंगी।"+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} असंगत खातों को {1} प्रदाता खातों के विरुद्ध मिलाया जाएगा।"+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} अपोस्ट किए गए दस्तावेज़"@@ -109,6 +131,11 @@ msgstr "{0} अपोस्ट किए गए दस्तावेज़"msgid "{0} uploaded successfully"msgstr "{0} सफलतापूर्वक अपलोड हो गया"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} मान"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} मान गायब हैं"@@ -134,6 +161,9 @@ msgstr "{done} में से {total} चरण पूर्ण"msgid "{from}–{to} of {count}"msgstr "{from}–{to} में से {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} में से {count} परिचालन"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# लाइन} other {# लाइनें}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB सीमा"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} महीने बेमेल कुल के साथ"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} पत्रिकाएं प्रदाता में नहीं हैं"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} नहीं मिली पत्रिकाएं और {mismatchCount} बेमेल महीने"+msgid "{name} deleted"msgstr "{name} हटाया गया"@@ -198,6 +237,9 @@ msgstr "↩ {0} अप्रचलित {1} से पुनर्निर्msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>इस आइटम के लिए एक आपूर्तिकर्ता भाग जोड़ें</0> एक पसंदीदा आपूर्तिकर्ता सेट करने के लिए।"+msgid "0 operations"+msgstr "0 परिचालन"+msgid "0-4 weeks"msgstr "0-4 सप्ताह"@@ -813,6 +855,9 @@ msgstr "खाता प्रबंधक"msgid "Account Manager"msgstr "खाता प्रबंधक"+msgid "Account Mapping"+msgstr "खाता मानचित्रण"+msgid "Account Number"msgstr "खाता संख्या"@@ -870,6 +915,9 @@ msgstr "प्राप्य खाते"msgid "Accounts receivable for amounts owed by customers"msgstr "ग्राहकों द्वारा देय राशियों के लिए प्राप्य खाते।"+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "पोस्टिंग डिफ़ॉल्ट या जर्नल इतिहास द्वारा संदर्भित खाते जिनके पास अभी तक कोई प्रदाता मानचित्रण नहीं है।"+msgid "Accumulated Depreciation"msgstr "संचयी मूल्यह्रास"@@ -1128,6 +1176,9 @@ msgstr "शिपमेंट जोड़ें"msgid "Add Shipping"msgstr "शिपिंग जोड़ें"+msgid "Add slot"+msgstr "स्लॉट जोड़ें"+msgid "Add Spare Part"msgstr "स्पेयर पार्ट जोड़ें"@@ -1219,6 +1270,9 @@ msgstr "दायरे पर सहमति दें"msgid "Agree who owns what and set a working rhythm"msgstr "सहमत हों कि कौन क्या मालिक है और एक कार्य लय निर्धारित करें"+msgid "AI couldn't confidently match any accounts"+msgstr "एआई किसी भी खातों को आत्मविश्वास से मिलाने में असमर्थ रहा"+msgid "AI Tokens"msgstr "एआई टोकन"@@ -1228,6 +1282,10 @@ msgstr "दायरे पर संरेखित करें"msgid "All"msgstr "सभी"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "सभी {0} कोशिकाएँ मेल खाती हैं"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "सभी {total} चरण पूरे हो गए। शानदार काम — आपकी टीम चल रही है।"@@ -1264,9 +1322,15 @@ msgstr "सभी स्थान"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "चयनित समूहों के सभी सदस्य और चयनित व्यक्ति अनुरोधों को मंजूरी दे सकेंगे"+msgid "All posting accounts are mapped"+msgstr "सभी पोस्टिंग खाते मैप किए गए हैं"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "सभी पंक्तियाँ आयात की गईं — {inserted} डाली गईं, {updated} अपडेट की गईं।"+msgid "All slotted dimension values are mapped"+msgstr "सभी स्लॉटेड आयाम मान मैप किए गए हैं"+msgid "All Suppliers"msgstr "सभी आपूर्तिकर्ता"@@ -1464,6 +1528,9 @@ msgstr "किसी भी आइटम प्रकार"msgid "Anything not explicitly listed in scope above"msgstr "स्कोप में ऊपर स्पष्ट रूप से सूचीबद्ध कुछ भी नहीं"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "AP एजिंग"@@ -1540,6 +1607,9 @@ msgstr "मूल्य निर्धारण नियम लागू कmsgid "Apply Rules On Top"msgstr "शीर्ष पर नियम लागू करें"+msgid "Apply suggestions"+msgstr "सुझाव लागू करें"+msgid "Apply To"msgstr "लागू करें"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "AR / AP प्रतिनिधित्व"+msgid "AR Aging"msgstr "AR एजिंग"@@ -1594,6 +1670,9 @@ msgstr "AR बकाया"msgid "AR Overdue"msgstr "AR अतिदेय"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "संग्रह"@@ -2146,6 +2225,9 @@ msgstr "संलग्नक"msgid "Attachments"msgstr "संलग्नताएं"+msgid "Attempts"+msgstr "प्रयास"+msgid "Attribute"msgstr "विशेषता"@@ -2194,6 +2276,9 @@ msgstr "नौकरी को स्वचालित रूप से शुmsgid "Auto Start Job"msgstr "ऑटो स्टार्ट जॉब"+msgid "Auto-create"+msgstr "स्वचालित-निर्माण"+msgid "Auto-generated QR Code"msgstr "स्वचालित रूप से उत्पन्न QR कोड"@@ -2440,6 +2525,9 @@ msgstr "Carbon के साथ कॉल बुक करें"msgid "Book Depreciation"msgstr "पुस्तक मूल्यह्रास"+msgid "Books lock date (manual)"+msgstr "पुस्तकें लॉक तारीख (मैनुअल)"+msgid "Both"msgstr "दोनों"@@ -2671,6 +2759,9 @@ msgstr "कार्बन"msgid "Carbon + you"msgstr "Carbon + आप"+msgid "Carbon account"+msgstr "कार्बन खाता"+msgid "Carbon client is not available"msgstr "Carbon क्लाइंट उपलब्ध नहीं है"@@ -2695,9 +2786,19 @@ msgstr "कार्बन लोगो"msgid "Carbon only"msgstr "केवल कार्बन"+msgid "Carbon Posted"+msgstr "Carbon पोस्ट किया गया"++msgid "Carbon value"+msgstr "Carbon मान"+msgid "Carbon Value"msgstr "कार्बन मान"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "कार्बन आपके {0} असंगत खातों में से प्रत्येक के लिए एक प्रदाता खाता अनुमान लगाने के लिए एआई का उपयोग करेगा। सुझाव एक शुरुआती बिंदु हैं — आप कुछ भी सहेजने से पहले उनकी समीक्षा कर सकते हैं।"+msgid "Carbon-only"msgstr "कार्बन-केवल"@@ -3112,6 +3213,13 @@ msgstr "पूर्ण बारकोड"msgid "Completion Time"msgstr "पूर्ण होने का समय"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "की गणना {0}"++msgid "Computed At"+msgstr "गणना समय"+msgid "Condensed P&L with margins and key subtotals"msgstr "मार्जिन और मुख्य उप-योग के साथ संक्षिप्त P&L"@@ -3209,6 +3317,9 @@ msgstr "की पुष्टि करें {0}"msgid "Confirm & release"msgstr "पुष्टि करें और जारी करें"+msgid "Confirm all"+msgstr "सभी की पुष्टि करें"+msgid "Confirm and sign the scope"msgstr "स्कोप की पुष्टि करें और हस्ताक्षर करें"@@ -3661,6 +3772,9 @@ msgstr "दस्तावेज़ लोड नहीं हो सके"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "संबंधित दस्तावेज़ लोड नहीं हो सके। डुप्लीकेट से बचने के लिए नया बनाने से पहले रीफ्रेश करें।"+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "प्रदाता के आयाम लक्ष्य लोड नहीं कर सके — कनेक्शन जांचें और फिर से लोड करें।"+msgid "Couldn't reschedule the job. Please try again."msgstr "कार्य पुनर्निर्धारित नहीं हो सका। कृपया पुनः प्रयास करें।"@@ -4210,6 +4324,9 @@ msgstr "दैनिक"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "दैनिक चेक-इन जबकि आपकी टीम लाइव सिस्टम पर अपने पैर जमाती है"+msgid "Daily summary"+msgstr "दैनिक सारांश"+msgid "Daily Usage"msgstr "दैनिक उपयोग"@@ -4926,6 +5043,12 @@ msgstr "आयाम"msgid "Dimension"msgstr "आयाम"+msgid "Dimension slots"+msgstr "आयाम स्लॉट"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "पोस्ट की गई पत्रिकाओं पर आयाम मान जिनके पास अभी तक कोई प्रदाता मैपिंग नहीं है।"+msgid "dimensions"msgstr "आयाम"@@ -5026,6 +5149,9 @@ msgstr "निपटान"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "क्या आप उपयोगकर्ता की वर्तमान अनुमतियों को इस कर्मचारी प्रकार के लिए डिफ़ॉल्ट अनुमतियों से अधिलेखित करना चाहते हैं?"+msgid "Doc-Backed"+msgstr "दस्तावेज़-समर्थित"+msgid "Docs"msgstr "दस्तावेज़"@@ -5050,6 +5176,9 @@ msgstr "दस्तावेज़:"msgid "Documents"msgstr "दस्तावेज़"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "दस्तावेज़ चालान, बिल और भुगतान को मूल प्रदाता दस्तावेज़ के रूप में धकेलता है; उनकी पत्रिकाओं को दस्तावेज़ द्वारा कवर किए गए के रूप में दर्ज किया जाता है। यह प्रदाता में दर्ज भुगतान को वापस Carbon में खींचता है, मिलान वाले चालान या बिल को बंद करता है और एक Carbon GL पत्रिका पोस्ट करता है। बंद उन्हें जानबूझकर बाहर रखे गए के रूप में दर्ज करता है।"+msgid "Don't Cancel"msgstr "रद्द न करें"@@ -5975,6 +6104,12 @@ msgstr "छूट प्रमाणपत्र"msgid "Exemption Reason"msgstr "छूट कारण"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "मौजूदा मानचित्रण। पुनः मानचित्रण के लिए एक अलग प्रदाता खाता चुनें।"++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "मौजूदा मैपिंग। पुनः-मैप करने के लिए एक अलग प्रदाता विकल्प चुनें।"+msgid "Expand"msgstr "विस्तार करें"@@ -6111,9 +6246,15 @@ msgstr "विस्तारित मूल्य"msgid "External"msgstr "बाहरी"+msgid "External Delta"+msgstr "बाहरी अंतर"+msgid "External document"msgstr "बाहरी दस्तावेज़"+msgid "External ID"+msgstr "बाहरी आईडी"+msgid "External link"msgstr "बाहरी लिंक"@@ -6830,6 +6971,9 @@ msgstr "जेनरेट की गई आईडी अक्षम हैं"msgid "Generated IDs are enabled"msgstr "जेनरेट की गई आईडी सक्षम हैं"+msgid "Generating suggestions…"+msgstr "सुझाव उत्पन्न जा रहे हैं…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Carbon पर लाइव जाएं: एक सिस्टम जो कोटिंग, खरीद, शॉप फ्लोर, इन्वेंटरी और वित्त चलाता है, वर्तमान उपकरणों को प्रतिस्थापित करता है।"@@ -7113,6 +7257,9 @@ msgstr "ऐतिहासिक दर (इक्विटी)"msgid "History"msgstr "इतिहास"+msgid "Hold the journal as a warning to fix."+msgstr "जर्नल को ठीक करने के लिए एक चेतावनी के रूप में रखें।"+msgid "Holiday"msgstr "छुट्टी"@@ -7281,6 +7428,9 @@ msgstr "आईडी"msgid "Ideas, suggestions or problems?"msgstr "विचार, सुझाव या समस्याएं?"+msgid "Idempotency key"+msgstr "समरूपता कुंजी"+msgid "Identifiers"msgstr "पहचानकर्ता"@@ -7549,6 +7699,9 @@ msgstr "निर्देश"msgid "Instructions are inherited from the procedure."msgstr "निर्देश प्रक्रिया से विरासत में मिले हैं।"+msgid "Integration"+msgstr "एकीकरण"+msgid "Integration not found"msgstr "एकीकरण नहीं मिला"@@ -7585,6 +7738,9 @@ msgstr "बैंकिंग गतिविधियों से ब्याmsgid "Internal"msgstr "आंतरिक"+msgid "Internal Delta"+msgstr "आंतरिक अंतर"+msgid "Internal notes"msgstr "आंतरिक नोट्स"@@ -7967,6 +8123,9 @@ msgstr "इस अवधि में दिनांकित जर्नलmsgid "Journal Entry"msgstr "जर्नल प्रविष्टि"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "इस तारीख को या उससे पहले की तारीख वाली पत्रिकाओं को लॉक किए गए के रूप में माना जाता है। प्रदाता द्वारा रिपोर्ट की गई लॉक तारीख के साथ विलय किया जाता है जब दोनों मौजूद हों।"+msgid "Just one"msgstr "बस एक"@@ -8067,6 +8226,12 @@ msgstr "भाषा"msgid "Last 6 Months"msgstr "पिछले 6 महीने"+msgid "Last attempt"+msgstr "अंतिम प्रयास"++msgid "Last Attempt"+msgstr "अंतिम प्रयास"+msgid "Last Calibration"msgstr "अंतिम अंशांकन"@@ -8558,6 +8723,12 @@ msgstr "निर्माता भाग संख्या"msgid "Manufacturing"msgstr "विनिर्माण"+msgid "Map accounts"+msgstr "खातों को मैप करें"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "कार्बन खातों को प्रदाता के खातों के चार्ट से मैप करें। पोस्ट की गई पत्रिकाएं मैप किए गए प्रदाता खाता कोड का उपयोग करके धकेली जाती हैं।"+msgid "Map Extracted Invoice Lines"msgstr "निकाली गई चालान पंक्तियों को मैप करें"@@ -8570,6 +8741,12 @@ msgstr "अभी लाइनें मैप करें"msgid "Map your current process, systems, and data"msgstr "अपनी वर्तमान प्रक्रिया, सिस्टम और डेटा को मैप करें"+msgid "Mapped accounts"+msgstr "मैप किए गए खाते"++msgid "Mapped values"+msgstr "मैप किए गए मान"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "\"{0}\" को पास के रूप में चिह्नित करें?"@@ -8640,6 +8817,12 @@ msgstr "किसी भी को मिलाएं"msgid "Match any (OR)"msgstr "किसी भी को मिलाएं (OR)"+msgid "Match by code"+msgstr "कोड से मेल खाएं"++msgid "Match by name"+msgstr "नाम से मेल खाएं"+msgid "Match none"msgstr "कोई भी मेल न खाएं"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "संदेश"+msgid "Metadata"+msgstr "मेटाडेटा"+msgid "Method"msgstr "तरीका"@@ -8856,6 +9042,12 @@ msgstr "मिनट/1000 पीस"msgid "Minutes/Piece"msgstr "मिनट/टुकड़ा"+msgid "Mismatch"+msgstr "बेमेल"++msgid "Missing"+msgstr "नहीं मिला"+msgid "Missing Information"msgstr "लापता जानकारी"@@ -9372,6 +9564,10 @@ msgstr "नहीं"msgid "No {0} found"msgstr "कोई {0} नहीं मिला"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "{0} सिंक परिचालन नहीं हैं"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "अभी कोई {0} नहीं"@@ -9382,6 +9578,9 @@ msgstr "कोई क्षमता जोड़ी नहीं गई"msgid "No Access"msgstr "कोई एक्सेस नहीं"+msgid "No accounts mapped yet"+msgstr "अभी तक कोई खाते मैप नहीं किए गए"+msgid "No action needed"msgstr "कोई कार्रवाई की आवश्यकता नहीं है"@@ -9470,6 +9669,12 @@ msgstr "कोई दिन बंद निर्धारित नहींmsgid "No default attachments yet."msgstr "अभी तक कोई डिफ़ॉल्ट अटैचमेंट नहीं है।"+msgid "No dimension slots configured"+msgstr "कोई आयाम स्लॉट कॉन्फ़िगर नहीं किया गया"++msgid "No dimension values mapped yet"+msgstr "अभी तक कोई आयाम मान मैप नहीं किया गया"+msgid "No draft make method for this item yet."msgstr "इस आइटम के लिए अभी तक कोई ड्राफ्ट विधि नहीं।"@@ -9635,6 +9840,9 @@ msgstr "अभी तक कोई भुगतान नहीं।"msgid "No planning data"msgstr "कोई योजना डेटा नहीं"+msgid "No posted journals in this period for this account"+msgstr "इस अवधि में इस खाते के लिए कोई पोस्ट किए गए जर्नल नहीं हैं"+msgid "No pricing for selected quantity"msgstr "चयनित मात्रा के लिए कोई मूल्य निर्धारण नहीं"@@ -9716,6 +9924,9 @@ msgstr "कोई स्टोरेज यूनिट नहीं"msgid "No suppliers yet"msgstr "अभी तक कोई आपूर्तिकर्ता नहीं"+msgid "No sync operations yet"+msgstr "अभी तक कोई सिंक परिचालन नहीं है"+msgid "No time entries for this week"msgstr "इस सप्ताह के लिए कोई समय प्रविष्टि नहीं"@@ -9728,6 +9939,12 @@ msgstr "इस कदम के लिए कोई उपकरण नहींmsgid "No transactions in this period"msgstr "इस अवधि में कोई लेनदेन नहीं"+msgid "No unmapped accounts match a provider code"+msgstr "कोई भी अनमैप किया गया खाता प्रदाता कोड से मेल नहीं खाता"++msgid "No unmapped values match a provider option name"+msgstr "कोई भी अनमैप्ड मान प्रदाता विकल्प नाम से मेल नहीं खाता"+msgid "No value needed"msgstr "कोई मान आवश्यक नहीं"@@ -9803,6 +10020,9 @@ msgstr "पर्याप्त नौकरियां नहीं हैंmsgid "Not reached"msgstr "प्राप्त नहीं"+msgid "Not recorded"+msgstr "रिकॉर्ड नहीं किया गया"+msgid "Not referenced anywhere yet."msgstr "अभी तक कहीं भी संदर्भित नहीं।"@@ -9891,6 +10111,9 @@ msgstr "OEM (मूल उपकरण निर्माता)"msgid "of"msgstr "का"+msgid "Off — handled outside the sync"+msgstr "बंद — सिंक के बाहर संभाला गया"+msgid "Off — released revisions stay editable"msgstr "बंद — जारी किए गए संशोधन संपादन योग्य रहते हैं"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "पैकिंग स्लिप"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "राशियों को उनकी मुद्रा के दशमलव स्थानों तक पैड करें, इसलिए 300 को 300.00 के रूप में दिखाया जाता है और आंकड़ों के स्तंभ संरेखित रहते हैं। इसे बंद करें ताकि केवल वे अंक दिखें जिनका मूल्य है। मुद्रित दस्तावेज़ और संग्रहीत राशियां दोनों ही तरीकों से प्रभावित नहीं होती हैं।"msgid "Page"msgstr "पृष्ठ"@@ -10418,6 +10641,12 @@ msgstr "पैरेंट स्टोरेज यूनिट"msgid "Pareto by Type"msgstr "प्रकार के अनुसार पेरेटो"+msgid "Park as error"+msgstr "त्रुटि के रूप में पार्क करें"++msgid "Park the journal with a warning until the value is mapped"+msgstr "पत्रिका को चेतावनी के साथ पार्क करें जब तक मान मैप न हो जाए"+msgid "part"msgstr "भाग"@@ -10478,6 +10707,9 @@ msgstr "भुगतान दर"msgid "Payables"msgstr "देय खाते (डिफ़ॉल्ट)"+msgid "Payables (AP)"+msgstr "देय (AP)"+msgid "Payables (default)"msgstr "भुगतान अवधि"@@ -10574,6 +10806,9 @@ msgstr "अवधि बंद"msgid "Period End"msgstr "अवधि का अंत"+msgid "Period lock policy"+msgstr "अवधि लॉक नीति"+msgid "Periodic depreciation expense for fixed assets"msgstr "पिकिंग ट्रैक किए गए इकाइयों को सबसे पहले समाप्ति के क्रम में प्रदान करती है, इसलिए सबसे जल्दी समाप्त होने वाला स्टॉक डिफ़ॉल्ट रूप से पहले छोड़ा जाता है।"@@ -10613,6 +10848,9 @@ msgstr "असाइनमेंट के लिए उपलब्ध भौmsgid "Pick"msgstr "चुनें"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "एक Carbon आयाम चुनें और प्रदाता लक्ष्य चुनें जहां यह पोस्ट करता है। स्वचालित-निर्माण पुश समय पर नाम से लापता प्रदाता विकल्प जोड़ता है।"+msgid "Pick a column to sort by"msgstr "सॉर्ट करने के लिए एक कॉलम चुनें"@@ -10834,6 +11072,9 @@ msgstr "द्वारा पोस्ट किया गया"msgid "Posted By"msgstr "द्वारा पोस्ट किया गया"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "पोस्ट किए गए जर्नल इन स्रोत प्रकारों के साथ हमेशा सिंक करते हैं। दैनिक सारांश एक दिन के जर्नल को प्रति खाते में एक प्रदाता प्रविष्टि में समूहित करता है।"+msgid "Posted once, corrected {corrections} times."msgstr "एक बार पोस्ट किया गया, {corrections} बार सही किया गया।"@@ -11124,6 +11365,12 @@ msgstr "गुण"msgid "Property"msgstr "प्रॉपर्टी"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "प्रस्तावित मेल जहां कार्बन खाता संख्या प्रदाता खाता कोड के बिल्कुल बराबर है।"++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "प्रस्तावित मेल जहां Carbon आयाम मान का नाम प्रदाता विकल्प नाम के बिल्कुल बराबर है।"+msgid "Protect the go-live date"msgstr "गो-लाइव की तारीख की सुरक्षा करें"@@ -11133,6 +11380,15 @@ msgstr "प्रशिक्षण समय की सुरक्षा कmsgid "Provide process knowledge and inputs"msgstr "प्रक्रिया ज्ञान और इनपुट प्रदान करें"+msgid "Provider"+msgstr "प्रदाता"++msgid "Provider account"+msgstr "प्रदाता खाता"++msgid "Provider option"+msgstr "प्रदाता विकल्प"+msgid "Public"msgstr "सार्वजनिक"@@ -11146,9 +11402,15 @@ msgstr "संस्करण {0} प्रकाशित करें?"msgid "Published by Carbon"msgstr "Carbon द्वारा प्रकाशित"+msgid "Pull"+msgstr "खींचें"+msgid "Pull From"msgstr "से खींचें"+msgid "Pull from accounting"+msgstr "लेखांकन से खींचें"+msgid "Pull from Inventory"msgstr "इन्वेंटरी से खींचें"@@ -11272,9 +11534,21 @@ msgstr "खरीद चालान"msgid "Purchasing Unit of Measure"msgstr "क्रय माप की इकाई"+msgid "Push"+msgstr "धकेलें"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "इसे पहले खुले दिन तक पुनः-तारीखित करें, मूल तारीख को विवरण में रखते हुए।"+msgid "Push record changes to external systems the moment they happen."msgstr "रिकॉर्ड परिवर्तनों को बाहरी सिस्टम में तुरंत भेजें जब वे होते हैं।"+msgid "Push the journal without the dimension"+msgstr "आयाम के बिना पत्रिका को पुश करें"++msgid "Push to accounting"+msgstr "लेखांकन को धकेलें"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "इस कनबन के लिए {0} बनाने के लिए QR कोड"@@ -11481,9 +11755,15 @@ msgstr "कच्चा माल"msgid "Raw Materials (default)"msgstr "कच्चा माल (डिफ़ॉल्ट)"+msgid "Re-date to first open day"+msgstr "पहले खुले दिन को फिर से डेट करें"+msgid "Re-keying between quoting, the floor, and finance"msgstr "उद्धरण, फर्श और वित्त के बीच पुनः-कुंजीकरण"+msgid "Re-send"+msgstr "फिर से भेजें"+msgid "Reactivate"msgstr "पुनः सक्रिय करें"@@ -11505,6 +11785,9 @@ msgstr "संशोधन के साथ पठनीय आईडी"msgid "Reading the document..."msgstr "दस्तावेज़ पढ़ा जा रहा है..."+msgid "Ready"+msgstr "तैयार"+msgid "Ready for Quote"msgstr "उद्धरण के लिए तैयार"@@ -11577,6 +11860,9 @@ msgstr "रसीदें, शिपमेंट, बिक्रय चालmsgid "Receivables"msgstr "प्राप्य खाते (डिफ़ॉल्ट)"+msgid "Receivables (AR)"+msgstr "प्राप्य (AR)"+msgid "Receivables (default)"msgstr "एक क्रय आदेश को प्राप्त और चालान किए गए के साथ समेटना — Carbon में निहित, लाइन मात्रा और GR/IR शेष के माध्यम से।"@@ -11635,6 +11921,9 @@ msgstr "हाल ही में बनाया गया"msgid "Reconcile"msgstr "सुलह करें"+msgid "Reconciliation found discrepancies with the provider"+msgstr "समन्वय ने प्रदाता के साथ विसंगतियां पाईं"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "वसूली अवधि"@@ -11813,6 +12102,9 @@ msgstr "पंक्ति हटाएं"msgid "Remove slide"msgstr "स्लाइड हटाएँ"+msgid "Remove slot"+msgstr "स्लॉट हटाएं"+msgid "Remove sort by column"msgstr "कॉलम द्वारा सॉर्ट हटाएं"@@ -12047,6 +12339,9 @@ msgstr "स्क्रैपिंग या बिक्री द्वारmsgid "Retry"msgstr "पुनः प्रयास करें"+msgid "Retry all"+msgstr "सभी को पुनः प्रयास करें"+msgid "Return Home"msgstr "घर लौटें"@@ -12098,6 +12393,9 @@ msgstr "प्रत्येक आइटम के परिवर्तनोmsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "अवधि की बैलेंस शीट और आय विवरण की समीक्षा करें और पुष्टि करें कि आंकड़े सही लगते हैं। यह एक मैनुअल साइन-ऑफ है — एक बार समीक्षा करने के बाद इसे पूर्ण चिह्नित करें।"+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "लागू करने से पहले सुझाए गए मिलानों की समीक्षा करें। ये एक सर्वोत्तम अनुमान हैं — प्रत्येक की पुष्टि करें कि यह सही है।"+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "नीचे दी गई चेतावनियों की समीक्षा करें, फिर समायोजन लागू करने के लिए गणना पोस्ट करें।"@@ -12153,6 +12451,9 @@ msgstr "RFQ संख्या"msgid "RFQs"msgstr "आरएफक्यू"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "पुश की गई पत्रिकाओं पर Carbon आयाम साथ रखें। प्रत्येक स्लॉट एक Carbon आयाम को एक प्रदाता विश्लेषण लक्ष्य के लिए मैप करता है; नीचे मान मैपिंग व्यक्तिगत आयाम मान को प्रदाता विकल्प के साथ जोड़ता है।"+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "आवेदन सहेजें"msgid "Save contacts"msgstr "संपर्क सहेजें"+msgid "Save dimension settings"+msgstr "आयाम सेटिंग्स सहेजें"+msgid "Save Method"msgstr "विधि सहेजें"@@ -12759,6 +13063,9 @@ msgstr "ग्राहक प्रकार चुनें"msgid "Select customers"msgstr "ग्राहकों का चयन करें"+msgid "Select dimension"+msgstr "आयाम चुनें"+msgid "Select Employee"msgstr "कर्मचारी चुनें"@@ -12795,6 +13102,15 @@ msgstr "विधि का चयन करें..."msgid "Select Printer"msgstr "प्रिंटर चुनें"+msgid "Select provider account"+msgstr "प्रदाता खाता चुनें"++msgid "Select provider target"+msgstr "प्रदाता लक्ष्य चुनें"++msgid "Select provider value"+msgstr "प्रदाता मान चुनें"+msgid "Select Quantities"msgstr "मात्रा चुनें"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "सिंक विकल्प दिखाएं"msgid "Show Trailing Zeros"-msgstr ""+msgstr "अनुगामी शून्य दिखाएं"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "में दिखाई दे रहा है {parentCurrency}"msgid "Showing the first 500 lines"msgstr "पहली 500 लाइनें दिखा रहे हैं"+msgid "Showing the newest 200 journals"+msgstr "नवीनतम 200 जर्नल दिखाए जा रहे हैं"+msgid "Showing the top 1,000 groups by amount"msgstr "राशि द्वारा शीर्ष 1,000 समूह दिखा रहे हैं"@@ -13383,6 +13702,9 @@ msgstr "स्रोत सूची"msgid "Source Method"msgstr "स्रोत विधि"+msgid "Source types"+msgstr "स्रोत प्रकार"+msgid "Source Version"msgstr "स्रोत संस्करण"@@ -13721,6 +14043,15 @@ msgstr "उत्तराधिकारी भाग"msgid "Suffix"msgstr "प्रत्यय"+msgid "Suggest mappings"+msgstr "मैपिंग सुझाएं"++msgid "Suggest mappings with AI"+msgstr "एआई के साथ मैपिंग सुझाएं"++msgid "Suggest with AI"+msgstr "एआई के साथ सुझाएं"+msgid "Suggested orders you haven't placed yet."msgstr "सुझाए गए ऑर्डर जो आपने अभी तक नहीं दिए हैं।"@@ -13926,6 +14257,18 @@ msgstr "यहां कर्मचारी के प्रकार कोmsgid "Sync"msgstr "सिंक करें"+msgid "Sync Activity"+msgstr "सिंक गतिविधि"++msgid "Sync operation"+msgstr "सिंक संचालन"++msgid "Sync Tie-Out"+msgstr "सिंक समंजन"++msgid "Synced"+msgstr "सिंक किया गया"+msgid "System"msgstr "सिस्टम"@@ -14599,6 +14942,9 @@ msgstr "प्रक्रिया जो तकनीशियन इस रmsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "प्रक्रियाएं जो यह कार्य केंद्र चला सकता है; संचालन निर्धारण करते समय प्रक्रिया-पिकर्स में दिखाई देता है, और इस कार्य केंद्र के माध्यम से कौन से नौकरियां रूट कर सकती हैं।"+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "प्रदाता कोई आयाम लक्ष्य प्रदान नहीं करता है। पहले प्रदाता में सुविधा सक्षम करें (जैसे ट्रैकिंग श्रेणियां, कक्षा ट्रैकिंग, या फ़ील्ड)।"+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "मात्रा विभाजन बिंदु जिन पर इस पंक्ति की कीमत है; प्रत्येक कॉलम क्रेता-आपूर्तिकर्ता बातचीत और डाउनस्ट्रीम दस्तावेजों में परिवर्तित करने के लिए अपनी स्वयं की प्रति-यूनिट कीमत रखता है।"@@ -15077,6 +15423,9 @@ msgstr "गुरुवार"msgid "Tie shipments through to an invoice with no re-keying"msgstr "शिपमेंट को बिना पुनः-कुंजीयन के चालान से जोड़ें"+msgid "Tie-out"+msgstr "समंजन"+msgid "Tie-Out"msgstr "टाई-आउट"@@ -15533,9 +15882,18 @@ msgstr "बिक्रय आदेश से नौकरी को अनलmsgid "Unlock"msgstr "अनलॉक करें"+msgid "Unmapped accounts"+msgstr "असंबद्ध खाते"++msgid "Unmapped dimension values"+msgstr "अनमैप्ड आयाम मान"+msgid "Unmapped Extracted Lines"msgstr "अनमैप किए गए निकाली गई लाइनें"+msgid "Unmapped values"+msgstr "अनमैप्ड मान"+msgid "Unmatched"msgstr "बेमेल"@@ -16077,6 +16435,9 @@ msgstr "सुझाव देखें"msgid "View Suppliers"msgstr "आपूर्तिकर्ताओं को देखें"+msgid "View tie-out"+msgstr "समंजन देखें"+msgid "View Traceability Graph"msgstr "ट्रेसेबिलिटी ग्राफ देखें"@@ -16283,6 +16644,9 @@ msgstr "कौन सा डेटा"msgid "What drove inventory up or down, by any dimension"msgstr "किस चीज़ ने इन्वेंटरी को किसी भी आयाम द्वारा ऊपर या नीचे ले जाया"+msgid "What happens when a journal is dated in a locked period."+msgstr "जब कोई जर्नल लॉक की गई अवधि में तारीख दी जाती है तो क्या होता है।"+msgid "What is {translatedTerm}?"msgstr "{translatedTerm} क्या है?"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex ee12f47db6..b13e7ffc9a 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "Un fornitore è un'azienda o una persona che ti vende parti o servizi."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— ultimo controllo {0}"+msgid ", {residual}% residual"msgstr ", {residual}% residuo"@@ -56,6 +60,10 @@ msgstr "{0} conti"msgid "{0} ago"msgstr "{0} fa"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} celle con delta"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} clienti con saldo"@@ -81,6 +89,15 @@ msgstr "{0} processi creati"msgid "{0} lines to map"msgstr "{0} righe da mappare"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} di {1} conti di registrazione mappati"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} di {maxSlots} slot provider utilizzati"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} ordini"@@ -101,6 +118,11 @@ msgstr "{0} fornitori con un saldo"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} entità non campionate verranno rilasciate a Disponibile. I campioni approvati rimangono Disponibili e i campioni rifiutati rimangono Rifiutati."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} conti non mappati verranno associati a {1} conti provider."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} documenti non registrati"@@ -109,6 +131,11 @@ msgstr "{0} documenti non registrati"msgid "{0} uploaded successfully"msgstr "{0} caricato con successo"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} valori"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} valori mancanti"@@ -134,6 +161,9 @@ msgstr "{done} di {total} fasi completate"msgid "{from}–{to} of {count}"msgstr "{from}–{to} di {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} di {count} operazioni"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# riga} other {# righe}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB limite"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} mesi con totali non corrispondenti"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} giornali mancanti nel provider"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} giornali mancanti e {mismatchCount} mesi non corrispondenti"+msgid "{name} deleted"msgstr "{name} eliminato"@@ -198,6 +237,9 @@ msgstr "↩ {0} reindirizzato da {1} obsoleto"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Aggiungi una parte fornitore</0> per questo articolo per impostare un fornitore preferito."+msgid "0 operations"+msgstr "0 operazioni"+msgid "0-4 weeks"msgstr "0-4 settimane"@@ -813,6 +855,9 @@ msgstr "Responsabile account"msgid "Account Manager"msgstr "Responsabile dell'Account"+msgid "Account Mapping"+msgstr "Mappatura conto"+msgid "Account Number"msgstr "Numero di Conto"@@ -870,6 +915,9 @@ msgstr "Crediti verso clienti"msgid "Accounts receivable for amounts owed by customers"msgstr "Crediti verso clienti per importi dovuti dai clienti."+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Conti referenziati da impostazioni di default di posting o cronologia giornale che non hanno ancora una mappatura provider."+msgid "Accumulated Depreciation"msgstr "Fondo di ammortamento"@@ -1128,6 +1176,9 @@ msgstr "Aggiungi Spedizione"msgid "Add Shipping"msgstr "Aggiungi Spedizione"+msgid "Add slot"+msgstr "Aggiungi slot"+msgid "Add Spare Part"msgstr "Aggiungi Pezzo di Ricambio"@@ -1219,6 +1270,9 @@ msgstr "Concordare sull'ambito"msgid "Agree who owns what and set a working rhythm"msgstr "Concordare chi possiede cosa e stabilire un ritmo di lavoro"+msgid "AI couldn't confidently match any accounts"+msgstr "L'IA non ha potuto associare con sicurezza alcun conto"+msgid "AI Tokens"msgstr "Token AI"@@ -1228,6 +1282,10 @@ msgstr "Allinea l'ambito"msgid "All"msgstr "Tutti"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "Tutte le {0} celle si bilanciano"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "Tutte le {total} fasi sono completate. Ottimo lavoro — il tuo team è operativo."@@ -1264,9 +1322,15 @@ msgstr "Tutte le Ubicazioni"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Tutti i membri dei gruppi selezionati e gli individui selezionati potranno approvare le richieste"+msgid "All posting accounts are mapped"+msgstr "Tutti i conti di posting sono mappati"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "Tutte le righe importate — {inserted} inserite, {updated} aggiornate."+msgid "All slotted dimension values are mapped"+msgstr "Tutti i valori di dimensione assegnati sono mappati"+msgid "All Suppliers"msgstr "Tutti i fornitori"@@ -1464,6 +1528,9 @@ msgstr "Qualsiasi tipo di articolo"msgid "Anything not explicitly listed in scope above"msgstr "Qualsiasi cosa non esplicitamente elencata nell'ambito di cui sopra"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "Anzianità dei Debiti"@@ -1540,6 +1607,9 @@ msgstr "Applica regole di prezzo"msgid "Apply Rules On Top"msgstr "Applica regole in alto"+msgid "Apply suggestions"+msgstr "Applica suggerimenti"+msgid "Apply To"msgstr "Applica a"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "Rappresentazione AR / AP"+msgid "AR Aging"msgstr "Anzianità dei Crediti"@@ -1594,6 +1670,9 @@ msgstr "Crediti in sospeso"msgid "AR Overdue"msgstr "AR Scaduto"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "Archivio"@@ -2146,6 +2225,9 @@ msgstr "Allegato"msgid "Attachments"msgstr "Allegati"+msgid "Attempts"+msgstr "Tentativi"+msgid "Attribute"msgstr "Attributo"@@ -2194,6 +2276,9 @@ msgstr "Il rilascio automatico deve essere abilitato per avviare un lavoro autommsgid "Auto Start Job"msgstr "Avvia automaticamente il lavoro"+msgid "Auto-create"+msgstr "Crea automaticamente"+msgid "Auto-generated QR Code"msgstr "Codice QR generato automaticamente"@@ -2440,6 +2525,9 @@ msgstr "Prenota una chiamata con Carbon"msgid "Book Depreciation"msgstr "Ammortamento Contabile"+msgid "Books lock date (manual)"+msgstr "Data di blocco dei registri (manuale)"+msgid "Both"msgstr "Entrambi"@@ -2671,6 +2759,9 @@ msgstr "Carbon"msgid "Carbon + you"msgstr "Carbon + tu"+msgid "Carbon account"+msgstr "Conto Carbon"+msgid "Carbon client is not available"msgstr "Il client Carbon non è disponibile"@@ -2695,9 +2786,19 @@ msgstr "Logo Carbon"msgid "Carbon only"msgstr "Solo Carbon"+msgid "Carbon Posted"+msgstr "Carbon Registrato"++msgid "Carbon value"+msgstr "Valore Carbon"+msgid "Carbon Value"msgstr "Valore Carbon"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon utilizzerà l'IA per indovinare un conto provider per ognuno dei tuoi {0} conti non mappati. I suggerimenti sono un punto di partenza — puoi rivederli prima che qualsiasi cosa venga salvata."+msgid "Carbon-only"msgstr "Solo Carbon"@@ -3112,6 +3213,13 @@ msgstr "Codice a barre di completamento"msgid "Completion Time"msgstr "Tempo di completamento"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "calcolato {0}"++msgid "Computed At"+msgstr "Calcolato il"+msgid "Condensed P&L with margins and key subtotals"msgstr "Conto economico condensato con margini e subtotali chiave"@@ -3209,6 +3317,9 @@ msgstr "Conferma {0}"msgid "Confirm & release"msgstr "Conferma e rilascia"+msgid "Confirm all"+msgstr "Conferma tutti"+msgid "Confirm and sign the scope"msgstr "Conferma e firma l'ambito"@@ -3661,6 +3772,9 @@ msgstr "Impossibile caricare i documenti"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Impossibile caricare i documenti correlati. Aggiorna prima di crearne uno nuovo per evitare duplicati."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "Impossibile caricare i target di dimensione del provider — verifica la connessione e ricarica."+msgid "Couldn't reschedule the job. Please try again."msgstr "Impossibile ripianificare il lavoro. Riprova."@@ -4210,6 +4324,9 @@ msgstr "Giornaliero"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Check-in giornalieri mentre il tuo team si ambientalizza sul sistema live"+msgid "Daily summary"+msgstr "Riepilogo giornaliero"+msgid "Daily Usage"msgstr "Utilizzo Giornaliero"@@ -4926,6 +5043,12 @@ msgstr "dimensione"msgid "Dimension"msgstr "Dimensione"+msgid "Dimension slots"+msgstr "Slot dimensionali"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Valori di dimensione nei journal contabilizzati che non hanno ancora un mapping provider."+msgid "dimensions"msgstr "dimensioni"@@ -5026,6 +5149,9 @@ msgstr "Disposizioni"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "Vuoi sovrascrivere i permessi attuali dell'utente con i permessi predefiniti per questo tipo di dipendente?"+msgid "Doc-Backed"+msgstr "Supportato da Documento"+msgid "Docs"msgstr "Documentazione"@@ -5050,6 +5176,9 @@ msgstr "Documento:"msgid "Documents"msgstr "Documenti"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Documenti invia fatture, bollette e pagamenti come documenti nativi del provider; i loro giornali vengono registrati come coperti dal documento. Estrae anche i pagamenti registrati nel provider nel Carbon, chiudendo la fattura o la bolletta corrispondente e registrando un giornale GL di Carbon. Off li registra come deliberatamente esclusi."+msgid "Don't Cancel"msgstr "Non annullare"@@ -5975,6 +6104,12 @@ msgstr "Certificato di Esenzione"msgid "Exemption Reason"msgstr "Motivo dell'Esenzione"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Mappature esistenti. Seleziona un conto provider diverso per rimappare."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Mapping esistenti. Scegli un'opzione provider diversa per rimappare."+msgid "Expand"msgstr "Espandi"@@ -6111,9 +6246,15 @@ msgstr "Prezzo Esteso"msgid "External"msgstr "Esterno"+msgid "External Delta"+msgstr "Delta Esterno"+msgid "External document"msgstr "Documento esterno"+msgid "External ID"+msgstr "ID esterno"+msgid "External link"msgstr "Collegamento esterno"@@ -6830,6 +6971,9 @@ msgstr "Gli ID generati sono disabilitati"msgid "Generated IDs are enabled"msgstr "Gli ID generati sono abilitati"+msgid "Generating suggestions…"+msgstr "Generazione suggerimenti…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Attiva Carbon: un unico sistema che gestisce preventivi, acquisti, shop floor, inventario e finanza, sostituendo gli strumenti attuali."@@ -7113,6 +7257,9 @@ msgstr "Tasso Storico (Patrimonio)"msgid "History"msgstr "Cronologia"+msgid "Hold the journal as a warning to fix."+msgstr "Mantieni il giornale come avvertimento da correggere."+msgid "Holiday"msgstr "Festività"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "Idee, suggerimenti o problemi?"+msgid "Idempotency key"+msgstr "Chiave di idempotenza"+msgid "Identifiers"msgstr "Identificatori"@@ -7549,6 +7699,9 @@ msgstr "Istruzioni"msgid "Instructions are inherited from the procedure."msgstr "Le istruzioni sono ereditate dalla procedura."+msgid "Integration"+msgstr "Integrazione"+msgid "Integration not found"msgstr "Integrazione non trovata"@@ -7585,6 +7738,9 @@ msgstr "Reddito o spese di interesse da attività bancarie"msgid "Internal"msgstr "Interno"+msgid "Internal Delta"+msgstr "Delta Interno"+msgid "Internal notes"msgstr "Note interne"@@ -7967,6 +8123,9 @@ msgstr "Le registrazioni contabili datate in questo periodo che sono ancora in Bmsgid "Journal Entry"msgstr "Registrazione Contabile"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "I giornali datati in questa data o prima sono trattati come bloccati. Uniti con la data di blocco segnalata dal provider quando entrambi esistono."+msgid "Just one"msgstr "Solo uno"@@ -8067,6 +8226,12 @@ msgstr "Lingua"msgid "Last 6 Months"msgstr "Ultimi 6 Mesi"+msgid "Last attempt"+msgstr "Ultimo tentativo"++msgid "Last Attempt"+msgstr "Ultimo tentativo"+msgid "Last Calibration"msgstr "Ultima Calibrazione"@@ -8558,6 +8723,12 @@ msgstr "Numero di parte del produttore"msgid "Manufacturing"msgstr "Produzione"+msgid "Map accounts"+msgstr "Mappa conti"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Mappa i conti Carbon al piano dei conti del provider. I giornali posting vengono inviati utilizzando il codice conto provider mappato."+msgid "Map Extracted Invoice Lines"msgstr "Mappa Righe Fattura Estratte"@@ -8570,6 +8741,12 @@ msgstr "Mappa Righe Ora"msgid "Map your current process, systems, and data"msgstr "Mappa il tuo processo attuale, i sistemi e i dati"+msgid "Mapped accounts"+msgstr "Conti mappati"++msgid "Mapped values"+msgstr "Valori mappati"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "Contrassegna \"{0}\" come superato?"@@ -8640,6 +8817,12 @@ msgstr "Corrisponde a uno qualsiasi"msgid "Match any (OR)"msgstr "Corrisponde a uno qualsiasi (OR)"+msgid "Match by code"+msgstr "Abbina per codice"++msgid "Match by name"+msgstr "Corrispondi per nome"+msgid "Match none"msgstr "Non corrispondere a nessuno"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Messaggio"+msgid "Metadata"+msgstr "Metadati"+msgid "Method"msgstr "Metodo"@@ -8856,6 +9042,12 @@ msgstr "Minuti/1000 Pezzi"msgid "Minutes/Piece"msgstr "Minuti/Pezzo"+msgid "Mismatch"+msgstr "Non corrisponde"++msgid "Missing"+msgstr "Mancante"+msgid "Missing Information"msgstr "Informazioni Mancanti"@@ -9372,6 +9564,10 @@ msgstr "No"msgid "No {0} found"msgstr "Nessun {0} trovato"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "Nessuna operazione di sincronizzazione {0}"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "Nessun {0} ancora"@@ -9382,6 +9578,9 @@ msgstr "Nessuna competenza aggiunta"msgid "No Access"msgstr "Nessun accesso"+msgid "No accounts mapped yet"+msgstr "Nessun conto mappato ancora"+msgid "No action needed"msgstr "Nessuna azione necessaria"@@ -9470,6 +9669,12 @@ msgstr "Nessun giorno libero programmato"msgid "No default attachments yet."msgstr "Nessun allegato predefinito ancora."+msgid "No dimension slots configured"+msgstr "Nessuno slot dimensionale configurato"++msgid "No dimension values mapped yet"+msgstr "Nessun valore di dimensione mappato ancora"+msgid "No draft make method for this item yet."msgstr "Nessun metodo di creazione della bozza per questo elemento ancora."@@ -9635,6 +9840,9 @@ msgstr "Nessun pagamento ancora."msgid "No planning data"msgstr "Nessun dato di pianificazione"+msgid "No posted journals in this period for this account"+msgstr "Nessun giornale registrato in questo periodo per questo conto"+msgid "No pricing for selected quantity"msgstr "Nessun prezzo per la quantità selezionata"@@ -9716,6 +9924,9 @@ msgstr "Nessuna unità di stoccaggio"msgid "No suppliers yet"msgstr "Nessun fornitore ancora"+msgid "No sync operations yet"+msgstr "Nessuna operazione di sincronizzazione ancora"+msgid "No time entries for this week"msgstr "Nessuna registrazione oraria per questa settimana"@@ -9728,6 +9939,12 @@ msgstr "Nessuno strumento per questo passaggio"msgid "No transactions in this period"msgstr "Nessuna transazione in questo periodo"+msgid "No unmapped accounts match a provider code"+msgstr "Nessun conto non mappato corrisponde a un codice provider"++msgid "No unmapped values match a provider option name"+msgstr "Nessun valore non mappato corrisponde al nome di un'opzione provider"+msgid "No value needed"msgstr "Nessun valore necessario"@@ -9803,6 +10020,9 @@ msgstr "Non ci sono abbastanza lavori per coprire la quantità"msgid "Not reached"msgstr "Non raggiunto"+msgid "Not recorded"+msgstr "Non registrato"+msgid "Not referenced anywhere yet."msgstr "Non referenziato da nessuna parte ancora."@@ -9891,6 +10111,9 @@ msgstr "OEM (Original Equipment Manufacturer)"msgid "of"msgstr "di"+msgid "Off — handled outside the sync"+msgstr "Disattivato — gestito al di fuori della sincronizzazione"+msgid "Off — released revisions stay editable"msgstr "Disattivato — le revisioni rilasciate rimangono modificabili"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "Documento di trasporto"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "Riempi i valori in base alle cifre decimali della valuta, in modo che 300 appaia come 300.00 e le colonne di cifre rimangono allineate. Disattivalo per mostrare solo le cifre che hanno valore. I documenti stampati e gli importi memorizzati non sono interessati in nessun modo."msgid "Page"msgstr "Pagina"@@ -10418,6 +10641,12 @@ msgstr "Unità di Archiviazione Principale"msgid "Pareto by Type"msgstr "Pareto per Tipo"+msgid "Park as error"+msgstr "Parcheggia come errore"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Parcheggia il journal con un avvertimento fino a quando il valore non è mappato"+msgid "part"msgstr "pezzi"@@ -10478,6 +10707,9 @@ msgstr "Tasso di Pagamento"msgid "Payables"msgstr "Debiti verso Fornitori (predefinito)"+msgid "Payables (AP)"+msgstr "Debiti (AP)"+msgid "Payables (default)"msgstr "termine di pagamento"@@ -10574,6 +10806,9 @@ msgstr "Chiusura del periodo"msgid "Period End"msgstr "Fine Periodo"+msgid "Period lock policy"+msgstr "Politica di blocco del periodo"+msgid "Periodic depreciation expense for fixed assets"msgstr "Il prelievo offre entità tracciate in ordine di scadenza più prossima per primo, quindi lo stock in scadenza più vicina esce per primo per impostazione predefinita."@@ -10613,6 +10848,9 @@ msgstr "Stampanti fisiche disponibili per l'assegnazione."msgid "Pick"msgstr "Preleva"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Scegli una dimensione Carbon e il target provider su cui viene contabilizzato. La creazione automatica aggiunge le opzioni provider mancanti per nome al momento del push."+msgid "Pick a column to sort by"msgstr "Scegli una colonna per ordinare"@@ -10834,6 +11072,9 @@ msgstr "Pubblicato da"msgid "Posted By"msgstr "Pubblicato da"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "I giornali registrati con questi tipi di origine si sincronizzano sempre. Il riepilogo giornaliero raggruppa i giornali di un giorno in una voce del provider per conto."+msgid "Posted once, corrected {corrections} times."msgstr "Registrato una volta, corretto {corrections} volte."@@ -11124,6 +11365,12 @@ msgstr "Proprietà"msgid "Property"msgstr "Proprietà"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Abbinamenti proposti in cui il numero di conto Carbon corrisponde esattamente al codice conto provider."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Corrispondenze proposte in cui il nome del valore di dimensione Carbon è esattamente uguale al nome di un'opzione provider."+msgid "Protect the go-live date"msgstr "Proteggi la data di go-live"@@ -11133,6 +11380,15 @@ msgstr "Proteggi il tempo di formazione e partecipa"msgid "Provide process knowledge and inputs"msgstr "Fornisci conoscenze e input del processo"+msgid "Provider"+msgstr "Provider"++msgid "Provider account"+msgstr "Account provider"++msgid "Provider option"+msgstr "Opzione provider"+msgid "Public"msgstr "Pubblico"@@ -11146,9 +11402,15 @@ msgstr "Pubblicare la versione {0}?"msgid "Published by Carbon"msgstr "Pubblicato da Carbon"+msgid "Pull"+msgstr "Estrai"+msgid "Pull From"msgstr "Preleva da"+msgid "Pull from accounting"+msgstr "Estrai dalla contabilità"+msgid "Pull from Inventory"msgstr "Preleva da Inventario"@@ -11272,9 +11534,21 @@ msgstr "Fatture di Acquisto"msgid "Purchasing Unit of Measure"msgstr "Unità di Misura di Acquisto"+msgid "Push"+msgstr "Invia"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "Spingerlo ri-datato al primo giorno aperto, mantenendo la data originale nella narrazione."+msgid "Push record changes to external systems the moment they happen."msgstr "Invia le modifiche dei record ai sistemi esterni nel momento in cui si verificano."+msgid "Push the journal without the dimension"+msgstr "Contabilizza il journal senza la dimensione"++msgid "Push to accounting"+msgstr "Invia alla contabilità"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "Codice QR per creare un {0} per questo kanban"@@ -11481,9 +11755,15 @@ msgstr "Materie Prime"msgid "Raw Materials (default)"msgstr "Materie Prime (predefinito)"+msgid "Re-date to first open day"+msgstr "Ricalibrare al primo giorno aperto"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Reinserimento dati tra preventivazione, produzione e finanza"+msgid "Re-send"+msgstr "Rinvia"+msgid "Reactivate"msgstr "Riattiva"@@ -11505,6 +11785,9 @@ msgstr "ID leggibile con revisione"msgid "Reading the document..."msgstr "Lettura del documento..."+msgid "Ready"+msgstr "Pronto"+msgid "Ready for Quote"msgstr "Pronto per Preventivo"@@ -11577,6 +11860,9 @@ msgstr "Le ricevute, le spedizioni, le fatture di vendita, le fatture di acquistmsgid "Receivables"msgstr "Crediti verso Clienti (predefinito)"+msgid "Receivables (AR)"+msgstr "Crediti (AR)"+msgid "Receivables (default)"msgstr "Riconciliazione di un ordine di acquisto con quanto ricevuto e fatturato — implicito in Carbon, tramite le quantità di riga e il saldo GR/IR."@@ -11635,6 +11921,9 @@ msgstr "Creato di recente"msgid "Reconcile"msgstr "Riconcilia"+msgid "Reconciliation found discrepancies with the provider"+msgstr "La riconciliazione ha riscontrato discrepanze con il provider"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Periodo di Recupero"@@ -11813,6 +12102,9 @@ msgstr "Rimuovi riga"msgid "Remove slide"msgstr "Rimuovi diapositiva"+msgid "Remove slot"+msgstr "Rimuovi slot"+msgid "Remove sort by column"msgstr "Rimuovi ordinamento per colonna"@@ -12047,6 +12339,9 @@ msgstr "Il ritiro di un cespite dal servizio tramite rottamazione o vendita, regmsgid "Retry"msgstr "Riprova"+msgid "Retry all"+msgstr "Riprova tutto"+msgid "Return Home"msgstr "Torna alla Home"@@ -12098,6 +12393,9 @@ msgstr "Rivedi i cambiamenti di ogni elemento, poi conferma — il rilascio nonmsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Rivedi il bilancio e il conto economico del periodo e conferma che i dati sembrino corretti. Questo è un completamento manuale — contrassegnalo come eseguito una volta revisionati."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Esamina gli abbinamenti suggeriti prima di applicare. Questi sono il miglior tentativo — conferma che ciascuno sia corretto."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Rivedi gli avvisi di seguito, quindi pubblica il conteggio per applicare gli aggiustamenti."@@ -12153,6 +12451,9 @@ msgstr "Numero RFQ"msgid "RFQs"msgstr "RFQ"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Trasporta le dimensioni Carbon insieme nei journal contabilizzati. Ogni slot mappa una dimensione Carbon a un target di analisi provider; il mapping dei valori sottostante associa i singoli valori di dimensione alle opzioni provider."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Salva applicazioni"msgid "Save contacts"msgstr "Salva contatti"+msgid "Save dimension settings"+msgstr "Salva impostazioni dimensionali"+msgid "Save Method"msgstr "Salva Metodo"@@ -12759,6 +13063,9 @@ msgstr "Seleziona tipi di cliente"msgid "Select customers"msgstr "Seleziona clienti"+msgid "Select dimension"+msgstr "Seleziona dimensione"+msgid "Select Employee"msgstr "Seleziona Dipendente"@@ -12795,6 +13102,15 @@ msgstr "Seleziona metodo..."msgid "Select Printer"msgstr "Seleziona Stampante"+msgid "Select provider account"+msgstr "Seleziona account provider"++msgid "Select provider target"+msgstr "Seleziona target provider"++msgid "Select provider value"+msgstr "Seleziona valore provider"+msgid "Select Quantities"msgstr "Seleziona Quantità"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "Mostra opzioni di sincronizzazione"msgid "Show Trailing Zeros"-msgstr ""+msgstr "Mostra Zeri Finali"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "Visualizzazione in {parentCurrency}"msgid "Showing the first 500 lines"msgstr "Visualizzazione delle prime 500 righe"+msgid "Showing the newest 200 journals"+msgstr "Mostrando i 200 giornali più recenti"+msgid "Showing the top 1,000 groups by amount"msgstr "Visualizzazione dei primi 1.000 gruppi per importo"@@ -13383,6 +13702,9 @@ msgstr "Elenco di origine"msgid "Source Method"msgstr "Metodo Sorgente"+msgid "Source types"+msgstr "Tipi di origine"+msgid "Source Version"msgstr "Versione Sorgente"@@ -13721,6 +14043,15 @@ msgstr "Parte Successiva"msgid "Suffix"msgstr "Suffisso"+msgid "Suggest mappings"+msgstr "Suggerisci mappature"++msgid "Suggest mappings with AI"+msgstr "Suggerisci mappature con l'IA"++msgid "Suggest with AI"+msgstr "Suggerisci con l'IA"+msgid "Suggested orders you haven't placed yet."msgstr "Ordini suggeriti che non hai ancora effettuato."@@ -13926,6 +14257,18 @@ msgstr "Il cambio del tipo di dipendente qui non modifica le autorizzazioni esismsgid "Sync"msgstr "Sincronizza"+msgid "Sync Activity"+msgstr "Attività di sincronizzazione"++msgid "Sync operation"+msgstr "Operazione di sincronizzazione"++msgid "Sync Tie-Out"+msgstr "Riconciliazione Sincronizzazione"++msgid "Synced"+msgstr "Sincronizzato"+msgid "System"msgstr "Sistema"@@ -14599,6 +14942,9 @@ msgstr "La procedura che i tecnici seguono quando viene eseguita questa manutenzmsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "I processi che questo centro di lavoro può eseguire; appare nei selezionatori di processo durante la programmazione delle operazioni e limita quali lavori possono instradare attraverso questo centro di lavoro."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "Il provider non offre target di dimensione. Abilita prima la funzione nel provider (ad es. categorie di tracciamento, tracciamento di classe o campi)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "I punti di interruzione della quantità a cui è quotata questa riga; ogni colonna porta il suo prezzo unitario per la negoziazione acquirente-fornitore e la conversione ai documenti a valle."@@ -15077,6 +15423,9 @@ msgstr "Giovedì"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Collegare le spedizioni a una fattura senza reinserimento dati"+msgid "Tie-out"+msgstr "Riconciliazione"+msgid "Tie-Out"msgstr "Riconciliazione"@@ -15533,9 +15882,18 @@ msgstr "Scollega il lavoro dall'ordine di vendita?"msgid "Unlock"msgstr "Sblocca"+msgid "Unmapped accounts"+msgstr "Account non mappati"++msgid "Unmapped dimension values"+msgstr "Valori di dimensione non mappati"+msgid "Unmapped Extracted Lines"msgstr "Linee Estratte Non Mappate"+msgid "Unmapped values"+msgstr "Valori non mappati"+msgid "Unmatched"msgstr "Non abbinato"@@ -16077,6 +16435,9 @@ msgstr "Visualizza Suggerimento"msgid "View Suppliers"msgstr "Visualizza Fornitori"+msgid "View tie-out"+msgstr "Visualizza riconciliazione"+msgid "View Traceability Graph"msgstr "Visualizza Grafico di Tracciabilità"@@ -16283,6 +16644,9 @@ msgstr "Quali dati"msgid "What drove inventory up or down, by any dimension"msgstr "Cosa ha fatto aumentare o diminuire l'inventario, per qualsiasi dimensione"+msgid "What happens when a journal is dated in a locked period."+msgstr "Cosa accade quando un giornale è datato in un periodo bloccato."+msgid "What is {translatedTerm}?"msgstr "Cos'è {translatedTerm}?"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex ebc6cc869e..06741e88ef 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "サプライヤーは、あなたに部品またはサービスを販売する企業または個人です。"+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— 最終確認: {0}"+msgid ", {residual}% residual"msgstr ", {residual}% 残存価額"@@ -56,6 +60,10 @@ msgstr "{0} 件のアカウント"msgid "{0} ago"msgstr "{0}前"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0}個のデルタを持つセル"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0}件の残高のある顧客"@@ -81,6 +89,15 @@ msgstr "{0}件のジョブが作成されました"msgid "{0} lines to map"msgstr "{0}件のラインをマップします"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} 件 / {1} 件の仕訳勘定がマップされています"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0}個の{maxSlots}プロバイダースロットが使用されています"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0}件の注文"@@ -101,6 +118,11 @@ msgstr "{0}件の残高のある仕入先"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0}個の未サンプリングエンティティが利用可能にリリースされます。サンプリング済みの合格品は利用可能なままで、サンプリング済みの不合格品は却下されたままです。"+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0}個のマッピングされていないアカウントが{1}個のプロバイダーアカウントと照合されます。"+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0}件の未転記書類"@@ -109,6 +131,11 @@ msgstr "{0}件の未転記書類"msgid "{0} uploaded successfully"msgstr "{0}が正常にアップロードされました"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0}個の値"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0}個の値が見つかりません"@@ -134,6 +161,9 @@ msgstr "{done} / {total} フェーズ完了"msgid "{from}–{to} of {count}"msgstr "{from}–{to} / {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}~{to}件 (合計{count}件の操作)"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# 行} other {# 行}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB制限"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount}ヶ月の合計が一致していません"++msgid "{missingCount} journals missing in the provider"+msgstr "プロバイダーで{missingCount}件のジャーナルが見つかりません"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount}件のジャーナルが見つからず、{mismatchCount}ヶ月の合計が一致していません"+msgid "{name} deleted"msgstr "{name}が削除されました"@@ -198,6 +237,9 @@ msgstr "↩ {0} は廃止された {1} からリダイレクトされました"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>この商品の仕入先部品を追加</0>して、優先仕入先を設定してください。"+msgid "0 operations"+msgstr "0件の操作"+msgid "0-4 weeks"msgstr "0~4週間"@@ -813,6 +855,9 @@ msgstr "アカウント マネージャー"msgid "Account Manager"msgstr "アカウントマネージャー"+msgid "Account Mapping"+msgstr "勘定科目マッピング"+msgid "Account Number"msgstr "勘定番号"@@ -870,6 +915,9 @@ msgstr "売掛金"msgid "Accounts receivable for amounts owed by customers"msgstr "顧客に支払う金額の売掛金。"+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "転記デフォルトまたはジャーナル履歴で参照されているが、プロバイダーマッピングがまだない勘定科目。"+msgid "Accumulated Depreciation"msgstr "累計減価償却費"@@ -1128,6 +1176,9 @@ msgstr "配送を追加"msgid "Add Shipping"msgstr "配送を追加"+msgid "Add slot"+msgstr "スロットを追加"+msgid "Add Spare Part"msgstr "スペアパーツを追加"@@ -1219,6 +1270,9 @@ msgstr "スコープに同意する"msgid "Agree who owns what and set a working rhythm"msgstr "誰が何を所有するかを合意し、作業リズムを設定する"+msgid "AI couldn't confidently match any accounts"+msgstr "AIは確実にアカウントを照合できませんでした"+msgid "AI Tokens"msgstr "AIトークン"@@ -1228,6 +1282,10 @@ msgstr "スコープを調整"msgid "All"msgstr "すべて"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "すべての{0}個のセルが一致します"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "すべての{total}フェーズが完了しました。素晴らしい仕事です。チームが稼働しています。"@@ -1264,9 +1322,15 @@ msgstr "すべての場所"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "選択されたグループのすべてのメンバーと選択された個人が承認リクエストを承認できます"+msgid "All posting accounts are mapped"+msgstr "すべての転記勘定科目がマップされています"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "すべての行をインポート—{inserted}行挿入、{updated}行更新。"+msgid "All slotted dimension values are mapped"+msgstr "すべてのスロット化されたディメンション値がマップされています"+msgid "All Suppliers"msgstr "すべてのサプライヤー"@@ -1464,6 +1528,9 @@ msgstr "任意のアイテムタイプ"msgid "Anything not explicitly listed in scope above"msgstr "上記の範囲に明示的にリストされていないもの"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "支払い老化分析"@@ -1540,6 +1607,9 @@ msgstr "価格設定ルールを適用"msgid "Apply Rules On Top"msgstr "上にルールを適用"+msgid "Apply suggestions"+msgstr "提案を適用"+msgid "Apply To"msgstr "適用対象"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "AR / AP の表現"+msgid "AR Aging"msgstr "売上老化分析"@@ -1594,6 +1670,9 @@ msgstr "売掛金未払い"msgid "AR Overdue"msgstr "売掛金滞納"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "アーカイブ"@@ -2146,6 +2225,9 @@ msgstr "添付ファイル"msgid "Attachments"msgstr "添付ファイル"+msgid "Attempts"+msgstr "試行"+msgid "Attribute"msgstr "属性"@@ -2194,6 +2276,9 @@ msgstr "ジョブを自動的に開始するには、自動リリースを有効msgid "Auto Start Job"msgstr "自動ジョブ開始"+msgid "Auto-create"+msgstr "自動作成"+msgid "Auto-generated QR Code"msgstr "自動生成されたQRコード"@@ -2440,6 +2525,9 @@ msgstr "Carbonとの通話を予約する"msgid "Book Depreciation"msgstr "簿価償却"+msgid "Books lock date (manual)"+msgstr "帳簿ロック日 (手動)"+msgid "Both"msgstr "両方"@@ -2671,6 +2759,9 @@ msgstr "カーボン"msgid "Carbon + you"msgstr "Carbon + あなた"+msgid "Carbon account"+msgstr "Carbon勘定科目"+msgid "Carbon client is not available"msgstr "Carbonクライアントは利用できません"@@ -2695,9 +2786,19 @@ msgstr "Carbonロゴ"msgid "Carbon only"msgstr "Carbonのみ"+msgid "Carbon Posted"+msgstr "カーボン転記済み"++msgid "Carbon value"+msgstr "Carbon値"+msgid "Carbon Value"msgstr "カーボン値"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbonはあなたの{0}個のマッピングされていないアカウントのそれぞれに対してAIを使用してプロバイダーアカウントを推測します。提案は出発点です—何かが保存される前にそれらを確認することができます。"+msgid "Carbon-only"msgstr "Carbon専用"@@ -3112,6 +3213,13 @@ msgstr "完了バーコード"msgid "Completion Time"msgstr "完了時間"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "{0}で計算済み"++msgid "Computed At"+msgstr "計算日時"+msgid "Condensed P&L with margins and key subtotals"msgstr "マージンと主要小計を含む圧縮P&L"@@ -3209,6 +3317,9 @@ msgstr "{0}を確認"msgid "Confirm & release"msgstr "確認してリリース"+msgid "Confirm all"+msgstr "すべて確認"+msgid "Confirm and sign the scope"msgstr "スコープを確認して署名する"@@ -3661,6 +3772,9 @@ msgstr "ドキュメントを読み込めませんでした"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "関連ドキュメントを読み込めませんでした。重複を避けるため、新規作成前に更新してください。"+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "プロバイダーのディメンションターゲットを読み込めませんでした。接続を確認して再度読み込んでください。"+msgid "Couldn't reschedule the job. Please try again."msgstr "ジョブを再スケジュールできませんでした。もう一度お試しください。"@@ -4210,6 +4324,9 @@ msgstr "毎日"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "ライブシステムでチームが軌道に乗るまでの毎日のチェックイン"+msgid "Daily summary"+msgstr "日次集約"+msgid "Daily Usage"msgstr "日次使用量"@@ -4926,6 +5043,12 @@ msgstr "ディメンション"msgid "Dimension"msgstr "寸法"+msgid "Dimension slots"+msgstr "ディメンションスロット"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "まだプロバイダーマッピングがない投稿済みジャーナルのディメンション値。"+msgid "dimensions"msgstr "ディメンション"@@ -5026,6 +5149,9 @@ msgstr "処分"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "このEmployee Typeのデフォルト権限でユーザーの現在の権限を上書きしますか?"+msgid "Doc-Backed"+msgstr "文書バック"+msgid "Docs"msgstr "ドキュメント"@@ -5050,6 +5176,9 @@ msgstr "ドキュメント:"msgid "Documents"msgstr "ドキュメント"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "ドキュメントは、請求書、帳票、支払いをネイティブプロバイダードキュメントとしてプッシュします。それらの仕訳はドキュメントでカバーされているものとして記録されます。また、プロバイダーで記録された支払いをCarbonに引き戻し、一致する請求書または帳票を閉じて、CarbonのGL仕訳を投稿します。Offはそれらを意図的に除外されたものとして記録します。"+msgid "Don't Cancel"msgstr "キャンセルしない"@@ -5975,6 +6104,12 @@ msgstr "免除証明書"msgid "Exemption Reason"msgstr "免除理由"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "既存のマッピング。再マップするには別のプロバイダー勘定科目を選択してください。"++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "既存のマッピング。異なるプロバイダーオプションを選択して再マップしてください。"+msgid "Expand"msgstr "展開"@@ -6111,9 +6246,15 @@ msgstr "拡張価格"msgid "External"msgstr "外部"+msgid "External Delta"+msgstr "外部デルタ"+msgid "External document"msgstr "外部ドキュメント"+msgid "External ID"+msgstr "外部ID"+msgid "External link"msgstr "外部リンク"@@ -6830,6 +6971,9 @@ msgstr "生成されたIDは無効です"msgid "Generated IDs are enabled"msgstr "生成されたIDが有効です"+msgid "Generating suggestions…"+msgstr "提案を生成中…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Carbonで本番稼働:見積、購買、生産現場、在庫、財務を実行する1つのシステムで、現在のツールを置き換えます。"@@ -7113,6 +7257,9 @@ msgstr "歴史レート(エクイティ)"msgid "History"msgstr "履歴"+msgid "Hold the journal as a warning to fix."+msgstr "修正する警告としてジャーナルを保持する"+msgid "Holiday"msgstr "祝日"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "アイデア、提案、または問題はありますか?"+msgid "Idempotency key"+msgstr "冪等性キー"+msgid "Identifiers"msgstr "識別子"@@ -7549,6 +7699,9 @@ msgstr "手順"msgid "Instructions are inherited from the procedure."msgstr "手順から継承された指示。"+msgid "Integration"+msgstr "統合"+msgid "Integration not found"msgstr "統合が見つかりません"@@ -7585,6 +7738,9 @@ msgstr "銀行業務からの利息収入または支出"msgid "Internal"msgstr "内部"+msgid "Internal Delta"+msgstr "内部デルタ"+msgid "Internal notes"msgstr "内部メモ"@@ -7967,6 +8123,9 @@ msgstr "当期に日付が付けられた仕訳がまだ下書きの場合は、msgid "Journal Entry"msgstr "仕訳"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "この日付以前の日付のジャーナルはロック済みとして扱われます。両方存在する場合はプロバイダーが報告するロック日と統合されます。"+msgid "Just one"msgstr "1つだけ"@@ -8067,6 +8226,12 @@ msgstr "言語"msgid "Last 6 Months"msgstr "過去6ヶ月"+msgid "Last attempt"+msgstr "最後の試行"++msgid "Last Attempt"+msgstr "最後の試行"+msgid "Last Calibration"msgstr "最後のキャリブレーション"@@ -8558,6 +8723,12 @@ msgstr "メーカー部品番号"msgid "Manufacturing"msgstr "製造"+msgid "Map accounts"+msgstr "勘定をマップ"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Carbon勘定科目をプロバイダーの勘定科目体系にマップします。転記されたジャーナルはマップされたプロバイダー勘定科目コードを使用して転記されます。"+msgid "Map Extracted Invoice Lines"msgstr "抽出された請求書行をマップする"@@ -8570,6 +8741,12 @@ msgstr "今すぐラインをマップ"msgid "Map your current process, systems, and data"msgstr "現在のプロセス、システム、データをマップする"+msgid "Mapped accounts"+msgstr "マップ済み勘定科目"++msgid "Mapped values"+msgstr "マップされた値"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "\"{0}\"をパスしたとしてマークしますか?"@@ -8640,6 +8817,12 @@ msgstr "いずれかに一致"msgid "Match any (OR)"msgstr "任意に一致 (OR)"+msgid "Match by code"+msgstr "コードで一致"++msgid "Match by name"+msgstr "名前で一致"+msgid "Match none"msgstr "いずれにも一致しない"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "メッセージ"+msgid "Metadata"+msgstr "メタデータ"+msgid "Method"msgstr "方法"@@ -8856,6 +9042,12 @@ msgstr "分/1000個"msgid "Minutes/Piece"msgstr "分/個"+msgid "Mismatch"+msgstr "不一致"++msgid "Missing"+msgstr "見つかりません"+msgid "Missing Information"msgstr "不足している情報"@@ -9372,6 +9564,10 @@ msgstr "いいえ"msgid "No {0} found"msgstr "{0}が見つかりません"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "{0}同期操作はありません"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "まだ{0}がありません"@@ -9382,6 +9578,9 @@ msgstr "能力が追加されていません"msgid "No Access"msgstr "アクセスなし"+msgid "No accounts mapped yet"+msgstr "マップされた勘定科目がまだありません"+msgid "No action needed"msgstr "対応は不要です"@@ -9470,6 +9669,12 @@ msgstr "休暇の予定がありません"msgid "No default attachments yet."msgstr "まだデフォルト添付ファイルがありません。"+msgid "No dimension slots configured"+msgstr "ディメンションスロットが構成されていません"++msgid "No dimension values mapped yet"+msgstr "まだディメンション値がマップされていません"+msgid "No draft make method for this item yet."msgstr "このアイテムのドラフト製造方法はまだありません。"@@ -9635,6 +9840,9 @@ msgstr "まだ支払いはありません。"msgid "No planning data"msgstr "計画データなし"+msgid "No posted journals in this period for this account"+msgstr "この期間にこのアカウントの転記済みジャーナルはありません"+msgid "No pricing for selected quantity"msgstr "選択した数量の価格設定がありません"@@ -9716,6 +9924,9 @@ msgstr "ストレージユニットがありません"msgid "No suppliers yet"msgstr "まだサプライヤーがありません"+msgid "No sync operations yet"+msgstr "同期操作がまだありません"+msgid "No time entries for this week"msgstr "今週のタイムエントリがありません"@@ -9728,6 +9939,12 @@ msgstr "このステップのツールがありません"msgid "No transactions in this period"msgstr "この期間に取引がありません"+msgid "No unmapped accounts match a provider code"+msgstr "マップされていない勘定科目でプロバイダーコードと一致するものがありません"++msgid "No unmapped values match a provider option name"+msgstr "マップされていない値がプロバイダーオプション名と一致しません"+msgid "No value needed"msgstr "値が不要です"@@ -9803,6 +10020,9 @@ msgstr "数量をカバーするのに十分なジョブがありません"msgid "Not reached"msgstr "未到達"+msgid "Not recorded"+msgstr "記録されていません"+msgid "Not referenced anywhere yet."msgstr "どこでも参照されていません。"@@ -9891,6 +10111,9 @@ msgstr "OEM (オリジナル機器メーカー)"msgid "of"msgstr "の"+msgid "Off — handled outside the sync"+msgstr "オフ — 同期外で処理"+msgid "Off — released revisions stay editable"msgstr "オフ - リリースされたリビジョンは編集可能なままです"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "梱包明細書"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "金額をその通貨の小数点以下の桁に合わせます。例えば300は300.00と表示され、数字の列が揃います。これをオフにすると、実際の値を持つ数字のみが表示されます。印刷されたドキュメントおよび保存された金額は、どちらの方法でも影響を受けません。"msgid "Page"msgstr "ページ"@@ -10418,6 +10641,12 @@ msgstr "親保管ユニット"msgid "Pareto by Type"msgstr "タイプ別パレート"+msgid "Park as error"+msgstr "エラーとして保留"++msgid "Park the journal with a warning until the value is mapped"+msgstr "値がマップされるまで、ジャーナルに警告を付けて保留します"+msgid "part"msgstr "部品"@@ -10478,6 +10707,9 @@ msgstr "支払レート"msgid "Payables"msgstr "買掛金(デフォルト)"+msgid "Payables (AP)"+msgstr "買掛金 (AP)"+msgid "Payables (default)"msgstr "支払条件"@@ -10574,6 +10806,9 @@ msgstr "期間クローズ"msgid "Period End"msgstr "期間終了"+msgid "Period lock policy"+msgstr "期間ロックポリシー"+msgid "Periodic depreciation expense for fixed assets"msgstr "ピッキングは追跡対象エンティティを最も早い有効期限順に提供するため、デフォルトで最初に期限切れになる在庫が最初に出庫されます。"@@ -10613,6 +10848,9 @@ msgstr "割り当て可能な物理プリンター。"msgid "Pick"msgstr "ピック"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Carbonディメンションと、それを投稿するプロバイダーターゲットを選択します。自動作成は、プッシュ時に不足しているプロバイダーオプションを名前で追加します。"+msgid "Pick a column to sort by"msgstr "ソート対象の列を選択"@@ -10834,6 +11072,9 @@ msgstr "投稿者"msgid "Posted By"msgstr "投稿者"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "これらのソースタイプで転記された仕訳は常に同期されます。日次サマリーは、1日の仕訳をアカウントごとに1つのプロバイダーエントリにグループ化します。"+msgid "Posted once, corrected {corrections} times."msgstr "1回投稿され、{corrections}回訂正されました。"@@ -11124,6 +11365,12 @@ msgstr "プロパティ"msgid "Property"msgstr "プロパティ"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Carbon勘定科目番号がプロバイダー勘定科目コードと正確に一致する提案されたマッチ。"++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Carbonディメンション値の名前がプロバイダーオプション名と完全に一致する提案されたマッチ。"+msgid "Protect the go-live date"msgstr "ゴーライブ日を保護する"@@ -11133,6 +11380,15 @@ msgstr "トレーニング時間を確保して参加する"msgid "Provide process knowledge and inputs"msgstr "プロセスの知識と入力を提供する"+msgid "Provider"+msgstr "プロバイダー"++msgid "Provider account"+msgstr "プロバイダアカウント"++msgid "Provider option"+msgstr "プロバイダーオプション"+msgid "Public"msgstr "公開"@@ -11146,9 +11402,15 @@ msgstr "バージョン{0}を公開しますか?"msgid "Published by Carbon"msgstr "Carbonによって公開"+msgid "Pull"+msgstr "プル"+msgid "Pull From"msgstr "から取得"+msgid "Pull from accounting"+msgstr "会計から引き出す"+msgid "Pull from Inventory"msgstr "在庫から取得"@@ -11272,9 +11534,21 @@ msgstr "購買請求書"msgid "Purchasing Unit of Measure"msgstr "購買単位"+msgid "Push"+msgstr "プッシュ"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "元の日付を説明に保持しながら、最初の開いている日に再日付してプッシュする"+msgid "Push record changes to external systems the moment they happen."msgstr "レコードの変更が発生した瞬間に外部システムにプッシュします。"+msgid "Push the journal without the dimension"+msgstr "ディメンションなしでジャーナルをプッシュ"++msgid "Push to accounting"+msgstr "会計にプッシュ"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "このカンバンの{0}を作成するためのQRコード"@@ -11481,9 +11755,15 @@ msgstr "原材料"msgid "Raw Materials (default)"msgstr "原材料(デフォルト)"+msgid "Re-date to first open day"+msgstr "最初の営業日に再日付け"+msgid "Re-keying between quoting, the floor, and finance"msgstr "見積、現場、財務間での再入力"+msgid "Re-send"+msgstr "再送信"+msgid "Reactivate"msgstr "再度有効化"@@ -11505,6 +11785,9 @@ msgstr "リビジョン付き読み取り可能ID"msgid "Reading the document..."msgstr "ドキュメントを読み込み中..."+msgid "Ready"+msgstr "準備完了"+msgid "Ready for Quote"msgstr "見積もり準備完了"@@ -11577,6 +11860,9 @@ msgstr "受領書、出荷、売上請求書、仕入請求書、支払、およmsgid "Receivables"msgstr "売掛金(デフォルト)"+msgid "Receivables (AR)"+msgstr "売掛金 (AR)"+msgid "Receivables (default)"msgstr "購買注文を受け取った内容と請求内容で調整する — Carbon に暗黙的に含まれており、行数量と GR/IR 残高を通じて。"@@ -11635,6 +11921,9 @@ msgstr "最近作成"msgid "Reconcile"msgstr "調整"+msgid "Reconciliation found discrepancies with the provider"+msgstr "調整でプロバイダとの不一致が見つかりました"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "回収期間"@@ -11813,6 +12102,9 @@ msgstr "行を削除"msgid "Remove slide"msgstr "スライドを削除"+msgid "Remove slot"+msgstr "スロットを削除"+msgid "Remove sort by column"msgstr "列でソートを削除"@@ -12047,6 +12339,9 @@ msgstr "除却または売却により資産を稼働から除外し、正味簿msgid "Retry"msgstr "再試行"+msgid "Retry all"+msgstr "すべてを再試行"+msgid "Return Home"msgstr "ホームに戻る"@@ -12098,6 +12393,9 @@ msgstr "各アイテムの変更をレビューしてから確認してくださmsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "当期の貸借対照表と損益計算書を確認し、数字が正しいことを確認してください。これは手動による認可です。確認後、完了とマークしてください。"+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "適用する前に提案されたマッチを確認します。これらは最良の推測です—各マッチが正しいことを確認します。"+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "下の警告を確認してから、カウントを投稿して調整を適用してください。"@@ -12153,6 +12451,9 @@ msgstr "RFQ番号"msgid "RFQs"msgstr "RFQ"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "プッシュされたジャーナルに沿ってCarbonディメンションを含める。各スロットは1つのCarbonディメンションを1つのプロバイダー分析ターゲットにマップします。以下の値マッピングは個々のディメンション値をプロバイダーオプションとペアリングします。"+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "アプリケーションを保存"msgid "Save contacts"msgstr "連絡先を保存"+msgid "Save dimension settings"+msgstr "ディメンション設定を保存"+msgid "Save Method"msgstr "メソッドを保存"@@ -12759,6 +13063,9 @@ msgstr "顧客タイプを選択"msgid "Select customers"msgstr "顧客を選択"+msgid "Select dimension"+msgstr "ディメンションを選択"+msgid "Select Employee"msgstr "従業員を選択"@@ -12795,6 +13102,15 @@ msgstr "メソッドを選択..."msgid "Select Printer"msgstr "プリンターを選択"+msgid "Select provider account"+msgstr "プロバイダアカウントを選択"++msgid "Select provider target"+msgstr "プロバイダーターゲットを選択"++msgid "Select provider value"+msgstr "プロバイダー値を選択"+msgid "Select Quantities"msgstr "数量を選択"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "同期オプションを表示"msgid "Show Trailing Zeros"-msgstr ""+msgstr "末尾のゼロを表示"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "{parentCurrency}で表示"msgid "Showing the first 500 lines"msgstr "最初の 500 行を表示中"+msgid "Showing the newest 200 journals"+msgstr "最新の200個のジャーナルを表示しています"+msgid "Showing the top 1,000 groups by amount"msgstr "金額別上位 1,000 グループを表示中"@@ -13383,6 +13702,9 @@ msgstr "ソースリスト"msgid "Source Method"msgstr "ソース方法"+msgid "Source types"+msgstr "ソースタイプ"+msgid "Source Version"msgstr "ソースバージョン"@@ -13721,6 +14043,15 @@ msgstr "後継部品"msgid "Suffix"msgstr "サフィックス"+msgid "Suggest mappings"+msgstr "マッピングを提案"++msgid "Suggest mappings with AI"+msgstr "AIでマッピングを提案"++msgid "Suggest with AI"+msgstr "AIで提案"+msgid "Suggested orders you haven't placed yet."msgstr "まだ発注していない推奨注文。"@@ -13926,6 +14257,18 @@ msgstr "ここで従業員のタイプを変更しても、既存の権限は変msgid "Sync"msgstr "同期"+msgid "Sync Activity"+msgstr "同期アクティビティ"++msgid "Sync operation"+msgstr "同期操作"++msgid "Sync Tie-Out"+msgstr "同期一致"++msgid "Synced"+msgstr "同期済み"+msgid "System"msgstr "システム"@@ -14599,6 +14942,9 @@ msgstr "このメンテナンスが実行されるときにテクニシャンがmsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "このワークセンターが実行できるプロセス。オペレーションをスケジュールするときのプロセスピッカーに表示され、このワークセンターを通じてルーティングできるジョブを制限します。"+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "プロバイダーはディメンションターゲットを提供していません。最初にプロバイダーで機能を有効にしてください(例:追跡カテゴリ、クラス追跡、またはフィールド)。"+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "この行が価格設定される数量ブレークポイント。各列は、買い手-サプライヤー交渉とダウンストリーム文書への変換のための独自の単価を行います。"@@ -15077,6 +15423,9 @@ msgstr "木曜日"msgid "Tie shipments through to an invoice with no re-keying"msgstr "出荷を請求書に結びつけ、再入力なしで処理する"+msgid "Tie-out"+msgstr "一致"+msgid "Tie-Out"msgstr "照合"@@ -15533,9 +15882,18 @@ msgstr "販売注文からジョブのリンクを解除しますか?"msgid "Unlock"msgstr "ロック解除"+msgid "Unmapped accounts"+msgstr "マップされていないアカウント"++msgid "Unmapped dimension values"+msgstr "マップされていないディメンション値"+msgid "Unmapped Extracted Lines"msgstr "マップされていない抽出行"+msgid "Unmapped values"+msgstr "マップされていない値"+msgid "Unmatched"msgstr "不一致"@@ -16077,6 +16435,9 @@ msgstr "提案を表示"msgid "View Suppliers"msgstr "サプライヤーを表示"+msgid "View tie-out"+msgstr "一致を表示"+msgid "View Traceability Graph"msgstr "トレーサビリティグラフを表示"@@ -16283,6 +16644,9 @@ msgstr "どのデータ"msgid "What drove inventory up or down, by any dimension"msgstr "在庫の増減を駆動した要因(ディメンション別)"+msgid "What happens when a journal is dated in a locked period."+msgstr "ジャーナルがロックされた期間に日付が付けられた場合、何が起こるか"+msgid "What is {translatedTerm}?"msgstr "{translatedTerm}とは何ですか?"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex a78911b059..c94f17fc55 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr " 공급업체는 귀사에 부품이나 서비스를 판매하는 회사 또는 개인입니다."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— 마지막 확인 {0}"+msgid ", {residual}% residual"msgstr ", {residual}% 잔존"@@ -56,6 +60,10 @@ msgstr "{0} 계정"msgid "{0} ago"msgstr "{0} 전"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0}개 셀에 변경사항 있음"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "잔액이 있는 고객 {0}명"@@ -81,6 +89,15 @@ msgstr "{0}개 작업이 생성됨"msgid "{0} lines to map"msgstr "매핑할 라인 {0}개"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0}개의 {1} 게시 계정 매핑됨"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0}개 중 {maxSlots}개 제공자 슬롯 사용됨"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "주문 {0}건"@@ -101,6 +118,11 @@ msgstr "잔액이 있는 공급업체 {0}곳"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "샘플링되지 않은 개체 {0}개가 사용 가능 상태로 전환됩니다. 샘플링에서 합격한 항목은 사용 가능 상태를 유지하고, 불합격한 항목은 반려 상태를 유지합니다."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0}개의 매핑되지 않은 계정이 {1}개의 공급자 계정과 매칭됩니다."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0}건의 미전기 문서"@@ -109,6 +131,11 @@ msgstr "{0}건의 미전기 문서"msgid "{0} uploaded successfully"msgstr "{0}이(가) 업로드되었습니다"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0}개 값"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0}개 값 누락"@@ -134,6 +161,9 @@ msgstr "{done}개 중 {total}개 단계 완료"msgid "{from}–{to} of {count}"msgstr "{count}개 중 {from}–{to}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} / {count}개 작업"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# 줄} other {# 줄}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB 제한"+msgid "{mismatchCount} months with mismatched totals"+msgstr "총액이 일치하지 않는 {mismatchCount}개월"++msgid "{missingCount} journals missing in the provider"+msgstr "공급자에서 누락된 {missingCount}개 분개"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount}개 누락된 분개 및 {mismatchCount}개 일치하지 않는 월"+msgid "{name} deleted"msgstr "{name} 삭제됨"@@ -198,6 +237,9 @@ msgstr "↩ 대체된 {1}에서 {0}(으)로 전환됨"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "이 품목에 <0>공급업체 부품 추가</0>를 하여 선호 공급업체를 설정하세요."+msgid "0 operations"+msgstr "0개 작업"+msgid "0-4 weeks"msgstr "0-4주"@@ -813,6 +855,9 @@ msgstr "계정 관리자"msgid "Account Manager"msgstr "계정 관리자"+msgid "Account Mapping"+msgstr "계정 매핑"+msgid "Account Number"msgstr "계좌번호"@@ -870,6 +915,9 @@ msgstr "매출채권"msgid "Accounts receivable for amounts owed by customers"msgstr "고객이 지급할 금액에 대한 매출채권"+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "게시 기본값 또는 분개 기록에서 참조되지만 공급자 매핑이 아직 없는 계정입니다."+msgid "Accumulated Depreciation"msgstr "감가상각누계액"@@ -1128,6 +1176,9 @@ msgstr "출하 추가"msgid "Add Shipping"msgstr "배송비 추가"+msgid "Add slot"+msgstr "슬롯 추가"+msgid "Add Spare Part"msgstr "예비 부품 추가"@@ -1219,6 +1270,9 @@ msgstr "범위에 합의"msgid "Agree who owns what and set a working rhythm"msgstr "역할 분담에 합의하고 업무 리듬을 설정하세요"+msgid "AI couldn't confidently match any accounts"+msgstr "AI가 계정을 확실하게 매칭하지 못했습니다"+msgid "AI Tokens"msgstr "AI 토큰"@@ -1228,6 +1282,10 @@ msgstr "범위 정렬"msgid "All"msgstr "전체"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "모든 {0}개 셀이 일치함"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "{total}단계가 모두 완료되었습니다. 수고하셨습니다 — 팀이 이제 정상 가동 중입니다."@@ -1264,9 +1322,15 @@ msgstr "모든 위치"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "선택한 그룹의 모든 구성원과 선택한 개인이 요청을 승인할 수 있습니다"+msgid "All posting accounts are mapped"+msgstr "모든 게시 계정이 매핑됨"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "모든 행을 가져왔습니다 — {inserted}개 추가, {updated}개 업데이트."+msgid "All slotted dimension values are mapped"+msgstr "모든 슬롯된 차원 값이 매핑되었습니다"+msgid "All Suppliers"msgstr "모든 공급업체"@@ -1464,6 +1528,9 @@ msgstr "모든 품목 유형"msgid "Anything not explicitly listed in scope above"msgstr "위 범위에 명시적으로 나열되지 않은 모든 사항"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "AP 에이징"@@ -1540,6 +1607,9 @@ msgstr "가격 규칙 적용"msgid "Apply Rules On Top"msgstr "규칙을 우선 적용"+msgid "Apply suggestions"+msgstr "제안 적용"+msgid "Apply To"msgstr "적용 대상"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL(Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "AR / AP 표현"+msgid "AR Aging"msgstr "AR 에이징"@@ -1594,6 +1670,9 @@ msgstr "매출채권 미결제액"msgid "AR Overdue"msgstr "매출채권 연체"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "보관"@@ -2146,6 +2225,9 @@ msgstr "첨부파일"msgid "Attachments"msgstr "첨부파일"+msgid "Attempts"+msgstr "시도"+msgid "Attribute"msgstr "속성"@@ -2194,6 +2276,9 @@ msgstr "작업을 자동으로 시작하려면 자동 릴리즈가 활성화되msgid "Auto Start Job"msgstr "작업 자동 시작"+msgid "Auto-create"+msgstr "자동 생성"+msgid "Auto-generated QR Code"msgstr "자동 생성된 QR 코드"@@ -2440,6 +2525,9 @@ msgstr "Carbon과 상담 예약"msgid "Book Depreciation"msgstr "장부 감가상각"+msgid "Books lock date (manual)"+msgstr "장부 잠금 날짜(수동)"+msgid "Both"msgstr "모두"@@ -2671,6 +2759,9 @@ msgstr "Carbon"msgid "Carbon + you"msgstr "Carbon + 당신"+msgid "Carbon account"+msgstr "Carbon 계정"+msgid "Carbon client is not available"msgstr "Carbon 클라이언트를 사용할 수 없습니다"@@ -2695,9 +2786,19 @@ msgstr "Carbon 로고"msgid "Carbon only"msgstr "Carbon 전용"+msgid "Carbon Posted"+msgstr "Carbon 게시됨"++msgid "Carbon value"+msgstr "Carbon 값"+msgid "Carbon Value"msgstr "Carbon Value"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon은 AI를 사용하여 {0}개의 매핑되지 않은 계정 각각에 대한 공급자 계정을 추측합니다. 제안은 시작점입니다 — 저장하기 전에 검토할 수 있습니다."+msgid "Carbon-only"msgstr "Carbon 전용"@@ -3112,6 +3213,13 @@ msgstr "완료 바코드"msgid "Completion Time"msgstr "완료 시간"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "{0}에 계산됨"++msgid "Computed At"+msgstr "계산 시간"+msgid "Condensed P&L with margins and key subtotals"msgstr "마진 및 주요 소계를 포함한 축약 손익계산"@@ -3209,6 +3317,9 @@ msgstr "{0} 확인"msgid "Confirm & release"msgstr "확인 및 릴리스"+msgid "Confirm all"+msgstr "모두 확인"+msgid "Confirm and sign the scope"msgstr "범위를 확인하고 서명하세요"@@ -3661,6 +3772,9 @@ msgstr "문서를 불러올 수 없습니다"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "관련 문서를 불러올 수 없습니다. 중복 생성을 방지하려면 새로 만들기 전에 새로고침하세요."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "제공자의 차원 대상을 로드할 수 없습니다 — 연결을 확인하고 다시 로드하세요."+msgid "Couldn't reschedule the job. Please try again."msgstr "작업 일정을 변경할 수 없습니다. 다시 시도하세요."@@ -4210,6 +4324,9 @@ msgstr "매일"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "팀이 실제 운영 시스템에 적응하는 동안 매일 체크인"+msgid "Daily summary"+msgstr "일일 요약"+msgid "Daily Usage"msgstr "일일 사용량"@@ -4926,6 +5043,12 @@ msgstr "치수"msgid "Dimension"msgstr "치수"+msgid "Dimension slots"+msgstr "차원 슬롯"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "아직 제공자 매핑이 없는 게시된 저널의 차원 값입니다."+msgid "dimensions"msgstr "치수"@@ -5026,6 +5149,9 @@ msgstr "처리"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "이 직원 유형의 기본 권한으로 사용자의 현재 권한을 덮어쓰시겠습니까?"+msgid "Doc-Backed"+msgstr "문서 기반"+msgid "Docs"msgstr "문서"@@ -5050,6 +5176,9 @@ msgstr "문서:"msgid "Documents"msgstr "문서"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "문서는 송장, 청구서 및 지불을 기본 공급자 문서로 푸시하고, 해당 분개는 문서에서 다룬 것으로 기록됩니다. 또한 공급자에 기록된 지불을 Carbon으로 다시 끌어와 일치하는 청구서 또는 송장을 마감하고 Carbon GL 분개를 게시합니다. Off는 이를 의도적으로 제외된 것으로 기록합니다."+msgid "Don't Cancel"msgstr "취소하지 않음"@@ -5975,6 +6104,12 @@ msgstr "면세 증명서"msgid "Exemption Reason"msgstr "면세 사유"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "기존 매핑입니다. 다시 매핑하려면 다른 공급자 계정을 선택하세요."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "기존 매핑입니다. 다시 매핑하려면 다른 제공자 옵션을 선택하세요."+msgid "Expand"msgstr "펼치기"@@ -6111,9 +6246,15 @@ msgstr "확장 가격"msgid "External"msgstr "외부"+msgid "External Delta"+msgstr "외부 변경사항"+msgid "External document"msgstr "외부 문서"+msgid "External ID"+msgstr "외부 ID"+msgid "External link"msgstr "외부 링크"@@ -6830,6 +6971,9 @@ msgstr "자동 생성 ID가 비활성화됨"msgid "Generated IDs are enabled"msgstr "자동 생성 ID가 활성화됨"+msgid "Generating suggestions…"+msgstr "제안 생성 중…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Carbon으로 전환하세요: 견적, 구매, 현장, 재고, 재무를 하나의 시스템에서 운영하여 기존 도구들을 대체합니다."@@ -7113,6 +7257,9 @@ msgstr "역사적 환율(자본)"msgid "History"msgstr "이력"+msgid "Hold the journal as a warning to fix."+msgstr "수정할 수 있도록 경고로 저널을 보류합니다."+msgid "Holiday"msgstr "휴일"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "아이디어, 제안, 또는 문제가 있으신가요?"+msgid "Idempotency key"+msgstr "멱등성 키"+msgid "Identifiers"msgstr "식별자"@@ -7549,6 +7699,9 @@ msgstr "지시사항"msgid "Instructions are inherited from the procedure."msgstr "지시사항은 절차에서 상속됩니다."+msgid "Integration"+msgstr "통합"+msgid "Integration not found"msgstr "연동을 찾을 수 없습니다"@@ -7585,6 +7738,9 @@ msgstr "은행 거래에서 발생하는 이자 수익 또는 비용"msgid "Internal"msgstr "내부"+msgid "Internal Delta"+msgstr "내부 변경사항"+msgid "Internal notes"msgstr "내부 메모"@@ -7967,6 +8123,9 @@ msgstr "이 기간에 날짜가 지정된 임시 분개들은 전기되거나msgid "Journal Entry"msgstr "분개"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "이 날짜 이전의 분개는 잠금으로 처리됩니다. 둘 다 존재하면 공급자에서 보고한 잠금 날짜와 병합됩니다."+msgid "Just one"msgstr "정확히 하나"@@ -8067,6 +8226,12 @@ msgstr "언어"msgid "Last 6 Months"msgstr "지난 6개월"+msgid "Last attempt"+msgstr "마지막 시도"++msgid "Last Attempt"+msgstr "마지막 시도"+msgid "Last Calibration"msgstr "마지막 교정"@@ -8558,6 +8723,12 @@ msgstr "제조사 부품 번호"msgid "Manufacturing"msgstr "제조"+msgid "Map accounts"+msgstr "계정 매핑"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Carbon 계정을 공급자의 계정 과목표에 매핑합니다. 게시된 분개는 매핑된 공급자 계정 코드를 사용하여 푸시됩니다."+msgid "Map Extracted Invoice Lines"msgstr "추출된 인보이스 라인 매핑"@@ -8570,6 +8741,12 @@ msgstr "지금 라인 매핑"msgid "Map your current process, systems, and data"msgstr "현재 프로세스, 시스템, 데이터를 매핑하세요"+msgid "Mapped accounts"+msgstr "매핑된 계정"++msgid "Mapped values"+msgstr "매핑된 값"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "\"{0}\"을(를) 합격으로 표시하시겠습니까?"@@ -8640,6 +8817,12 @@ msgstr "하나라도 일치"msgid "Match any (OR)"msgstr "하나라도 일치(OR)"+msgid "Match by code"+msgstr "코드로 일치"++msgid "Match by name"+msgstr "이름으로 일치"+msgid "Match none"msgstr "일치 안 함"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "메시지"+msgid "Metadata"+msgstr "메타데이터"+msgid "Method"msgstr "제조방법"@@ -8856,6 +9042,12 @@ msgstr "분/1000개"msgid "Minutes/Piece"msgstr "분/개"+msgid "Mismatch"+msgstr "불일치"++msgid "Missing"+msgstr "누락"+msgid "Missing Information"msgstr "누락된 정보"@@ -9372,6 +9564,10 @@ msgstr "아니요"msgid "No {0} found"msgstr "{0}이(가) 없습니다"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "{0} 동기화 작업 없음"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "아직 {0}이(가) 없습니다"@@ -9382,6 +9578,9 @@ msgstr "추가된 역량이 없습니다"msgid "No Access"msgstr "접근 권한 없음"+msgid "No accounts mapped yet"+msgstr "아직 매핑된 계정 없음"+msgid "No action needed"msgstr "조치가 필요하지 않습니다"@@ -9470,6 +9669,12 @@ msgstr "예정된 휴무가 없습니다"msgid "No default attachments yet."msgstr "아직 기본 첨부파일이 없습니다."+msgid "No dimension slots configured"+msgstr "구성된 차원 슬롯이 없습니다"++msgid "No dimension values mapped yet"+msgstr "아직 매핑된 차원 값이 없습니다"+msgid "No draft make method for this item yet."msgstr "이 항목에 대한 초안 제작 방법이 아직 없습니다."@@ -9635,6 +9840,9 @@ msgstr "아직 결제가 없습니다."msgid "No planning data"msgstr "계획 데이터가 없습니다"+msgid "No posted journals in this period for this account"+msgstr "이 계정의 현재 기간에 게시된 저널이 없습니다"+msgid "No pricing for selected quantity"msgstr "선택한 수량에 대한 가격이 없습니다"@@ -9716,6 +9924,9 @@ msgstr "저장 단위 없음"msgid "No suppliers yet"msgstr "아직 공급업체가 없습니다"+msgid "No sync operations yet"+msgstr "아직 동기화 작업 없음"+msgid "No time entries for this week"msgstr "이번 주 시간 기록이 없습니다"@@ -9728,6 +9939,12 @@ msgstr "이 단계에 도구 없음"msgid "No transactions in this period"msgstr "이 기간에 거래가 없습니다"+msgid "No unmapped accounts match a provider code"+msgstr "매핑되지 않은 계정이 공급자 코드와 일치하지 않음"++msgid "No unmapped values match a provider option name"+msgstr "제공자 옵션 이름과 일치하는 매핑되지 않은 값이 없습니다"+msgid "No value needed"msgstr "값이 필요하지 않습니다"@@ -9803,6 +10020,9 @@ msgstr "수량을 충족할 만큼 작업이 충분하지 않습니다"msgid "Not reached"msgstr "도달하지 않음"+msgid "Not recorded"+msgstr "기록되지 않음"+msgid "Not referenced anywhere yet."msgstr "아직 어디에서도 참조되지 않음."@@ -9891,6 +10111,9 @@ msgstr "OEM(주문자상표부착생산)"msgid "of"msgstr "중"+msgid "Off — handled outside the sync"+msgstr "끔 — 동기화 외부에서 처리됨"+msgid "Off — released revisions stay editable"msgstr "꺼짐 — 릴리스된 리비전은 편집 가능한 상태로 유지됨"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "포장명세서"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "금액을 통화의 소수 자릿수만큼 패딩하면 300이 300.00으로 표시되고 숫자 열이 정렬된 상태로 유지됩니다. 이를 끄면 값이 있는 숫자만 표시됩니다. 인쇄된 문서와 저장된 금액은 어느 쪽이든 영향을 받지 않습니다."msgid "Page"msgstr "페이지"@@ -10418,6 +10641,12 @@ msgstr "상위 저장 단위"msgid "Pareto by Type"msgstr "유형별 파레토"+msgid "Park as error"+msgstr "오류로 보관"++msgid "Park the journal with a warning until the value is mapped"+msgstr "값이 매핑될 때까지 경고와 함께 저널을 보류합니다"+msgid "part"msgstr "품목"@@ -10478,6 +10707,9 @@ msgstr "급여율"msgid "Payables"msgstr "매입채무"+msgid "Payables (AP)"+msgstr "미지급금 (AP)"+msgid "Payables (default)"msgstr "매입채무(기본값)"@@ -10574,6 +10806,9 @@ msgstr "기간 종료"msgid "Period End"msgstr "기간 종료"+msgid "Period lock policy"+msgstr "기간 잠금 정책"+msgid "Periodic depreciation expense for fixed assets"msgstr "고정자산에 대한 정기 감가상각비"@@ -10613,6 +10848,9 @@ msgstr "배정 가능한 실물 프린터입니다."msgid "Pick"msgstr "피킹"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Carbon 차원과 게시할 제공자 대상을 선택하세요. 자동 생성은 푸시 시간에 이름으로 누락된 제공자 옵션을 추가합니다."+msgid "Pick a column to sort by"msgstr "정렬할 열을 선택하세요"@@ -10834,6 +11072,9 @@ msgstr "게시자"msgid "Posted By"msgstr "전기자"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "이러한 소스 유형의 게시된 저널은 항상 동기화됩니다. 일일 요약은 하루의 저널을 계정별로 하나의 공급자 항목으로 그룹화합니다."+msgid "Posted once, corrected {corrections} times."msgstr "한 번 게시되었으며 {corrections}번 수정되었습니다."@@ -11124,6 +11365,12 @@ msgstr "속성"msgid "Property"msgstr "속성"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Carbon 계정 번호가 공급자 계정 코드와 정확히 일치하는 제안된 일치 항목입니다."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Carbon 차원 값의 이름이 제공자 옵션 이름과 정확히 일치하는 제안된 일치 항목입니다."+msgid "Protect the go-live date"msgstr "도입일을 사수하세요"@@ -11133,6 +11380,15 @@ msgstr "교육 시간을 확보하고 참석하세요"msgid "Provide process knowledge and inputs"msgstr "공정 지식과 의견을 제공하세요"+msgid "Provider"+msgstr "공급자"++msgid "Provider account"+msgstr "공급자 계정"++msgid "Provider option"+msgstr "제공자 옵션"+msgid "Public"msgstr "공개"@@ -11146,9 +11402,15 @@ msgstr "버전 {0}을(를) 게시하시겠습니까?"msgid "Published by Carbon"msgstr "Carbon에서 게시함"+msgid "Pull"+msgstr "가져오기"+msgid "Pull From"msgstr "가져오기 출처"+msgid "Pull from accounting"+msgstr "회계에서 가져오기"+msgid "Pull from Inventory"msgstr "재고에서 가져오기"@@ -11272,9 +11534,21 @@ msgstr "구매 인보이스"msgid "Purchasing Unit of Measure"msgstr "구매 단위"+msgid "Push"+msgstr "푸시"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "원본 날짜를 설명에 유지하면서 첫 번째 개시 날짜로 재날짜를 지정합니다."+msgid "Push record changes to external systems the moment they happen."msgstr "레코드 변경 사항이 발생하는 즉시 외부 시스템으로 전송합니다."+msgid "Push the journal without the dimension"+msgstr "차원 없이 저널을 푸시합니다"++msgid "Push to accounting"+msgstr "회계로 푸시"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "이 칸반에 대한 {0}을(를) 생성하는 QR 코드"@@ -11481,9 +11755,15 @@ msgstr "원자재"msgid "Raw Materials (default)"msgstr "원자재 (기본값)"+msgid "Re-date to first open day"+msgstr "첫 개설 날짜로 다시 설정"+msgid "Re-keying between quoting, the floor, and finance"msgstr "견적, 현장, 재무 간 데이터 재입력"+msgid "Re-send"+msgstr "다시 보내기"+msgid "Reactivate"msgstr "재활성화"@@ -11505,6 +11785,9 @@ msgstr "개정판이 포함된 읽을 수 있는 ID"msgid "Reading the document..."msgstr "문서를 읽는 중..."+msgid "Ready"+msgstr "준비됨"+msgid "Ready for Quote"msgstr "견적 준비 완료"@@ -11577,6 +11860,9 @@ msgstr "수령, 배송, 판매 송장, 구매 송장, 지급, 대변/차변전msgid "Receivables"msgstr "매출채권"+msgid "Receivables (AR)"+msgstr "미수금 (AR)"+msgid "Receivables (default)"msgstr "매출채권(기본값)"@@ -11635,6 +11921,9 @@ msgstr "최근 생성됨"msgid "Reconcile"msgstr "조정"+msgid "Reconciliation found discrepancies with the provider"+msgstr "조정 중에 공급자와의 불일치를 발견했습니다"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "구매주문을 실제 입고 및 청구 내역과 대조하는 작업 — Carbon에서는 라인 수량과 GR/IR 잔액을 통해 암묵적으로 처리됩니다."@@ -11813,6 +12102,9 @@ msgstr "행 제거"msgid "Remove slide"msgstr "슬라이드 제거"+msgid "Remove slot"+msgstr "슬롯 제거"+msgid "Remove sort by column"msgstr "열 정렬 제거"@@ -12047,6 +12339,9 @@ msgstr "폐기 또는 매각을 통해 자산을 운용에서 제외하고, 순msgid "Retry"msgstr "재시도"+msgid "Retry all"+msgstr "모두 다시 시도"+msgid "Return Home"msgstr "홈으로 돌아가기"@@ -12098,6 +12393,9 @@ msgstr "각 항목의 변경 사항을 검토한 후 확인하세요 — 릴리msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "기간의 대차대조표와 손익계산서를 검토하고 수치가 올바른지 확인하세요. 이것은 수동 승인입니다. 검토가 끝나면 완료로 표시하세요."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "적용하기 전에 제안된 매칭을 검토하세요. 이는 최선의 추측입니다 — 각 항목이 올바른지 확인하세요."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "아래의 경고를 검토한 후 계산을 게시하여 조정을 적용하세요."@@ -12153,6 +12451,9 @@ msgstr "RFQ 번호"msgid "RFQs"msgstr "RFQ"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "게시된 저널에 Carbon 차원을 함께 탑승하세요. 각 슬롯은 하나의 Carbon 차원을 하나의 제공자 분석 대상에 매핑합니다. 아래 값 매핑은 개별 차원 값을 제공자 옵션과 쌍으로 만듭니다."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "애플리케이션 저장"msgid "Save contacts"msgstr "연락처 저장"+msgid "Save dimension settings"+msgstr "차원 설정 저장"+msgid "Save Method"msgstr "저장 방법"@@ -12759,6 +13063,9 @@ msgstr "고객 유형 선택"msgid "Select customers"msgstr "고객 선택"+msgid "Select dimension"+msgstr "차원 선택"+msgid "Select Employee"msgstr "직원 선택"@@ -12795,6 +13102,15 @@ msgstr "방법 선택..."msgid "Select Printer"msgstr "프린터 선택"+msgid "Select provider account"+msgstr "공급자 계정 선택"++msgid "Select provider target"+msgstr "제공자 대상 선택"++msgid "Select provider value"+msgstr "제공자 값 선택"+msgid "Select Quantities"msgstr "수량 선택"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "동기화 옵션 표시"msgid "Show Trailing Zeros"-msgstr ""+msgstr "후행 0 표시"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "{parentCurrency}로 표시"msgid "Showing the first 500 lines"msgstr "처음 500줄을 표시하고 있습니다"+msgid "Showing the newest 200 journals"+msgstr "최신 200개 저널 표시 중"+msgid "Showing the top 1,000 groups by amount"msgstr "금액별 상위 1,000개 그룹을 표시하고 있습니다"@@ -13383,6 +13702,9 @@ msgstr "원본 목록"msgid "Source Method"msgstr "소스 방법"+msgid "Source types"+msgstr "소스 유형"+msgid "Source Version"msgstr "소스 버전"@@ -13721,6 +14043,15 @@ msgstr "후속 품목"msgid "Suffix"msgstr "접미사"+msgid "Suggest mappings"+msgstr "매핑 제안"++msgid "Suggest mappings with AI"+msgstr "AI로 매핑 제안"++msgid "Suggest with AI"+msgstr "AI로 제안"+msgid "Suggested orders you haven't placed yet."msgstr "아직 발주하지 않은 제안 주문입니다."@@ -13926,6 +14257,18 @@ msgstr "여기서 직원 유형을 전환해도 기존 권한은 변경되지msgid "Sync"msgstr "동기화"+msgid "Sync Activity"+msgstr "동기화 활동"++msgid "Sync operation"+msgstr "동기화 작업"++msgid "Sync Tie-Out"+msgstr "동기화 일치"++msgid "Synced"+msgstr "동기화됨"+msgid "System"msgstr "시스템"@@ -14599,6 +14942,9 @@ msgstr "이 유지보수를 수행할 때 기술자가 따르는 절차입니다msgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "이 작업장에서 수행할 수 있는 공정입니다. 공정작업을 예약할 때 공정 선택 목록에 표시되며, 이 작업장을 경유할 수 있는 작업을 제한합니다."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "제공자가 차원 대상을 제공하지 않습니다. 먼저 제공자에서 기능을 활성화하세요(예: 추적 카테고리, 클래스 추적 또는 필드)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "이 라인의 가격이 책정되는 수량 구간입니다. 각 열은 구매자-공급업체 협상 및 후속 문서 전환을 위한 자체 단가를 갖습니다."@@ -15077,6 +15423,9 @@ msgstr "목요일"msgid "Tie shipments through to an invoice with no re-keying"msgstr "재입력 없이 출하를 인보이스까지 연결"+msgid "Tie-out"+msgstr "일치"+msgid "Tie-Out"msgstr "대사"@@ -15533,9 +15882,18 @@ msgstr "작업을 판매주문에서 연결 해제하시겠습니까?"msgid "Unlock"msgstr "잠금 해제"+msgid "Unmapped accounts"+msgstr "매핑되지 않은 계정"++msgid "Unmapped dimension values"+msgstr "매핑되지 않은 차원 값"+msgid "Unmapped Extracted Lines"msgstr "매핑되지 않은 추출 라인"+msgid "Unmapped values"+msgstr "매핑되지 않은 값"+msgid "Unmatched"msgstr "일치하지 않음"@@ -16077,6 +16435,9 @@ msgstr "제안 보기"msgid "View Suppliers"msgstr "공급업체 보기"+msgid "View tie-out"+msgstr "일치 보기"+msgid "View Traceability Graph"msgstr "이력추적 그래프 보기"@@ -16283,6 +16644,9 @@ msgstr "어떤 데이터"msgid "What drove inventory up or down, by any dimension"msgstr "모든 차원별 재고를 높이거나 낮춘 요인"+msgid "What happens when a journal is dated in a locked period."+msgstr "저널이 잠긴 기간에 날짜가 지정되면 어떻게 됩니까?"+msgid "What is {translatedTerm}?"msgstr "{translatedTerm}란 무엇인가요?"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 11e93d04b8..076ca31779 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "Dostawca to firma lub osoba, która sprzedaje Ci części lub usługi."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— ostatnia weryfikacja {0}"+msgid ", {residual}% residual"msgstr ", {residual}% pozostałe"@@ -56,6 +60,10 @@ msgstr "{0} konta"msgid "{0} ago"msgstr "{0} temu"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} komórek z różnicami"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} klientów z saldem"@@ -81,6 +89,15 @@ msgstr "{0} zadań utworzonych"msgid "{0} lines to map"msgstr "{0} linii do mapowania"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} z {1} kont księgowych zmapowanych"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} z {maxSlots} slotów dostawcy jest w użyciu"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} zamówień"@@ -101,6 +118,11 @@ msgstr "{0} dostawców z saldem"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} nieprzetestowane jednostki zostaną zwolnione do Dostępne. Przebadane pozytywne pozostają Dostępne, a przebadane negatywne pozostają Odrzucone."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} niezamapowane konta zostaną dopasowane do {1} kont dostawcy."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} nieopublikowanych dokumentów"@@ -109,6 +131,11 @@ msgstr "{0} nieopublikowanych dokumentów"msgid "{0} uploaded successfully"msgstr "{0} przesłano pomyślnie"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} wartości"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} brakujących wartości"@@ -134,6 +161,9 @@ msgstr "{done} z {total} faz ukończonych"msgid "{from}–{to} of {count}"msgstr "{from}–{to} z {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} z {count} operacji"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# linia} other {# linii}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB limit"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} miesięcy z niezgodnymi sumami"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} dzienników brakuje u dostawcy"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} brakujących dzienników i {mismatchCount} miesięcy z niezgodnościami"+msgid "{name} deleted"msgstr "{name} usunięty"@@ -198,6 +237,9 @@ msgstr "↩ {0} przekierowano z wycofanych {1}"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Dodaj część dostawcy</0> do tego artykułu, aby ustawić preferowanego dostawcę."+msgid "0 operations"+msgstr "0 operacji"+msgid "0-4 weeks"msgstr "0-4 tygodnie"@@ -813,6 +855,9 @@ msgstr "Menedżer konta"msgid "Account Manager"msgstr "Kierownik Konta"+msgid "Account Mapping"+msgstr "Mapowanie Kont"+msgid "Account Number"msgstr "Numer konta"@@ -870,6 +915,9 @@ msgstr "Rozrachunki z odbiorcami"msgid "Accounts receivable for amounts owed by customers"msgstr "Rozrachunki z odbiorcami za kwoty należne od odbiorców."+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Konta przywoływane przez ustawienia domyślne księgowania lub historię dziennika, które nie mają jeszcze mapowania dostawcy."+msgid "Accumulated Depreciation"msgstr "Skumulowana amortyzacja"@@ -1128,6 +1176,9 @@ msgstr "Dodaj wysyłkę"msgid "Add Shipping"msgstr "Dodaj wysyłkę"+msgid "Add slot"+msgstr "Dodaj slot"+msgid "Add Spare Part"msgstr "Dodaj część zamienną"@@ -1219,6 +1270,9 @@ msgstr "Uzgodnij zakres"msgid "Agree who owns what and set a working rhythm"msgstr "Uzgodnij, kto za co odpowiada i ustal rytm pracy"+msgid "AI couldn't confidently match any accounts"+msgstr "AI nie potrafił pewnie dopasować żadnych kont"+msgid "AI Tokens"msgstr "Tokeny AI"@@ -1228,6 +1282,10 @@ msgstr "Wyrównaj zakres"msgid "All"msgstr "Wszystko"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "Wszystkie {0} komórki się wyrównują"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "Wszystkie {total} fazy są gotowe. Świetna robota — Twój zespół jest już w pełni operacyjny."@@ -1264,9 +1322,15 @@ msgstr "Wszystkie lokalizacje"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Wszyscy członkowie wybranych grup i wybrane osoby będą mogły zatwierdzać żądania"+msgid "All posting accounts are mapped"+msgstr "Wszystkie konta księgowania są zmapowane"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "Wszystkie wiersze zaimportowane — {inserted} wstawiono, {updated} zaktualizowano."+msgid "All slotted dimension values are mapped"+msgstr "Wszystkie wartości wymiarów w slotach są mapowane"+msgid "All Suppliers"msgstr "Wszyscy dostawcy"@@ -1464,6 +1528,9 @@ msgstr "Dowolny typ przedmiotu"msgid "Anything not explicitly listed in scope above"msgstr "Wszystko, co nie jest wyraźnie wymienione w zakresie powyżej"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "Wiekowanie zobowiązań"@@ -1540,6 +1607,9 @@ msgstr "Zastosuj reguły cenowe"msgid "Apply Rules On Top"msgstr "Zastosuj reguły na górze"+msgid "Apply suggestions"+msgstr "Zastosuj sugestie"+msgid "Apply To"msgstr "Zastosuj do"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "Reprezentacja AR / AP"+msgid "AR Aging"msgstr "Wiekowanie należności"@@ -1594,6 +1670,9 @@ msgstr "Zaległości z tytułu należności"msgid "AR Overdue"msgstr "AR Zaległy"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "Archiwum"@@ -2146,6 +2225,9 @@ msgstr "Załącznik"msgid "Attachments"msgstr "Załączniki"+msgid "Attempts"+msgstr "Próby"+msgid "Attribute"msgstr "Atrybut"@@ -2194,6 +2276,9 @@ msgstr "Aby automatycznie uruchomić zadanie, należy włączyć automatyczne zwmsgid "Auto Start Job"msgstr "Automatyczne uruchomienie zadania"+msgid "Auto-create"+msgstr "Automatyczne tworzenie"+msgid "Auto-generated QR Code"msgstr "Automatycznie generowany kod QR"@@ -2440,6 +2525,9 @@ msgstr "Zarezerwuj rozmowę z Carbon"msgid "Book Depreciation"msgstr "Amortyzacja księgowa"+msgid "Books lock date (manual)"+msgstr "Data zablokowania ksiąg (ręczna)"+msgid "Both"msgstr "Oba"@@ -2671,6 +2759,9 @@ msgstr "Carbon"msgid "Carbon + you"msgstr "Carbon + ty"+msgid "Carbon account"+msgstr "Konto Carbon"+msgid "Carbon client is not available"msgstr "Klient Carbon jest niedostępny"@@ -2695,9 +2786,19 @@ msgstr "Logo Carbon"msgid "Carbon only"msgstr "Tylko Carbon"+msgid "Carbon Posted"+msgstr "Carbon Zaksięgowano"++msgid "Carbon value"+msgstr "Wartość Carbon"+msgid "Carbon Value"msgstr "Wartość Carbon"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon będzie używać AI do zgadywania konta dostawcy dla każdego z Twoich {0} niezamapowanych kont. Sugestie są punktem wyjścia — możesz je przejrzeć przed zapisaniem czegokolwiek."+msgid "Carbon-only"msgstr "Tylko dla Carbon"@@ -3112,6 +3213,13 @@ msgstr "Kod kreskowy ukończenia"msgid "Completion Time"msgstr "Czas ukończenia"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "obliczono {0}"++msgid "Computed At"+msgstr "Obliczone o"+msgid "Condensed P&L with margins and key subtotals"msgstr "Skrócone rachunki zysków i strat z marżami i kluczowymi subtotalami"@@ -3209,6 +3317,9 @@ msgstr "Potwierdź {0}"msgid "Confirm & release"msgstr "Potwierdź i wydaj"+msgid "Confirm all"+msgstr "Potwierdź wszystkie"+msgid "Confirm and sign the scope"msgstr "Potwierdź i podpisz zakres"@@ -3661,6 +3772,9 @@ msgstr "Nie udało się załadować dokumentów"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Nie można załadować powiązanych dokumentów. Odśwież przed utworzeniem nowego, aby uniknąć duplikatów."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "Nie udało się załadować celów wymiarów dostawcy — sprawdź połączenie i przeładuj stronę."+msgid "Couldn't reschedule the job. Please try again."msgstr "Nie można przeplanować zadania. Spróbuj ponownie."@@ -4210,6 +4324,9 @@ msgstr "Codziennie"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Codzienne spotkania kontrolne, podczas gdy Twój zespół oswaja się z systemem na żywo"+msgid "Daily summary"+msgstr "Podsumowanie dzienne"+msgid "Daily Usage"msgstr "Dzienne użycie"@@ -4926,6 +5043,12 @@ msgstr "wymiar"msgid "Dimension"msgstr "Wymiar"+msgid "Dimension slots"+msgstr "Sloty wymiarów"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Wartości wymiarów z opublikowanych dzienników, które nie mają jeszcze mapowania dostawcy."+msgid "dimensions"msgstr "wymiary"@@ -5026,6 +5149,9 @@ msgstr "Dyspozycje"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "Czy chcesz zastąpić bieżące uprawnienia użytkownika domyślnymi uprawnieniami dla tego typu pracownika?"+msgid "Doc-Backed"+msgstr "Wsparte dokumentami"+msgid "Docs"msgstr "Dokumentacja"@@ -5050,6 +5176,9 @@ msgstr "Dokument:"msgid "Documents"msgstr "Dokumenty"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Dokumenty wysyła faktury, rachunki i płatności jako dokumenty dostawcy; ich dzienniki są rejestrowane jako pokryte dokumentem. Pobiera również płatności zarejestrowane u dostawcy z powrotem do Carbon, zamykając pasującą fakturę lub rachunek i publikując dziennik GL Carbon. Off rejestruje je jako celowo wyłączone."+msgid "Don't Cancel"msgstr "Nie anuluj"@@ -5975,6 +6104,12 @@ msgstr "Certifikat Zwolnienia"msgid "Exemption Reason"msgstr "Powód Zwolnienia"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Istniejące mapowania. Wybierz inne konto dostawcy, aby ponownie zmapować."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Istniejące mapowania. Wybierz inną opcję dostawcy, aby przezmapować."+msgid "Expand"msgstr "Rozwiń"@@ -6111,9 +6246,15 @@ msgstr "Cena rozszerzona"msgid "External"msgstr "Zewnętrzne"+msgid "External Delta"+msgstr "Różnica zewnętrzna"+msgid "External document"msgstr "Dokument zewnętrzny"+msgid "External ID"+msgstr "ID Zewnętrzne"+msgid "External link"msgstr "Link zewnętrzny"@@ -6830,6 +6971,9 @@ msgstr "Wygenerowane identyfikatory są wyłączone"msgid "Generated IDs are enabled"msgstr "Wygenerowane identyfikatory są włączone"+msgid "Generating suggestions…"+msgstr "Generowanie sugestii…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Uruchom Carbon: jeden system obsługujący wycenę, zakupy, halę produkcyjną, magazyn i finanse, zastępujący obecne narzędzia."@@ -7113,6 +7257,9 @@ msgstr "Kurs Historyczny (Kapitał Własny)"msgid "History"msgstr "Historia"+msgid "Hold the journal as a warning to fix."+msgstr "Zatrzymaj dziennik jako ostrzeżenie do naprawy."+msgid "Holiday"msgstr "Święto"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "Pomysly, sugestie lub problemy?"+msgid "Idempotency key"+msgstr "Klucz idempotencji"+msgid "Identifiers"msgstr "Identyfikatory"@@ -7549,6 +7699,9 @@ msgstr "Instrukcje"msgid "Instructions are inherited from the procedure."msgstr "Instrukcje są dziedziczone z procedury."+msgid "Integration"+msgstr "Integracja"+msgid "Integration not found"msgstr "Integracja nie znaleziona"@@ -7585,6 +7738,9 @@ msgstr "Dochód lub wydatek z tytułu odsetek z działalności bankowej"msgid "Internal"msgstr "Wewnętrzne"+msgid "Internal Delta"+msgstr "Różnica wewnętrzna"+msgid "Internal notes"msgstr "Notatki wewnętrzne"@@ -7967,6 +8123,9 @@ msgstr "Wpisy dziennika datowane w tym okresie, które są w wersji roboczej, mumsgid "Journal Entry"msgstr "Wpis dziennika"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "Dzienniki datowane na lub przed tą datą są traktowane jako zablokowane. Scalane z datą blokady zgłoszoną przez dostawcę, gdy obie istnieją."+msgid "Just one"msgstr "Tylko jeden"@@ -8067,6 +8226,12 @@ msgstr "Język"msgid "Last 6 Months"msgstr "Ostatnie 6 miesięcy"+msgid "Last attempt"+msgstr "Ostatnia próba"++msgid "Last Attempt"+msgstr "Ostatnia Próba"+msgid "Last Calibration"msgstr "Ostatnia Kalibracja"@@ -8558,6 +8723,12 @@ msgstr "Numer części producenta"msgid "Manufacturing"msgstr "Produkcja"+msgid "Map accounts"+msgstr "Zmapuj konta"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Mapuj konta Carbon na plan kont dostawcy. Opublikowane dzienniki są wysyłane przy użyciu zmapowanego kodu konta dostawcy."+msgid "Map Extracted Invoice Lines"msgstr "Mapuj wyodrębnione linie faktury"@@ -8570,6 +8741,12 @@ msgstr "Mapuj linie teraz"msgid "Map your current process, systems, and data"msgstr "Zmapuj swój obecny proces, systemy i dane"+msgid "Mapped accounts"+msgstr "Zmapowane konta"++msgid "Mapped values"+msgstr "Zmapowane wartości"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "Oznaczyć „{0}\" jako ukończone?"@@ -8640,6 +8817,12 @@ msgstr "Dopasuj dowolny"msgid "Match any (OR)"msgstr "Dopasuj dowolny (LUB)"+msgid "Match by code"+msgstr "Dopasuj według kodu"++msgid "Match by name"+msgstr "Dopasuj po nazwie"+msgid "Match none"msgstr "Nie dopasuj żaden"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Wiadomość"+msgid "Metadata"+msgstr "Metadane"+msgid "Method"msgstr "Metoda"@@ -8856,6 +9042,12 @@ msgstr "Minuty/1000 Sztuk"msgid "Minutes/Piece"msgstr "Minuty/Sztuka"+msgid "Mismatch"+msgstr "Niezgodność"++msgid "Missing"+msgstr "Brakujący"+msgid "Missing Information"msgstr "Brakujące informacje"@@ -9372,6 +9564,10 @@ msgstr "Nie"msgid "No {0} found"msgstr "Nie znaleziono {0}"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "Brak operacji synchronizacji {0}"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "Jeszcze brak {0}"@@ -9382,6 +9578,9 @@ msgstr "Brak dodanych umiejętności"msgid "No Access"msgstr "Brak dostępu"+msgid "No accounts mapped yet"+msgstr "Nie zmapowano jeszcze żadnych kont"+msgid "No action needed"msgstr "Brak wymaganych działań"@@ -9470,6 +9669,12 @@ msgstr "Brak zaplanowanych dni wolnych"msgid "No default attachments yet."msgstr "Brak domyślnych załączników."+msgid "No dimension slots configured"+msgstr "Brak skonfigurowanych slotów wymiarów"++msgid "No dimension values mapped yet"+msgstr "Nie ma jeszcze zmapowanych wartości wymiarów"+msgid "No draft make method for this item yet."msgstr "Brak jeszcze wersji roboczej metody wytwarzania dla tego elementu."@@ -9635,6 +9840,9 @@ msgstr "Brak płatności."msgid "No planning data"msgstr "Brak danych planowania"+msgid "No posted journals in this period for this account"+msgstr "Brak zaksięgowanych dzienników w tym okresie dla tego konta"+msgid "No pricing for selected quantity"msgstr "Brak cen dla wybranej ilości"@@ -9716,6 +9924,9 @@ msgstr "Brak jednostki magazynowania"msgid "No suppliers yet"msgstr "Brak dostawców"+msgid "No sync operations yet"+msgstr "Brak operacji synchronizacji"+msgid "No time entries for this week"msgstr "Brak wpisów czasu pracy w tym tygodniu"@@ -9728,6 +9939,12 @@ msgstr "Brak narzędzi dla tego kroku"msgid "No transactions in this period"msgstr "Brak transakcji w tym okresie"+msgid "No unmapped accounts match a provider code"+msgstr "Żadne niezamapowane konta nie pasują do kodu dostawcy"++msgid "No unmapped values match a provider option name"+msgstr "Żadne niezamapowane wartości nie odpowiadają nazwie opcji dostawcy"+msgid "No value needed"msgstr "Wartość nie jest wymagana"@@ -9803,6 +10020,9 @@ msgstr "Niewystarczająca liczba zadań do pokrycia ilości"msgid "Not reached"msgstr "Nieosiągnięty"+msgid "Not recorded"+msgstr "Nie zarejestrowano"+msgid "Not referenced anywhere yet."msgstr "Nie odwołuje się nigdzie."@@ -9891,6 +10111,9 @@ msgstr "OEM (producent oryginalnego sprzętu)"msgid "of"msgstr "z"+msgid "Off — handled outside the sync"+msgstr "Wyłączone — obsługiwane poza synchronizacją"+msgid "Off — released revisions stay editable"msgstr "Wyłączone — wydane wersje pozostają edytowalne"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "Dokument wysyłki"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "Uzupełniaj kwoty do liczby miejsc dziesiętnych waluty, aby 300 pojawiało się jako 300,00 i kolumny liczb były wyrównane. Wyłącz tę opcję, aby wyświetlać tylko istotne cyfry. Drukowane dokumenty i zapisane kwoty nie ulegają zmianie, niezależnie od tego ustawienia."msgid "Page"msgstr "Strona"@@ -10418,6 +10641,12 @@ msgstr "Nadrzędna jednostka magazynowa"msgid "Pareto by Type"msgstr "Pareto wg typu"+msgid "Park as error"+msgstr "Zaparkuj jako błąd"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Zatrzymaj dziennik z ostrzeżeniem aż do zmapowania wartości"+msgid "part"msgstr "części"@@ -10478,6 +10707,9 @@ msgstr "Kurs płatności"msgid "Payables"msgstr "Zobowiązania (domyślnie)"+msgid "Payables (AP)"+msgstr "Zobowiązania (AP)"+msgid "Payables (default)"msgstr "warunek płatności"@@ -10574,6 +10806,9 @@ msgstr "Zamknięcie okresu"msgid "Period End"msgstr "Koniec okresu"+msgid "Period lock policy"+msgstr "Polityka blokady okresu"+msgid "Periodic depreciation expense for fixed assets"msgstr "Kompletacja oferuje śledziane jednostki w kolejności najwcześniejszego wygaśnięcia, więc zapasy wygasające najwcześniej są domyślnie wydawane jako pierwsze."@@ -10613,6 +10848,9 @@ msgstr "Drukarki fizyczne dostępne do przypisania."msgid "Pick"msgstr "Wybierz"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Wybierz wymiar Carbon i cel dostawcy, do którego będzie wysyłany. Automatyczne tworzenie dodaje brakujące opcje dostawcy po nazwie podczas wysłania."+msgid "Pick a column to sort by"msgstr "Wybierz kolumnę do sortowania"@@ -10834,6 +11072,9 @@ msgstr "Opublikowane przez"msgid "Posted By"msgstr "Opublikowano przez"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "Zaksięgowane dzienniki z tymi typami źródeł zawsze się synchronizują. Dzienne podsumowanie grupuje dzienniki z jednego dnia w jeden wpis dostawcy na konto."+msgid "Posted once, corrected {corrections} times."msgstr "Opublikowane raz, poprawione {corrections} razy."@@ -11124,6 +11365,12 @@ msgstr "Właściwości"msgid "Property"msgstr "Właściwość"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Proponowane dopasowania, w których numer konta Carbon dokładnie odpowiada kodowi konta dostawcy."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Proponowane dopasowania, gdzie nazwa wartości wymiaru Carbon dokładnie pasuje do nazwy opcji dostawcy."+msgid "Protect the go-live date"msgstr "Chroń datę wdrożenia"@@ -11133,6 +11380,15 @@ msgstr "Zarezerwuj czas na szkolenie i weź w nim udział"msgid "Provide process knowledge and inputs"msgstr "Udostępnij wiedzę procesową i dane wejściowe"+msgid "Provider"+msgstr "Dostawca"++msgid "Provider account"+msgstr "Konto dostawcy"++msgid "Provider option"+msgstr "Opcja dostawcy"+msgid "Public"msgstr "Publiczny"@@ -11146,9 +11402,15 @@ msgstr "Opublikować wersję {0}?"msgid "Published by Carbon"msgstr "Opublikowano przez Carbon"+msgid "Pull"+msgstr "Pobierz"+msgid "Pull From"msgstr "Pobierz z"+msgid "Pull from accounting"+msgstr "Pobierz z systemu księgowego"+msgid "Pull from Inventory"msgstr "Pobierz z magazynu"@@ -11272,9 +11534,21 @@ msgstr "Faktury zakupu"msgid "Purchasing Unit of Measure"msgstr "Jednostka miary zakupu"+msgid "Push"+msgstr "Wyślij"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "Przesuń go z nową datą na pierwszy otwarty dzień, zachowując oryginalną datę w naracji."+msgid "Push record changes to external systems the moment they happen."msgstr "Wyślij zmiany rekordów do systemów zewnętrznych w momencie ich wystąpienia."+msgid "Push the journal without the dimension"+msgstr "Wyślij dziennik bez wymiaru"++msgid "Push to accounting"+msgstr "Wyślij do systemu księgowego"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "Kod QR do utworzenia {0} dla tego kanbanu"@@ -11481,9 +11755,15 @@ msgstr "Surowce"msgid "Raw Materials (default)"msgstr "Surowce (domyślnie)"+msgid "Re-date to first open day"+msgstr "Zmień datę na pierwszy otwarty dzień"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Ponowne wprowadzanie danych między ofertowaniem, halą produkcyjną i finansami"+msgid "Re-send"+msgstr "Wyślij ponownie"+msgid "Reactivate"msgstr "Ponownie aktywuj"@@ -11505,6 +11785,9 @@ msgstr "Czytelny identyfikator z wersją"msgid "Reading the document..."msgstr "Czytanie dokumentu..."+msgid "Ready"+msgstr "Gotowe"+msgid "Ready for Quote"msgstr "Gotowy do wyceny"@@ -11577,6 +11860,9 @@ msgstr "Pokwitowania, przesyłki, faktury sprzedaży, faktury zakupu, płatnoścmsgid "Receivables"msgstr "Należności (domyślnie)"+msgid "Receivables (AR)"+msgstr "Należności (AR)"+msgid "Receivables (default)"msgstr "Uzgodnienie zamówienia zakupowego z tym, co zostało odebrane i zafakturowane — niejawnie w Carbon, przez ilości wierszy i saldo GR/IR."@@ -11635,6 +11921,9 @@ msgstr "Niedawno utworzone"msgid "Reconcile"msgstr "Reconcile"+msgid "Reconciliation found discrepancies with the provider"+msgstr "Reconcyliacja wykazała rozbieżności z dostawcą"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Okres Odzysku"@@ -11813,6 +12102,9 @@ msgstr "Usuń wiersz"msgid "Remove slide"msgstr "Usuń slajd"+msgid "Remove slot"+msgstr "Usuń slot"+msgid "Remove sort by column"msgstr "Usuń sortowanie według kolumny"@@ -12047,6 +12339,9 @@ msgstr "Wycofanie środka trwałego z użytkowania poprzez złomowanie lub sprzemsgid "Retry"msgstr "Ponów"+msgid "Retry all"+msgstr "Ponów wszystko"+msgid "Return Home"msgstr "Wróć do domu"@@ -12098,6 +12393,9 @@ msgstr "Przejrzyj zmiany każdego elementu, a następnie potwierdź — wydaniemsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Przejrzyj bilans i rachunek zysków i strat okresu i potwierdź, że liczby wyglądają prawidłowo. To jest ręczne zatwierdzenie — oznacz jako gotowe po ich przejrzeniu."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Przejrzyj sugerowane dopasowania przed zastosowaniem. To są najlepsze zgadywanki — potwierdź, że każde jest poprawne."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Przejrzyj ostrzeżenia poniżej, a następnie opublikuj liczenie, aby zastosować korekty."@@ -12153,6 +12451,9 @@ msgstr "Numer RFQ"msgid "RFQs"msgstr "Zapytania ofertowe"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Dołącz wymiary Carbon do wysyłanych dzienników. Każdy slot mapuje jeden wymiar Carbon na jeden cel analityki dostawcy; mapowanie wartości poniżej łączy poszczególne wartości wymiarów z opcjami dostawcy."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Zapisz aplikacje"msgid "Save contacts"msgstr "Zapisz kontakty"+msgid "Save dimension settings"+msgstr "Zapisz ustawienia wymiarów"+msgid "Save Method"msgstr "Zapisz metodę"@@ -12759,6 +13063,9 @@ msgstr "Wybierz typy klientów"msgid "Select customers"msgstr "Wybierz klientów"+msgid "Select dimension"+msgstr "Wybierz wymiar"+msgid "Select Employee"msgstr "Wybierz pracownika"@@ -12795,6 +13102,15 @@ msgstr "Wybierz metodę..."msgid "Select Printer"msgstr "Wybierz drukarkę"+msgid "Select provider account"+msgstr "Wybierz konto dostawcy"++msgid "Select provider target"+msgstr "Wybierz cel dostawcy"++msgid "Select provider value"+msgstr "Wybierz wartość dostawcy"+msgid "Select Quantities"msgstr "Wybierz ilości"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "Pokaż opcje synchronizacji"msgid "Show Trailing Zeros"-msgstr ""+msgstr "Wyświetlaj zera końcowe"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "Wyświetlanie w {parentCurrency}"msgid "Showing the first 500 lines"msgstr "Pokazywanie pierwszych 500 linii"+msgid "Showing the newest 200 journals"+msgstr "Wyświetlanie 200 najnowszych dzienników"+msgid "Showing the top 1,000 groups by amount"msgstr "Pokazywanie 1000 najlepszych grup wg kwoty"@@ -13383,6 +13702,9 @@ msgstr "Lista źródłowa"msgid "Source Method"msgstr "Metoda źródłowa"+msgid "Source types"+msgstr "Typy źródła"+msgid "Source Version"msgstr "Wersja źródłowa"@@ -13721,6 +14043,15 @@ msgstr "Część następcza"msgid "Suffix"msgstr "Sufiks"+msgid "Suggest mappings"+msgstr "Zasugeruj mapowania"++msgid "Suggest mappings with AI"+msgstr "Zasugeruj mapowania przy pomocy AI"++msgid "Suggest with AI"+msgstr "Zasugeruj przy pomocy AI"+msgid "Suggested orders you haven't placed yet."msgstr "Sugerowane zamówienia, które jeszcze nie złożyłeś."@@ -13926,6 +14257,18 @@ msgstr "Zmiana typu pracownika tutaj nie zmienia ich istniejących uprawnień; omsgid "Sync"msgstr "Synchronizuj"+msgid "Sync Activity"+msgstr "Działalność synchronizacji"++msgid "Sync operation"+msgstr "Operacja synchronizacji"++msgid "Sync Tie-Out"+msgstr "Wyrównanie synchronizacji"++msgid "Synced"+msgstr "Zsynchronizowano"+msgid "System"msgstr "System"@@ -14599,6 +14942,9 @@ msgstr "Procedura, którą technicycy stosują podczas wykonywania tej konserwacmsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "Procesy, które to centrum pracy może uruchamiać; pojawia się w selectorach procesów podczas planowania operacji i ogranicza, które zadania mogą trasować przez to centrum pracy."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "Dostawca nie oferuje celów wymiarów. Najpierw włącz funkcję u dostawcy (np. kategorie śledzenia, śledzenie klasy lub pola)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Punkty przerwania ilości, po które ta linia jest wyceniana; każda kolumna ma swoją własną cenę za jednostkę do negocjacji kupujący-dostawca i konwersji do dokumentów poniżej."@@ -15077,6 +15423,9 @@ msgstr "Czwartek"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Powiąż przesyłki z fakturą bez ponownego wprowadzania danych"+msgid "Tie-out"+msgstr "Wyrównanie"+msgid "Tie-Out"msgstr "Uzgodnienie"@@ -15533,9 +15882,18 @@ msgstr "Odłączyć zadanie od zamówienia sprzedaży?"msgid "Unlock"msgstr "Odblokuj"+msgid "Unmapped accounts"+msgstr "Niezamapowane konta"++msgid "Unmapped dimension values"+msgstr "Niezamapowane wartości wymiarów"+msgid "Unmapped Extracted Lines"msgstr "Niemapowane wyodrębnione linie"+msgid "Unmapped values"+msgstr "Niezamapowane wartości"+msgid "Unmatched"msgstr "Niedopasowane"@@ -16077,6 +16435,9 @@ msgstr "Wyświetl sugestię"msgid "View Suppliers"msgstr "Wyświetl dostawców"+msgid "View tie-out"+msgstr "Wyświetl wyrównanie"+msgid "View Traceability Graph"msgstr "Wyświetl Graf Możliwości Śledzenia"@@ -16283,6 +16644,9 @@ msgstr "Jakie dane"msgid "What drove inventory up or down, by any dimension"msgstr "Co spowodowało wzrost lub spadek zapasów, wg dowolnego wymiaru"+msgid "What happens when a journal is dated in a locked period."+msgstr "Co się dzieje, gdy dziennik jest datowany w zablokowanym okresie."+msgid "What is {translatedTerm}?"msgstr "Co to jest {translatedTerm}?"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 1e27624aa0..65edb0ce2a 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "Um fornecedor é uma empresa ou pessoa que vende peças ou serviços para você."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— última verificação {0}"+msgid ", {residual}% residual"msgstr ", {residual}% residual"@@ -56,6 +60,10 @@ msgstr "{0} contas"msgid "{0} ago"msgstr "{0} atrás"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} células com deltas"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} clientes com saldo"@@ -81,6 +89,15 @@ msgstr "{0} trabalhos criados"msgid "{0} lines to map"msgstr "{0} linhas para mapear"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} de {1} contas de lançamento mapeadas"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} de {maxSlots} slots de provedor utilizados"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} pedidos"@@ -101,6 +118,11 @@ msgstr "{0} fornecedores com saldo"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} entidades não amostradas serão liberadas para Disponível. Passes amostradas permanecem Disponível e falhas amostradas permanecem Rejeitadas."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} contas não mapeadas serão comparadas com {1} contas do provedor."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} documentos não lançados"@@ -109,6 +131,11 @@ msgstr "{0} documentos não lançados"msgid "{0} uploaded successfully"msgstr "{0} enviado com sucesso"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} valores"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} valores ausentes"@@ -134,6 +161,9 @@ msgstr "{done} de {total} fases concluídas"msgid "{from}–{to} of {count}"msgstr "{from}–{to} de {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} de {count} operações"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# linha} other {# linhas}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB limit"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} meses com totais não correspondentes"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} periódicos faltando no provedor"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} periódicos faltando e {mismatchCount} meses não correspondentes"+msgid "{name} deleted"msgstr "{name} eliminado"@@ -198,6 +237,9 @@ msgstr "↩ {0} redirecionado de {1} obsoleto"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Adicione uma peça de fornecedor</0> para este item para definir um fornecedor preferido."+msgid "0 operations"+msgstr "0 operações"+msgid "0-4 weeks"msgstr "0-4 semanas"@@ -813,6 +855,9 @@ msgstr "Gerenciador de conta"msgid "Account Manager"msgstr "Gerente de Conta"+msgid "Account Mapping"+msgstr "Mapeamento de Contas"+msgid "Account Number"msgstr "Número da Conta"@@ -870,6 +915,9 @@ msgstr "Contas a receber"msgid "Accounts receivable for amounts owed by customers"msgstr "Contas a receber para valores devidos pelos clientes."+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Contas referenciadas por padrões de lançamento ou histórico de periódicos que ainda não têm mapeamento de provedor."+msgid "Accumulated Depreciation"msgstr "Depreciação acumulada"@@ -1128,6 +1176,9 @@ msgstr "Adicionar Envio"msgid "Add Shipping"msgstr "Adicionar Envio"+msgid "Add slot"+msgstr "Adicionar slot"+msgid "Add Spare Part"msgstr "Adicionar Peça de Reposição"@@ -1219,6 +1270,9 @@ msgstr "Concordar sobre o escopo"msgid "Agree who owns what and set a working rhythm"msgstr "Concordar quem é responsável por quê e estabelecer um ritmo de trabalho"+msgid "AI couldn't confidently match any accounts"+msgstr "A IA não conseguiu corresponder confiantemente com nenhuma conta"+msgid "AI Tokens"msgstr "Tokens de IA"@@ -1228,6 +1282,10 @@ msgstr "Alinhar no escopo"msgid "All"msgstr "Todos"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "Todas as {0} células correspondem"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "Todas as {total} fases estão concluídas. Excelente trabalho — sua equipe está funcionando."@@ -1264,9 +1322,15 @@ msgstr "Todos os Locais"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Todos os membros dos grupos selecionados e indivíduos selecionados poderão aprovar solicitações"+msgid "All posting accounts are mapped"+msgstr "Todas as contas de lançamento estão mapeadas"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "Todas as linhas importadas — {inserted} inseridas, {updated} atualizadas."+msgid "All slotted dimension values are mapped"+msgstr "Todos os valores de dimensão com slot estão mapeados"+msgid "All Suppliers"msgstr "Todos os Fornecedores"@@ -1464,6 +1528,9 @@ msgstr "Qualquer tipo de item"msgid "Anything not explicitly listed in scope above"msgstr "Qualquer coisa não explicitamente listada no escopo acima"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "Envelhecimento de Contas a Pagar"@@ -1540,6 +1607,9 @@ msgstr "Aplicar regras de preços"msgid "Apply Rules On Top"msgstr "Aplicar regras na parte superior"+msgid "Apply suggestions"+msgstr "Aplicar sugestões"+msgid "Apply To"msgstr "Aplicar a"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "Representação AR / AP"+msgid "AR Aging"msgstr "Envelhecimento de Contas a Receber"@@ -1594,6 +1670,9 @@ msgstr "AR Pendente"msgid "AR Overdue"msgstr "AR Vencido"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "Arquivo"@@ -2146,6 +2225,9 @@ msgstr "Anexo"msgid "Attachments"msgstr "Anexos"+msgid "Attempts"+msgstr "Tentativas"+msgid "Attribute"msgstr "Atributo"@@ -2194,6 +2276,9 @@ msgstr "A liberação automática deve estar ativada para iniciar um trabalho aumsgid "Auto Start Job"msgstr "Iniciar Trabalho Automaticamente"+msgid "Auto-create"+msgstr "Criar automaticamente"+msgid "Auto-generated QR Code"msgstr "Código QR gerado automaticamente"@@ -2440,6 +2525,9 @@ msgstr "Agende uma chamada com Carbon"msgid "Book Depreciation"msgstr "Depreciação Contábil"+msgid "Books lock date (manual)"+msgstr "Data de bloqueio de livros (manual)"+msgid "Both"msgstr "Ambos"@@ -2671,6 +2759,9 @@ msgstr "Carbon"msgid "Carbon + you"msgstr "Carbon + você"+msgid "Carbon account"+msgstr "Conta Carbon"+msgid "Carbon client is not available"msgstr "Cliente Carbon não está disponível"@@ -2695,9 +2786,19 @@ msgstr "Logótipo do Carbon"msgid "Carbon only"msgstr "Apenas Carbon"+msgid "Carbon Posted"+msgstr "Enviado para o Carbon"++msgid "Carbon value"+msgstr "Valor Carbon"+msgid "Carbon Value"msgstr "Valor Carbon"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "O Carbon usará IA para adivinhar uma conta do provedor para cada uma de suas {0} contas não mapeadas. As sugestões são um ponto de partida — você pode revisá-las antes de salvar qualquer coisa."+msgid "Carbon-only"msgstr "Apenas Carbon"@@ -3112,6 +3213,13 @@ msgstr "Código de Barras de Conclusão"msgid "Completion Time"msgstr "Tempo de Conclusão"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "calculado {0}"++msgid "Computed At"+msgstr "Calculado em"+msgid "Condensed P&L with margins and key subtotals"msgstr "P&L Condensado com margens e subtotais principais"@@ -3209,6 +3317,9 @@ msgstr "Confirmar {0}"msgid "Confirm & release"msgstr "Confirmar e lançar"+msgid "Confirm all"+msgstr "Confirmar tudo"+msgid "Confirm and sign the scope"msgstr "Confirmar e assinar o escopo"@@ -3661,6 +3772,9 @@ msgstr "Não foi possível carregar documentos"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Não foi possível carregar os documentos relacionados. Atualize antes de criar um novo para evitar duplicatas."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "Não foi possível carregar os alvos de dimensão do provedor — verifique a conexão e recarregue."+msgid "Couldn't reschedule the job. Please try again."msgstr "Não foi possível reagendar o trabalho. Por favor, tente novamente."@@ -4210,6 +4324,9 @@ msgstr "Diariamente"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Verificações diárias enquanto sua equipe se adapta ao sistema em produção"+msgid "Daily summary"+msgstr "Resumo diário"+msgid "Daily Usage"msgstr "Uso Diário"@@ -4926,6 +5043,12 @@ msgstr "dimensão"msgid "Dimension"msgstr "Dimensão"+msgid "Dimension slots"+msgstr "Slots de dimensão"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Valores de dimensão em diários postados que ainda não têm mapeamento de provedor."+msgid "dimensions"msgstr "dimensões"@@ -5026,6 +5149,9 @@ msgstr "Disposições"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "Deseja sobrescrever as permissões atuais do utilizador com as permissões padrão para este tipo de funcionário?"+msgid "Doc-Backed"+msgstr "Apoiado em documento"+msgid "Docs"msgstr "Documentação"@@ -5050,6 +5176,9 @@ msgstr "Documento:"msgid "Documents"msgstr "Documentos"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Documentos envia faturas, contas a pagar e pagamentos como documentos nativos do provedor; seus diários são registados como cobertos pelo documento. Também obtém pagamentos registados no provedor de volta para Carbon, fechando a fatura ou conta a pagar correspondente e publicando um diário GL do Carbon. Off registra-os como deliberadamente excluídos."+msgid "Don't Cancel"msgstr "Não Cancelar"@@ -5975,6 +6104,12 @@ msgstr "Certificado de Isenção"msgid "Exemption Reason"msgstr "Motivo da Isenção"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Mapeamentos existentes. Escolha uma conta de provedor diferente para remapear."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Mapeamentos existentes. Escolha uma opção de provedor diferente para remapear."+msgid "Expand"msgstr "Expandir"@@ -6111,9 +6246,15 @@ msgstr "Preço Estendido"msgid "External"msgstr "Externo"+msgid "External Delta"+msgstr "Delta externo"+msgid "External document"msgstr "Documento externo"+msgid "External ID"+msgstr "ID Externo"+msgid "External link"msgstr "Link externo"@@ -6830,6 +6971,9 @@ msgstr "IDs gerados estão desativados"msgid "Generated IDs are enabled"msgstr "IDs gerados estão ativados"+msgid "Generating suggestions…"+msgstr "Gerando sugestões…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Ativar no Carbon: um sistema executando cotações, compras, chão de fábrica, inventário e finanças, substituindo as ferramentas atuais."@@ -7113,6 +7257,9 @@ msgstr "Taxa Histórica (Patrimônio)"msgid "History"msgstr "Histórico"+msgid "Hold the journal as a warning to fix."+msgstr "Manter o diário como aviso para correção."+msgid "Holiday"msgstr "Feriado"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "Ideias, sugestões ou problemas?"+msgid "Idempotency key"+msgstr "Chave de Idempotência"+msgid "Identifiers"msgstr "Identificadores"@@ -7549,6 +7699,9 @@ msgstr "Instruções"msgid "Instructions are inherited from the procedure."msgstr "As instruções são herdadas do procedimento."+msgid "Integration"+msgstr "Integração"+msgid "Integration not found"msgstr "Integração não encontrada"@@ -7585,6 +7738,9 @@ msgstr "Receita ou despesa de juros de atividades bancárias"msgid "Internal"msgstr "Interno"+msgid "Internal Delta"+msgstr "Delta interno"+msgid "Internal notes"msgstr "Notas internas"@@ -7967,6 +8123,9 @@ msgstr "Lançamentos de diário datados neste período que ainda estão em Rascumsgid "Journal Entry"msgstr "Lançamento de Diário"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "Os periódicos datados nesta data ou antes são tratados como bloqueados. Mesclado com a data de bloqueio informada pelo provedor quando ambas existem."+msgid "Just one"msgstr "Apenas um"@@ -8067,6 +8226,12 @@ msgstr "Idioma"msgid "Last 6 Months"msgstr "Últimos 6 Meses"+msgid "Last attempt"+msgstr "Última tentativa"++msgid "Last Attempt"+msgstr "Última Tentativa"+msgid "Last Calibration"msgstr "Última Calibração"@@ -8558,6 +8723,12 @@ msgstr "Número de Peça do Fabricante"msgid "Manufacturing"msgstr "Fabricação"+msgid "Map accounts"+msgstr "Mapear contas"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Mapeie contas Carbon para o plano de contas do provedor. Os periódicos lançados são enviados usando o código de conta de provedor mapeado."+msgid "Map Extracted Invoice Lines"msgstr "Mapear Linhas de Fatura Extraídas"@@ -8570,6 +8741,12 @@ msgstr "Mapear Linhas Agora"msgid "Map your current process, systems, and data"msgstr "Mapeie seu processo, sistemas e dados atuais"+msgid "Mapped accounts"+msgstr "Contas Mapeadas"++msgid "Mapped values"+msgstr "Valores mapeados"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "Marcar \"{0}\" como aprovado?"@@ -8640,6 +8817,12 @@ msgstr "Corresponder a qualquer"msgid "Match any (OR)"msgstr "Corresponder a qualquer (OU)"+msgid "Match by code"+msgstr "Corresponder por código"++msgid "Match by name"+msgstr "Corresponder por nome"+msgid "Match none"msgstr "Não corresponder a nenhum"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Mensagem"+msgid "Metadata"+msgstr "Metadados"+msgid "Method"msgstr "Método"@@ -8856,6 +9042,12 @@ msgstr "Minutos/1000 Peças"msgid "Minutes/Piece"msgstr "Minutos/Peça"+msgid "Mismatch"+msgstr "Não correspondência"++msgid "Missing"+msgstr "Faltando"+msgid "Missing Information"msgstr "Informações Faltantes"@@ -9372,6 +9564,10 @@ msgstr "Não"msgid "No {0} found"msgstr "Nenhum {0} encontrado"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "Sem operações de sincronização {0}"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "Nenhum {0} ainda"@@ -9382,6 +9578,9 @@ msgstr "Nenhuma habilidade adicionada"msgid "No Access"msgstr "Sem Acesso"+msgid "No accounts mapped yet"+msgstr "Nenhuma conta mapeada ainda"+msgid "No action needed"msgstr "Nenhuma ação necessária"@@ -9470,6 +9669,12 @@ msgstr "Nenhum dia de folga agendado"msgid "No default attachments yet."msgstr "Nenhum anexo padrão ainda."+msgid "No dimension slots configured"+msgstr "Nenhum slot de dimensão configurado"++msgid "No dimension values mapped yet"+msgstr "Nenhum valor de dimensão mapeado ainda"+msgid "No draft make method for this item yet."msgstr "Nenhum método de fabricação de rascunho para este item ainda."@@ -9635,6 +9840,9 @@ msgstr "Nenhum pagamento ainda."msgid "No planning data"msgstr "Sem dados de planejamento"+msgid "No posted journals in this period for this account"+msgstr "Nenhum diário lançado neste período para esta conta"+msgid "No pricing for selected quantity"msgstr "Sem preço para a quantidade selecionada"@@ -9716,6 +9924,9 @@ msgstr "Sem unidade de armazenamento"msgid "No suppliers yet"msgstr "Nenhum fornecedor ainda"+msgid "No sync operations yet"+msgstr "Nenhuma operação de sincronização ainda"+msgid "No time entries for this week"msgstr "Sem registros de tempo para esta semana"@@ -9728,6 +9939,12 @@ msgstr "Nenhuma ferramenta para esta etapa"msgid "No transactions in this period"msgstr "Nenhuma transação neste período"+msgid "No unmapped accounts match a provider code"+msgstr "Nenhuma conta não mapeada corresponde a um código de provedor"++msgid "No unmapped values match a provider option name"+msgstr "Nenhum valor não mapeado corresponde a um nome de opção de provedor"+msgid "No value needed"msgstr "Nenhum valor necessário"@@ -9803,6 +10020,9 @@ msgstr "Não há trabalhos suficientes para cobrir a quantidade"msgid "Not reached"msgstr "Não atingido"+msgid "Not recorded"+msgstr "Não registrado"+msgid "Not referenced anywhere yet."msgstr "Não referenciado em lugar nenhum ainda."@@ -9891,6 +10111,9 @@ msgstr "OEM (fabricante de equipamento original)"msgid "of"msgstr "de"+msgid "Off — handled outside the sync"+msgstr "Desativado — tratado fora da sincronização"+msgid "Off — released revisions stay editable"msgstr "Desativado — revisões lançadas permanecem editáveis"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "Guia de Remessa"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "Preencha os valores com os lugares decimais da moeda, para que 300 apareça como 300.00 e as colunas de números permaneçam alinhadas. Desative isso para mostrar apenas os dígitos significativos. Documentos impressos e valores armazenados não são afetados."msgid "Page"msgstr "Página"@@ -10418,6 +10641,12 @@ msgstr "Unidade de Armazenamento Pai"msgid "Pareto by Type"msgstr "Pareto por Tipo"+msgid "Park as error"+msgstr "Estacionar como erro"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Estacione o diário com um aviso até que o valor seja mapeado"+msgid "part"msgstr "peças"@@ -10478,6 +10707,9 @@ msgstr "Taxa de Pagamento"msgid "Payables"msgstr "Contas a Pagar (padrão)"+msgid "Payables (AP)"+msgstr "Contas a Pagar (AP)"+msgid "Payables (default)"msgstr "prazo de pagamento"@@ -10574,6 +10806,9 @@ msgstr "Fechamento de período"msgid "Period End"msgstr "Fim do Período"+msgid "Period lock policy"+msgstr "Política de bloqueio de período"+msgid "Periodic depreciation expense for fixed assets"msgstr "A coleta oferece entidades rastreadas na ordem de vencimento mais próximo primeiro, então o estoque que vence mais cedo sai primeiro por padrão."@@ -10613,6 +10848,9 @@ msgstr "Impressoras físicas disponíveis para atribuição."msgid "Pick"msgstr "Selecionar"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Escolha uma dimensão Carbon e o alvo do provedor ao qual ela publica. Auto-create adiciona opções de provedor ausentes por nome no momento do push."+msgid "Pick a column to sort by"msgstr "Escolha uma coluna para ordenar"@@ -10834,6 +11072,9 @@ msgstr "Postado por"msgid "Posted By"msgstr "Postado Por"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "Os diários lançados com esses tipos de origem sempre sincronizam. O resumo diário agrupa os diários de um dia em uma única entrada do provedor por conta."+msgid "Posted once, corrected {corrections} times."msgstr "Lançado uma vez, corrigido {corrections} vezes."@@ -11124,6 +11365,12 @@ msgstr "Propriedades"msgid "Property"msgstr "Propriedade"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Correspondências propostas onde o número da conta Carbon é exatamente igual ao código de conta do provedor."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Correspondências propostas onde o nome do valor da dimensão Carbon é exatamente igual a um nome de opção de provedor."+msgid "Protect the go-live date"msgstr "Proteja a data de ativação"@@ -11133,6 +11380,15 @@ msgstr "Proteja o tempo de treinamento e participe"msgid "Provide process knowledge and inputs"msgstr "Forneça conhecimento do processo e entradas"+msgid "Provider"+msgstr "Provedor"++msgid "Provider account"+msgstr "Conta do provedor"++msgid "Provider option"+msgstr "Opção de provedor"+msgid "Public"msgstr "Público"@@ -11146,9 +11402,15 @@ msgstr "Publicar versão {0}?"msgid "Published by Carbon"msgstr "Publicado pela Carbon"+msgid "Pull"+msgstr "Puxar"+msgid "Pull From"msgstr "Puxar De"+msgid "Pull from accounting"+msgstr "Puxar da contabilidade"+msgid "Pull from Inventory"msgstr "Retirar do Inventário"@@ -11272,9 +11534,21 @@ msgstr "Faturas de Compra"msgid "Purchasing Unit of Measure"msgstr "Unidade de Medida de Compra"+msgid "Push"+msgstr "Empurrar"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "Redatá-lo para o primeiro dia aberto, mantendo a data original na narração."+msgid "Push record changes to external systems the moment they happen."msgstr "Envie alterações de registros para sistemas externos no momento em que ocorrem."+msgid "Push the journal without the dimension"+msgstr "Enviar o diário sem a dimensão"++msgid "Push to accounting"+msgstr "Enviar para contabilidade"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "Código QR para criar um {0} para este kanban"@@ -11481,9 +11755,15 @@ msgstr "Matérias-Primas"msgid "Raw Materials (default)"msgstr "Matérias-Primas (padrão)"+msgid "Re-date to first open day"+msgstr "Re-datar para o primeiro dia aberto"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Re-digitação entre orçamento, chão de fábrica e finanças"+msgid "Re-send"+msgstr "Re-enviar"+msgid "Reactivate"msgstr "Reativar"@@ -11505,6 +11785,9 @@ msgstr "ID legível com revisão"msgid "Reading the document..."msgstr "Lendo o documento..."+msgid "Ready"+msgstr "Pronto"+msgid "Ready for Quote"msgstr "Pronto para Cotação"@@ -11577,6 +11860,9 @@ msgstr "Recebimentos, remessas, faturas de vendas, faturas de compra, pagamentosmsgid "Receivables"msgstr "Contas a Receber (padrão)"+msgid "Receivables (AR)"+msgstr "Contas a Receber (AR)"+msgid "Receivables (default)"msgstr "Reconciliação de um pedido de compra com o que foi recebido e faturado — implícito em Carbon, através das quantidades de linha e saldo GR/IR."@@ -11635,6 +11921,9 @@ msgstr "Criado Recentemente"msgid "Reconcile"msgstr "Reconciliar"+msgid "Reconciliation found discrepancies with the provider"+msgstr "A reconciliação encontrou discrepâncias com o provedor"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Período de Recuperação"@@ -11813,6 +12102,9 @@ msgstr "Remover linha"msgid "Remove slide"msgstr "Remover slide"+msgid "Remove slot"+msgstr "Remover slot"+msgid "Remove sort by column"msgstr "Remover ordenação por coluna"@@ -12047,6 +12339,9 @@ msgstr "Retirar um ativo de serviço por sucateamento ou venda, registrando qualmsgid "Retry"msgstr "Tentar novamente"+msgid "Retry all"+msgstr "Tentar tudo novamente"+msgid "Return Home"msgstr "Voltar para Início"@@ -12098,6 +12393,9 @@ msgstr "Revise as alterações de cada item e confirme — liberar não pode sermsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Revise o balanço patrimonial e demonstração de resultado do período e confirme se os valores parecem corretos. Esta é uma aprovação manual — marque como concluído depois de tê-los revisado."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Revise as correspondências sugeridas antes de aplicar. Estas são uma melhor aproximação — confirme que cada uma está correta."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Revise os avisos abaixo, depois poste a contagem para aplicar os ajustes."@@ -12153,6 +12451,9 @@ msgstr "Número de RFQ"msgid "RFQs"msgstr "RFQs"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Leve as dimensões Carbon junto nos diários enviados. Cada slot mapeia uma dimensão Carbon para um alvo de análise do provedor; o mapeamento de valor abaixo emparelha valores de dimensão individuais com opções de provedor."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Guardar aplicações"msgid "Save contacts"msgstr "Guardar contactos"+msgid "Save dimension settings"+msgstr "Salvar configurações de dimensão"+msgid "Save Method"msgstr "Salvar Método"@@ -12759,6 +13063,9 @@ msgstr "Selecionar tipos de cliente"msgid "Select customers"msgstr "Selecionar clientes"+msgid "Select dimension"+msgstr "Selecionar dimensão"+msgid "Select Employee"msgstr "Selecionar Funcionário"@@ -12795,6 +13102,15 @@ msgstr "Selecione método..."msgid "Select Printer"msgstr "Selecionar Impressora"+msgid "Select provider account"+msgstr "Selecionar conta do provedor"++msgid "Select provider target"+msgstr "Selecionar alvo do provedor"++msgid "Select provider value"+msgstr "Selecionar valor do provedor"+msgid "Select Quantities"msgstr "Selecionar Quantidades"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "Mostrar opções de sincronização"msgid "Show Trailing Zeros"-msgstr ""+msgstr "Mostrar Zeros Decimais"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "Exibindo em {parentCurrency}"msgid "Showing the first 500 lines"msgstr "Mostrando as primeiras 500 linhas"+msgid "Showing the newest 200 journals"+msgstr "Mostrando os 200 diários mais recentes"+msgid "Showing the top 1,000 groups by amount"msgstr "Mostrando os 1.000 grupos principais por valor"@@ -13383,6 +13702,9 @@ msgstr "Lista de origem"msgid "Source Method"msgstr "Método de Origem"+msgid "Source types"+msgstr "Tipos de origem"+msgid "Source Version"msgstr "Versão de Origem"@@ -13721,6 +14043,15 @@ msgstr "Peça Sucessora"msgid "Suffix"msgstr "Sufixo"+msgid "Suggest mappings"+msgstr "Sugerir mapeamentos"++msgid "Suggest mappings with AI"+msgstr "Sugerir mapeamentos com IA"++msgid "Suggest with AI"+msgstr "Sugerir com IA"+msgid "Suggested orders you haven't placed yet."msgstr "Pedidos sugeridos que você ainda não realizou."@@ -13926,6 +14257,18 @@ msgstr "Alterar o tipo de funcionário aqui não altera suas permissões existenmsgid "Sync"msgstr "Sincronizar"+msgid "Sync Activity"+msgstr "Atividade de sincronização"++msgid "Sync operation"+msgstr "Operação de sincronização"++msgid "Sync Tie-Out"+msgstr "Sincronização de Reconciliação"++msgid "Synced"+msgstr "Sincronizado"+msgid "System"msgstr "Sistema"@@ -14599,6 +14942,9 @@ msgstr "O procedimento que os técnicos seguem quando essa manutenção é execumsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "Os processos que este centro de trabalho pode executar; aparece nos seletores de processo ao agendar operações e limita quais trabalhos podem rotear através deste centro de trabalho."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "O provedor não oferece alvos de dimensão. Habilite o recurso no provedor primeiro (por exemplo, categorias de rastreamento, rastreamento de classe ou campos)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Os pontos de ruptura de quantidade em que essa linha é precificada; cada coluna possui seu próprio preço por unidade para negociação comprador-fornecedor e conversão para documentos posteriores."@@ -15077,6 +15423,9 @@ msgstr "Quinta-feira"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Vincular remessas a uma fatura sem re-digitação"+msgid "Tie-out"+msgstr "Reconciliação"+msgid "Tie-Out"msgstr "Reconciliação"@@ -15533,9 +15882,18 @@ msgstr "Desassociar trabalho da ordem de venda?"msgid "Unlock"msgstr "Desbloquear"+msgid "Unmapped accounts"+msgstr "Contas não mapeadas"++msgid "Unmapped dimension values"+msgstr "Valores de dimensão não mapeados"+msgid "Unmapped Extracted Lines"msgstr "Linhas Extraídas Não Mapeadas"+msgid "Unmapped values"+msgstr "Valores não mapeados"+msgid "Unmatched"msgstr "Não correspondido"@@ -16077,6 +16435,9 @@ msgstr "Ver Sugestão"msgid "View Suppliers"msgstr "Ver Fornecedores"+msgid "View tie-out"+msgstr "Visualizar reconciliação"+msgid "View Traceability Graph"msgstr "Ver Gráfico de Rastreabilidade"@@ -16283,6 +16644,9 @@ msgstr "Que dados"msgid "What drove inventory up or down, by any dimension"msgstr "O que impulsionou o inventário para cima ou para baixo, por qualquer dimensão"+msgid "What happens when a journal is dated in a locked period."+msgstr "O que acontece quando um diário é datado em um período bloqueado."+msgid "What is {translatedTerm}?"msgstr "O que é {translatedTerm}?"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex d80bde0604..054ffc9df5 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "Поставщик — это компания или лицо, которое продает вам детали или услуги."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— последняя проверка {0}"+msgid ", {residual}% residual"msgstr ", {residual}% остаточная"@@ -56,6 +60,10 @@ msgstr "{0} счётов"msgid "{0} ago"msgstr "{0} назад"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} ячеек с разницами"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} клиентов с остатком"@@ -81,6 +89,15 @@ msgstr "{0} заданий создано"msgid "{0} lines to map"msgstr "{0} строк для сопоставления"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} из {1} счетов сопоставлено"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} из {maxSlots} слотов провайдера используется"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} заказов"@@ -101,6 +118,11 @@ msgstr "{0} поставщиков с остатком"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} необследованных объектов будут отпущены в статус Available. Проверенные успешные остаются Available, а проверенные отказы остаются Rejected."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} неотображенных счетов будут сопоставлены с {1} счетами поставщика."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} неопубликованных документов"@@ -109,6 +131,11 @@ msgstr "{0} неопубликованных документов"msgid "{0} uploaded successfully"msgstr "{0} успешно загружен"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} значений"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} значений отсутствует"@@ -134,6 +161,9 @@ msgstr "{done} из {total} этапов завершено"msgid "{from}–{to} of {count}"msgstr "{from}–{to} из {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} из {count} операций"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# строка} other {# строк}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}МБ максимум"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} месяцев с несовпадающими итогами"++msgid "{missingCount} journals missing in the provider"+msgstr "{missingCount} журналов отсутствуют в системе"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} отсутствующих журналов и {mismatchCount} месяцев с несовпадениями"+msgid "{name} deleted"msgstr "{name} удален"@@ -198,6 +237,9 @@ msgstr "↩ {0} перенаправлено из снятых с произвоmsgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Добавьте компонент поставщика</0> для этого товара, чтобы установить предпочтительного поставщика."+msgid "0 operations"+msgstr "0 операций"+msgid "0-4 weeks"msgstr "0-4 недели"@@ -813,6 +855,9 @@ msgstr "Менеджер счета"msgid "Account Manager"msgstr "Менеджер по работе с клиентами"+msgid "Account Mapping"+msgstr "Сопоставление счетов"+msgid "Account Number"msgstr "Номер счета"@@ -870,6 +915,9 @@ msgstr "Дебиторская задолженность"msgid "Accounts receivable for amounts owed by customers"msgstr "Дебиторская задолженность клиентов за задолженные суммы."+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Счета, на которые ссылаются стандартные значения проводок или история журналов, которые еще не имеют сопоставления с системой."+msgid "Accumulated Depreciation"msgstr "Накопленная амортизация"@@ -1128,6 +1176,9 @@ msgstr "Добавить отправку"msgid "Add Shipping"msgstr "Добавить доставку"+msgid "Add slot"+msgstr "Добавить слот"+msgid "Add Spare Part"msgstr "Добавить запасную часть"@@ -1219,6 +1270,9 @@ msgstr "Согласовать область охвата"msgid "Agree who owns what and set a working rhythm"msgstr "Согласуйте, кто за что отвечает, и установите рабочий ритм"+msgid "AI couldn't confidently match any accounts"+msgstr "ИИ не смог уверенно сопоставить ни один счет"+msgid "AI Tokens"msgstr "Токены ИИ"@@ -1228,6 +1282,10 @@ msgstr "Согласовать объем"msgid "All"msgstr "Все"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "Все {0} ячеек согласованы"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "Все {total} этапов завершены. Отличная работа — ваша команда готова к работе."@@ -1264,9 +1322,15 @@ msgstr "Все местоположения"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Все члены выбранных групп и выбранные лица смогут одобрять запросы"+msgid "All posting accounts are mapped"+msgstr "Все счета проводок сопоставлены"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "Все строки импортированы — {inserted} вставлено, {updated} обновлено."+msgid "All slotted dimension values are mapped"+msgstr "Все значения размерности слотов отображены"+msgid "All Suppliers"msgstr "Все поставщики"@@ -1464,6 +1528,9 @@ msgstr "Любой тип товара"msgid "Anything not explicitly listed in scope above"msgstr "Все, что не указано явно в области действия выше"+msgid "AP"+msgstr "КЗ"+msgid "AP Aging"msgstr "Анализ возраста кредиторской задолженности"@@ -1540,6 +1607,9 @@ msgstr "Применять правила ценообразования"msgid "Apply Rules On Top"msgstr "Применить правила выше"+msgid "Apply suggestions"+msgstr "Применить предложения"+msgid "Apply To"msgstr "Применить к"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "АПК (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "ДЗ"++msgid "AR / AP representation"+msgstr "Представление ДЗ/КЗ"+msgid "AR Aging"msgstr "Анализ возраста дебиторской задолженности"@@ -1594,6 +1670,9 @@ msgstr "Дебиторская задолженность"msgid "AR Overdue"msgstr "Просроченная дебиторская задолженность"+msgid "AR/AP"+msgstr "ДЗ/КЗ"+msgid "Archive"msgstr "Архив"@@ -2146,6 +2225,9 @@ msgstr "Вложение"msgid "Attachments"msgstr "Вложения"+msgid "Attempts"+msgstr "Попытки"+msgid "Attribute"msgstr "Атрибут"@@ -2194,6 +2276,9 @@ msgstr "Автоматический выпуск должен быть вклюmsgid "Auto Start Job"msgstr "Автоматический запуск задания"+msgid "Auto-create"+msgstr "Автоматическое создание"+msgid "Auto-generated QR Code"msgstr "Автоматически созданный QR-код"@@ -2440,6 +2525,9 @@ msgstr "Забронировать звонок с Carbon"msgid "Book Depreciation"msgstr "Амортизация по книге"+msgid "Books lock date (manual)"+msgstr "Дата блокировки книг (вручную)"+msgid "Both"msgstr "Оба"@@ -2671,6 +2759,9 @@ msgstr "Углерод"msgid "Carbon + you"msgstr "Carbon + вы"+msgid "Carbon account"+msgstr "Счет Carbon"+msgid "Carbon client is not available"msgstr "Клиент Carbon недоступен"@@ -2695,9 +2786,19 @@ msgstr "Логотип Carbon"msgid "Carbon only"msgstr "Только Carbon"+msgid "Carbon Posted"+msgstr "Carbon проведен"++msgid "Carbon value"+msgstr "Значение Carbon"+msgid "Carbon Value"msgstr "Значение Carbon"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon будет использовать ИИ для подбора счета поставщика для каждого из ваших {0} неотображенных счетов. Предложения — это отправная точка — вы можете проверить их перед сохранением."+msgid "Carbon-only"msgstr "Только для Carbon"@@ -3112,6 +3213,13 @@ msgstr "Штрихкод завершения"msgid "Completion Time"msgstr "Время завершения"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "вычислено {0}"++msgid "Computed At"+msgstr "Вычислено в"+msgid "Condensed P&L with margins and key subtotals"msgstr "Сокращенный П&У с прибыльностью и ключевыми итогами"@@ -3209,6 +3317,9 @@ msgstr "Подтвердить {0}"msgid "Confirm & release"msgstr "Подтвердить и выпустить"+msgid "Confirm all"+msgstr "Подтвердить все"+msgid "Confirm and sign the scope"msgstr "Подтвердите и подпишите объем работ"@@ -3661,6 +3772,9 @@ msgstr "Не удалось загрузить документы"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Не удалось загрузить связанные документы. Обновите страницу перед созданием нового, чтобы избежать дублирования."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "Не удалось загрузить цели размерности провайдера — проверьте соединение и перезагрузите страницу."+msgid "Couldn't reschedule the job. Please try again."msgstr "Не удалось перепланировать задание. Пожалуйста, попробуйте еще раз."@@ -4210,6 +4324,9 @@ msgstr "Ежедневно"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Ежедневные встречи, пока ваша команда осваивается в живой системе"+msgid "Daily summary"+msgstr "Ежедневный отчет"+msgid "Daily Usage"msgstr "Ежедневное использование"@@ -4926,6 +5043,12 @@ msgstr "измерение"msgid "Dimension"msgstr "Размер"+msgid "Dimension slots"+msgstr "Слоты размерности"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Значения размерности в опубликованных журналах, которые еще не имеют отображения провайдера."+msgid "dimensions"msgstr "измерения"@@ -5026,6 +5149,9 @@ msgstr "Решения"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "Вы хотите перезаписать текущие разрешения пользователя разрешениями по умолчанию для этого типа сотрудника?"+msgid "Doc-Backed"+msgstr "Обеспечено документом"+msgid "Docs"msgstr "Документы"@@ -5050,6 +5176,9 @@ msgstr "Документ:"msgid "Documents"msgstr "Документы"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Documents отправляет счета-фактуры, счета и платежи в виде родных документов поставщика; их журналы записываются как покрытые документом. Он также получает платежи, записанные в поставщик, обратно в Carbon, закрывая соответствующую счет-фактуру или счет и публикуя журнал GL Carbon. Off записывает их как намеренно исключенные."+msgid "Don't Cancel"msgstr "Не отменять"@@ -5975,6 +6104,12 @@ msgstr "Сертификат освобождения"msgid "Exemption Reason"msgstr "Причина освобождения"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Существующие сопоставления. Выберите другой счет системы для переассоциации."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Существующие отображения. Выберите другой вариант провайдера для переотображения."+msgid "Expand"msgstr "Развернуть"@@ -6111,9 +6246,15 @@ msgstr "Расширенная цена"msgid "External"msgstr "Внешние"+msgid "External Delta"+msgstr "Внешняя разница"+msgid "External document"msgstr "Внешний документ"+msgid "External ID"+msgstr "Внешний идентификатор"+msgid "External link"msgstr "Внешняя ссылка"@@ -6830,6 +6971,9 @@ msgstr "Сгенерированные ID отключены"msgid "Generated IDs are enabled"msgstr "Сгенерированные ID включены"+msgid "Generating suggestions…"+msgstr "Создание предложений…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Запустить Carbon: одна система для котировок, закупок, производственного цеха, управления запасами и финансов, заменяющая текущие инструменты."@@ -7113,6 +7257,9 @@ msgstr "Исторический курс (Капитал)"msgid "History"msgstr "История"+msgid "Hold the journal as a warning to fix."+msgstr "Удержать журнал как предупреждение для исправления."+msgid "Holiday"msgstr "Праздник"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "Идеи, предложения или проблемы?"+msgid "Idempotency key"+msgstr "Ключ идемпотентности"+msgid "Identifiers"msgstr "Идентификаторы"@@ -7549,6 +7699,9 @@ msgstr "Инструкции"msgid "Instructions are inherited from the procedure."msgstr "Инструкции наследуются из процедуры."+msgid "Integration"+msgstr "Интеграция"+msgid "Integration not found"msgstr "Интеграция не найдена"@@ -7585,6 +7738,9 @@ msgstr "Процентный доход или расход от банковсmsgid "Internal"msgstr "Внутренние"+msgid "Internal Delta"+msgstr "Внутренняя разница"+msgid "Internal notes"msgstr "Внутренние заметки"@@ -7967,6 +8123,9 @@ msgstr "Записи в журнале, датированные в этом пmsgid "Journal Entry"msgstr "Запись в журнале"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "Журналы с датой в указанный день или раньше считаются заблокированными. Объединяются с датой блокировки, сообщаемой системой, когда обе существуют."+msgid "Just one"msgstr "Только один"@@ -8067,6 +8226,12 @@ msgstr "Язык"msgid "Last 6 Months"msgstr "Последние 6 месяцев"+msgid "Last attempt"+msgstr "Последняя попытка"++msgid "Last Attempt"+msgstr "Последняя попытка"+msgid "Last Calibration"msgstr "Последняя калибровка"@@ -8558,6 +8723,12 @@ msgstr "Номер детали производителя"msgid "Manufacturing"msgstr "Производство"+msgid "Map accounts"+msgstr "Сопоставить счета"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Сопоставьте счета Carbon с планом счетов системы. Проводимые журналы отправляются, используя сопоставленный код счета системы."+msgid "Map Extracted Invoice Lines"msgstr "Сопоставить извлеченные строки счета"@@ -8570,6 +8741,12 @@ msgstr "Сопоставить строки сейчас"msgid "Map your current process, systems, and data"msgstr "Сопоставьте ваш текущий процесс, системы и данные"+msgid "Mapped accounts"+msgstr "Сопоставленные счета"++msgid "Mapped values"+msgstr "Отображенные значения"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "Отметить \"{0}\" как пройденный?"@@ -8640,6 +8817,12 @@ msgstr "Совпадает с любым"msgid "Match any (OR)"msgstr "Совпадать с любым (ИЛИ)"+msgid "Match by code"+msgstr "Совпадение по коду"++msgid "Match by name"+msgstr "Совпадение по имени"+msgid "Match none"msgstr "Не совпадает ни одно"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Сообщение"+msgid "Metadata"+msgstr "Метаданные"+msgid "Method"msgstr "Метод"@@ -8856,6 +9042,12 @@ msgstr "Минуты/1000 Деталей"msgid "Minutes/Piece"msgstr "Минут/Деталь"+msgid "Mismatch"+msgstr "Несовпадение"++msgid "Missing"+msgstr "Отсутствует"+msgid "Missing Information"msgstr "Отсутствует информация"@@ -9372,6 +9564,10 @@ msgstr "Нет"msgid "No {0} found"msgstr "Не найдено {0}"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "Нет операций синхронизации {0}"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "Пока нет {0}"@@ -9382,6 +9578,9 @@ msgstr "Нет добавленных навыков"msgid "No Access"msgstr "Нет доступа"+msgid "No accounts mapped yet"+msgstr "Счета еще не сопоставлены"+msgid "No action needed"msgstr "Никаких действий не требуется"@@ -9470,6 +9669,12 @@ msgstr "Нет запланированных выходных"msgid "No default attachments yet."msgstr "Пока нет вложений по умолчанию."+msgid "No dimension slots configured"+msgstr "Нет настроенных слотов размерности"++msgid "No dimension values mapped yet"+msgstr "Значения размерности еще не отображены"+msgid "No draft make method for this item yet."msgstr "Пока нет чернового метода производства для этого элемента."@@ -9635,6 +9840,9 @@ msgstr "Платежей пока нет."msgid "No planning data"msgstr "Нет данных планирования"+msgid "No posted journals in this period for this account"+msgstr "Нет проведенных журналов в этом периоде для этого счета"+msgid "No pricing for selected quantity"msgstr "Нет цен для выбранного количества"@@ -9716,6 +9924,9 @@ msgstr "Нет единицы хранения"msgid "No suppliers yet"msgstr "Поставщиков еще нет"+msgid "No sync operations yet"+msgstr "Операции синхронизации еще не выполнены"+msgid "No time entries for this week"msgstr "Нет записей о времени на эту неделю"@@ -9728,6 +9939,12 @@ msgstr "Нет инструментов для этого шага"msgid "No transactions in this period"msgstr "Нет транзакций в этом периоде"+msgid "No unmapped accounts match a provider code"+msgstr "Ни один несопоставленный счет не совпадает с кодом системы"++msgid "No unmapped values match a provider option name"+msgstr "Никакие неотображенные значения не совпадают с названием параметра провайдера"+msgid "No value needed"msgstr "Значение не требуется"@@ -9803,6 +10020,9 @@ msgstr "Недостаточно заданий для покрытия колиmsgid "Not reached"msgstr "Не достигнуто"+msgid "Not recorded"+msgstr "Не записано"+msgid "Not referenced anywhere yet."msgstr "Пока не на что-либо ссылается."@@ -9891,6 +10111,9 @@ msgstr "OEM (производитель оригинального оборудmsgid "of"msgstr "из"+msgid "Off — handled outside the sync"+msgstr "Отключено — обработано вне синхронизации"+msgid "Off — released revisions stay editable"msgstr "Выключено — выпущенные версии остаются редактируемыми"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "Упаковочный лист"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "Дополняйте суммы нулями в соответствии с количеством десятичных знаков валюты, чтобы 300 отображалось как 300.00 и столбцы цифр оставались выровненными. Отключите эту опцию, чтобы показать только значащие цифры. Печатные документы и сохраненные суммы не затрагиваются в любом случае."msgid "Page"msgstr "Страница"@@ -10418,6 +10641,12 @@ msgstr "Родительское хранилище"msgid "Pareto by Type"msgstr "Парето по типам"+msgid "Park as error"+msgstr "Припарковать как ошибку"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Припаркуйте журнал с предупреждением до отображения значения"+msgid "part"msgstr "детали"@@ -10478,6 +10707,9 @@ msgstr "Курс платежа"msgid "Payables"msgstr "Кредиторская задолженность (по умолчанию)"+msgid "Payables (AP)"+msgstr "Кредиторская задолженность (КЗ)"+msgid "Payables (default)"msgstr "условие платежа"@@ -10574,6 +10806,9 @@ msgstr "Закрытие периода"msgid "Period End"msgstr "Конец периода"+msgid "Period lock policy"+msgstr "Политика блокировки периода"+msgid "Periodic depreciation expense for fixed assets"msgstr "Комплектация предлагает отслеживаемые сущности в порядке самого раннего истечения сначала, поэтому запас, истекающий в первую очередь, по умолчанию выходит первым."@@ -10613,6 +10848,9 @@ msgstr "Физические принтеры, доступные для назmsgid "Pick"msgstr "Выбрать"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Выберите размерность Carbon и цель провайдера, на которую она отправляется. Автоматическое создание добавляет отсутствующие параметры провайдера по имени во время отправки."+msgid "Pick a column to sort by"msgstr "Выберите столбец для сортировки"@@ -10834,6 +11072,9 @@ msgstr "Опубликовано"msgid "Posted By"msgstr "Опубликовано"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "Опубликованные журналы с этими типами источников всегда синхронизируются. Ежедневная сводка группирует журналы дня в одну запись поставщика для каждого счета."+msgid "Posted once, corrected {corrections} times."msgstr "Опубликовано один раз, исправлено {corrections} раз(а)."@@ -11124,6 +11365,12 @@ msgstr "Свойства"msgid "Property"msgstr "Свойство"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Предложенные совпадения, где номер счета Carbon точно совпадает с кодом счета системы."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Предложенные совпадения, где имя значения размерности Carbon точно соответствует имени параметра провайдера."+msgid "Protect the go-live date"msgstr "Защитите дату запуска"@@ -11133,6 +11380,15 @@ msgstr "Защитите время обучения и участвуйте"msgid "Provide process knowledge and inputs"msgstr "Предоставить знания о процессе и входные данные"+msgid "Provider"+msgstr "Система"++msgid "Provider account"+msgstr "Счет провайдера"++msgid "Provider option"+msgstr "Параметр провайдера"+msgid "Public"msgstr "Публичный"@@ -11146,9 +11402,15 @@ msgstr "Опубликовать версию {0}?"msgid "Published by Carbon"msgstr "Опубликовано Carbon"+msgid "Pull"+msgstr "Получить"+msgid "Pull From"msgstr "Извлечь из"+msgid "Pull from accounting"+msgstr "Получить из учета"+msgid "Pull from Inventory"msgstr "Извлечение из инвентаря"@@ -11272,9 +11534,21 @@ msgstr "Счета на покупку"msgid "Purchasing Unit of Measure"msgstr "Единица измерения закупки"+msgid "Push"+msgstr "Отправить"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "Переместить его с переустановленной датой на первый открытый день, сохраняя исходную дату в примечании."+msgid "Push record changes to external systems the moment they happen."msgstr "Отправляйте изменения записей во внешние системы в момент их возникновения."+msgid "Push the journal without the dimension"+msgstr "Отправить журнал без размерности"++msgid "Push to accounting"+msgstr "Отправить в учет"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "QR-код для создания {0} для этого канбана"@@ -11481,9 +11755,15 @@ msgstr "Сырьё и материалы"msgid "Raw Materials (default)"msgstr "Сырьё и материалы (по умолчанию)"+msgid "Re-date to first open day"+msgstr "Перенести дату на первый открытый день"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Повторный ввод данных между расчётом, цехом и финансами"+msgid "Re-send"+msgstr "Отправить снова"+msgid "Reactivate"msgstr "Переактивировать"@@ -11505,6 +11785,9 @@ msgstr "Читаемый идентификатор с редакцией"msgid "Reading the document..."msgstr "Чтение документа..."+msgid "Ready"+msgstr "Готово"+msgid "Ready for Quote"msgstr "Готово к предложению"@@ -11577,6 +11860,9 @@ msgstr "Приёмки, отгрузки, счета-фактуры продажmsgid "Receivables"msgstr "Дебиторская задолженность (по умолчанию)"+msgid "Receivables (AR)"+msgstr "Дебиторская задолженность (ДЗ)"+msgid "Receivables (default)"msgstr "Сверка заказа на покупку с полученным и выставленным счетом — неявно в Carbon через количество строк и остаток GR/IR."@@ -11635,6 +11921,9 @@ msgstr "Недавно созданные"msgid "Reconcile"msgstr "Согласовать"+msgid "Reconciliation found discrepancies with the provider"+msgstr "Сверка обнаружила расхождения с поставщиком"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Период восстановления"@@ -11813,6 +12102,9 @@ msgstr "Удалить строку"msgid "Remove slide"msgstr "Удалить слайд"+msgid "Remove slot"+msgstr "Удалить слот"+msgid "Remove sort by column"msgstr "Удалить сортировку по столбцу"@@ -12047,6 +12339,9 @@ msgstr "Вывод основного средства из эксплуатацmsgid "Retry"msgstr "Повторить"+msgid "Retry all"+msgstr "Повторить все"+msgid "Return Home"msgstr "Вернуться на главную"@@ -12098,6 +12393,9 @@ msgstr "Просмотрите изменения каждого элементmsgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Проверьте балансовый лист и отчёт о прибылях и убытках за период и подтвердите, что цифры выглядят правильно. Это ручное утверждение — отметьте как завершённое после их проверки."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Проверьте предложенные совпадения перед применением. Это лучшее предположение — подтвердите, что каждое из них верно."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Просмотрите предупреждения ниже, а затем опубликуйте подсчет для применения корректировок."@@ -12153,6 +12451,9 @@ msgstr "Номер РФП"msgid "RFQs"msgstr "РФЗ"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Передайте размерности Carbon вместе с отправленными журналами. Каждый слот отображает одну размерность Carbon в одну цель аналитики провайдера; приведенное ниже отображение значений связывает отдельные значения размерности с параметрами провайдера."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Сохранить применения"msgid "Save contacts"msgstr "Сохранить контакты"+msgid "Save dimension settings"+msgstr "Сохранить настройки размерности"+msgid "Save Method"msgstr "Сохранить метод"@@ -12759,6 +13063,9 @@ msgstr "Выберите типы клиентов"msgid "Select customers"msgstr "Выберите клиентов"+msgid "Select dimension"+msgstr "Выбрать размерность"+msgid "Select Employee"msgstr "Выберите сотрудника"@@ -12795,6 +13102,15 @@ msgstr "Выберите метод..."msgid "Select Printer"msgstr "Выберите принтер"+msgid "Select provider account"+msgstr "Выбрать счет провайдера"++msgid "Select provider target"+msgstr "Выбрать цель провайдера"++msgid "Select provider value"+msgstr "Выбрать значение провайдера"+msgid "Select Quantities"msgstr "Выберите количества"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "Показать параметры синхронизации"msgid "Show Trailing Zeros"-msgstr ""+msgstr "Показывать завершающие нули"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "Отображение в {parentCurrency}"msgid "Showing the first 500 lines"msgstr "Показано первые 500 строк"+msgid "Showing the newest 200 journals"+msgstr "Показываются последние 200 журналов"+msgid "Showing the top 1,000 groups by amount"msgstr "Показано топ 1000 групп по сумме"@@ -13383,6 +13702,9 @@ msgstr "Список источников"msgid "Source Method"msgstr "Исходный метод"+msgid "Source types"+msgstr "Типы источников"+msgid "Source Version"msgstr "Исходная версия"@@ -13721,6 +14043,15 @@ msgstr "Часть-преемник"msgid "Suffix"msgstr "Суффикс"+msgid "Suggest mappings"+msgstr "Предложить сопоставления"++msgid "Suggest mappings with AI"+msgstr "Предложить сопоставления с помощью ИИ"++msgid "Suggest with AI"+msgstr "Предложить с помощью ИИ"+msgid "Suggested orders you haven't placed yet."msgstr "Предложенные заказы, которые вы еще не разместили."@@ -13926,6 +14257,18 @@ msgstr "Изменение типа сотрудника здесь не измmsgid "Sync"msgstr "Синхронизация"+msgid "Sync Activity"+msgstr "Активность синхронизации"++msgid "Sync operation"+msgstr "Операция синхронизации"++msgid "Sync Tie-Out"+msgstr "Проверка синхронизации"++msgid "Synced"+msgstr "Синхронизировано"+msgid "System"msgstr "Система"@@ -14599,6 +14942,9 @@ msgstr "Процедура, которой следуют техники приmsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "Процессы, которые может выполнять этот рабочий центр; отображается в селекторах процессов при планировании операций и ограничивает, какие задания могут маршрутизироваться через этот рабочий центр."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "Провайдер не предлагает цели размерности. Сначала включите функцию в провайдере (например, категории отслеживания, отслеживание класса или поля)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Точки разрыва количества, по которым эта строка оценивается; каждый столбец имеет собственную цену за единицу для переговоров между покупателем и поставщиком и для преобразования в нижние документы."@@ -15077,6 +15423,9 @@ msgstr "Четверг"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Связать отправки с счетом без повторного ввода данных"+msgid "Tie-out"+msgstr "Согласование"+msgid "Tie-Out"msgstr "Сверка"@@ -15533,9 +15882,18 @@ msgstr "Отменить связь задания с заказом на проmsgid "Unlock"msgstr "Разблокировать"+msgid "Unmapped accounts"+msgstr "Несопоставленные счета"++msgid "Unmapped dimension values"+msgstr "Неотображенные значения размерности"+msgid "Unmapped Extracted Lines"msgstr "Неотображённые извлечённые строки"+msgid "Unmapped values"+msgstr "Неотображенные значения"+msgid "Unmatched"msgstr "Несопоставленный"@@ -16077,6 +16435,9 @@ msgstr "Просмотр предложения"msgid "View Suppliers"msgstr "Просмотр поставщиков"+msgid "View tie-out"+msgstr "Просмотр согласования"+msgid "View Traceability Graph"msgstr "Просмотр графика отслеживания"@@ -16283,6 +16644,9 @@ msgstr "Какие данные"msgid "What drove inventory up or down, by any dimension"msgstr "Что повлияло на инвентаризацию вверх или вниз, по любому измерению"+msgid "What happens when a journal is dated in a locked period."+msgstr "Что происходит, когда журнал датирован в закрытом периоде."+msgid "What is {translatedTerm}?"msgstr "Что такое {translatedTerm}?"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex bd4b177971..811a590725 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "Bir tedarikçi, size parça veya hizmet satan bir işletme veya kişidir."+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— son kontrol {0}"+msgid ", {residual}% residual"msgstr ", {residual}% kalıntı"@@ -56,6 +60,10 @@ msgstr "{0} hesaplar"msgid "{0} ago"msgstr "{0} önce"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} deltaları olan hücreler"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0} müşteri bakiye ile"@@ -81,6 +89,15 @@ msgstr "{0} iş oluşturuldu"msgid "{0} lines to map"msgstr "{0} satır eşlenecek"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} / {1} deftere nakil hesapları eşlendi"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0}/{maxSlots} sağlayıcı yuvası kullanıldı"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} sipariş"@@ -101,6 +118,11 @@ msgstr "{0} bakiyesi olan tedarikçi"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} örneklenmemiş varlıklar Kullanılabilir'e bırakılacaktır. Örneklenen başarılılar Kullanılabilir ve örneklenen başarısızlar Reddedilmiş olarak kalır."+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} eşleştirilmemiş hesap, {1} sağlayıcı hesabı ile eşleştirilecektir."+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} deftere geçmemiş belge"@@ -109,6 +131,11 @@ msgstr "{0} deftere geçmemiş belge"msgid "{0} uploaded successfully"msgstr "{0} başarıyla yüklendi"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} değer"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} değeri eksik"@@ -134,6 +161,9 @@ msgstr "{done} / {total} aşama tamamlandı"msgid "{from}–{to} of {count}"msgstr "{from}–{to} / {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} / {count} işlem"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# satır} other {# satırlar}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB sınırı"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} ay tutarları uyuşmazlığı"++msgid "{missingCount} journals missing in the provider"+msgstr "sağlayıcıda eksik {missingCount} yevmiye"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} eksik yevmiye ve {mismatchCount} tutarları uyuşmazlığı olan ay"+msgid "{name} deleted"msgstr "{name} silindi"@@ -198,6 +237,9 @@ msgstr "↩ {0} eski hale getirilen {1} kaynağından yönlendirildi"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>Bu ürün için bir tedarikçi parçası ekleyin</0> tercih edilen tedarikçi ayarlamak için."+msgid "0 operations"+msgstr "0 işlem"+msgid "0-4 weeks"msgstr "0-4 hafta"@@ -813,6 +855,9 @@ msgstr "Hesap yöneticisi"msgid "Account Manager"msgstr "Hesap Yöneticisi"+msgid "Account Mapping"+msgstr "Hesap Haritalama"+msgid "Account Number"msgstr "Hesap Numarası"@@ -870,6 +915,9 @@ msgstr "Alacak hesapları"msgid "Accounts receivable for amounts owed by customers"msgstr "Müşteriler tarafından borçlu olunan tutarlar için alacak hesapları."+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "Deftere nakil varsayılanları veya yevmiye geçmişi tarafından referans verilen ancak henüz sağlayıcı haritalaması olmayan hesaplar."+msgid "Accumulated Depreciation"msgstr "Birikmiş amortisman"@@ -1128,6 +1176,9 @@ msgstr "Sevkiyat Ekle"msgid "Add Shipping"msgstr "Nakliye Ekle"+msgid "Add slot"+msgstr "Yuva ekle"+msgid "Add Spare Part"msgstr "Yedek Parça Ekle"@@ -1219,6 +1270,9 @@ msgstr "Kapsamda anlaş"msgid "Agree who owns what and set a working rhythm"msgstr "Kimin neyi sahip olduğunu belirleyin ve çalışma ritmi oluşturun"+msgid "AI couldn't confidently match any accounts"+msgstr "Yapay Zeka herhangi bir hesapı emin bir şekilde eşleştiremedi"+msgid "AI Tokens"msgstr "Yapay Zeka Jetonları"@@ -1228,6 +1282,10 @@ msgstr "Kapsamda Hizala"msgid "All"msgstr "Tümü"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "Tüm {0} hücre uyumluyor"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "Tüm {total} aşama tamamlandı. Harika iş — ekibiniz çalışmaya başladı."@@ -1264,9 +1322,15 @@ msgstr "Tüm Konumlar"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Seçilen gruplardaki ve bireylerdeki tüm üyeler talepleri onaylayabilecektir"+msgid "All posting accounts are mapped"+msgstr "Tüm deftere nakil hesapları haritalanmış"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "{inserted} eklendi, {updated} güncellendi — tüm satırlar içe aktarıldı."+msgid "All slotted dimension values are mapped"+msgstr "Tüm boyut değerleri eşlendi"+msgid "All Suppliers"msgstr "Tüm Tedarikçiler"@@ -1464,6 +1528,9 @@ msgstr "Herhangi bir ürün tipi"msgid "Anything not explicitly listed in scope above"msgstr "Yukarıda açıkça kapsamda listelenmemiş herhangi bir şey"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "AP Yaşlandırma"@@ -1540,6 +1607,9 @@ msgstr "Fiyatlandırma kurallarını uygula"msgid "Apply Rules On Top"msgstr "Kuralları üste uygula"+msgid "Apply suggestions"+msgstr "Önerileri Uygula"+msgid "Apply To"msgstr "Uygulanacak Alan"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "AR / AP gösterimi"+msgid "AR Aging"msgstr "AR Yaşlandırma"@@ -1594,6 +1670,9 @@ msgstr "AR Ödenmemiş"msgid "AR Overdue"msgstr "AR Vadesi Geçmiş"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "Arşiv"@@ -2146,6 +2225,9 @@ msgstr "Ek"msgid "Attachments"msgstr "Ekler"+msgid "Attempts"+msgstr "Denemeler"+msgid "Attribute"msgstr "Öznitelik"@@ -2194,6 +2276,9 @@ msgstr "Bir işi otomatik olarak başlatmak için Otomatik Serbest Bırakma etkimsgid "Auto Start Job"msgstr "Otomatik İş Başlatma"+msgid "Auto-create"+msgstr "Otomatik oluştur"+msgid "Auto-generated QR Code"msgstr "Otomatik oluşturulan QR kodu"@@ -2440,6 +2525,9 @@ msgstr "Carbon ile bir çağrı ayarlayın"msgid "Book Depreciation"msgstr "Defter Amortismanı"+msgid "Books lock date (manual)"+msgstr "Defterlerin kilitlenme tarihi (manuel)"+msgid "Both"msgstr "Her ikisi"@@ -2671,6 +2759,9 @@ msgstr "Karbon"msgid "Carbon + you"msgstr "Carbon + siz"+msgid "Carbon account"+msgstr "Carbon hesabı"+msgid "Carbon client is not available"msgstr "Carbon istemcisi mevcut değil"@@ -2695,9 +2786,19 @@ msgstr "Carbon Logosu"msgid "Carbon only"msgstr "Yalnızca Carbon"+msgid "Carbon Posted"+msgstr "Carbon Kaydedildi"++msgid "Carbon value"+msgstr "Carbon değeri"+msgid "Carbon Value"msgstr "Carbon Değeri"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon, {0} eşleştirilmemiş hesabınızın her biri için bir sağlayıcı hesabını tahmin etmek için Yapay Zeka kullanacaktır. Öneriler başlangıç noktasıdır — herhangi bir şey kaydedilmeden önce bunları gözden geçirebilirsiniz."+msgid "Carbon-only"msgstr "Yalnızca Carbon"@@ -3112,6 +3213,13 @@ msgstr "Tamamlama Barkodu"msgid "Completion Time"msgstr "Tamamlama Süresi"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "hesaplanan {0}"++msgid "Computed At"+msgstr "Hesaplama Tarihi"+msgid "Condensed P&L with margins and key subtotals"msgstr "Marjlar ve kilit alt toplamlarla sıkıştırılmış P&L"@@ -3209,6 +3317,9 @@ msgstr "Onayla {0}"msgid "Confirm & release"msgstr "Onayla ve yayınla"+msgid "Confirm all"+msgstr "Tümünü onayla"+msgid "Confirm and sign the scope"msgstr "Kapsamı onaylayın ve imzalayın"@@ -3661,6 +3772,9 @@ msgstr "Belgeler yüklenemedi"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "İlgili belgeler yüklenemedi. Yeni bir tane oluşturmadan önce yenileyerek tekrarları önleyin."+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "Sağlayıcının boyut hedefleri yüklenemedi — bağlantıyı kontrol edin ve sayfayı yeniden yükleyin."+msgid "Couldn't reschedule the job. Please try again."msgstr "İş yeniden planlanamadı. Lütfen tekrar deneyin."@@ -4210,6 +4324,9 @@ msgstr "Günlük"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "Canlı sistemde ekibiniz ayağa kalkarken günlük kontrol toplantıları"+msgid "Daily summary"+msgstr "Günlük özet"+msgid "Daily Usage"msgstr "Günlük Kullanım"@@ -4926,6 +5043,12 @@ msgstr "boyut"msgid "Dimension"msgstr "Boyut"+msgid "Dimension slots"+msgstr "Boyut yuvaları"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "Henüz sağlayıcı eşlemesi olmayan defterlerdeki boyut değerleri."+msgid "dimensions"msgstr "boyutlar"@@ -5026,6 +5149,9 @@ msgstr "Durumlar"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "Kullanıcının mevcut izinlerini bu çalışan türü için varsayılan izinlerle üzerine yazmak ister misiniz?"+msgid "Doc-Backed"+msgstr "Belge Destekli"+msgid "Docs"msgstr "Belgeler"@@ -5050,6 +5176,9 @@ msgstr "Belge:"msgid "Documents"msgstr "Belgeler"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "Documents faturaları, muhasebe faturalarını ve ödemeleri sağlayıcı belgesi olarak gönderir; muhasebe kayıtları belge tarafından kapsandığı şekilde kaydedilir. Ayrıca sağlayıcıda kaydedilen ödemeleri Carbon'a geri çekerek, eşleşen fatura veya muhasebe faturasını kapatır ve bir Carbon GL muhasebe kaydı oluşturur. Kapalı, bunları kasıtlı olarak hariç tutulmuş olarak kaydeder."+msgid "Don't Cancel"msgstr "İptal Etme"@@ -5975,6 +6104,12 @@ msgstr "İstisnai Sertifika"msgid "Exemption Reason"msgstr "İstisnai Nedeni"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "Mevcut haritalamalar. Yeniden haritalamak için farklı bir sağlayıcı hesabı seçin."++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "Mevcut eşlemeler. Yeniden eşlemek için farklı bir sağlayıcı seçeneği seçin."+msgid "Expand"msgstr "Genişlet"@@ -6111,9 +6246,15 @@ msgstr "Genelletilmiş Fiyat"msgid "External"msgstr "Harici"+msgid "External Delta"+msgstr "Harici Fark"+msgid "External document"msgstr "Harici belge"+msgid "External ID"+msgstr "Harici Kimlik"+msgid "External link"msgstr "Harici bağlantı"@@ -6830,6 +6971,9 @@ msgstr "Oluşturulan kimlikler devre dışı"msgid "Generated IDs are enabled"msgstr "Oluşturulan Kimlikler etkinleştirilmiş"+msgid "Generating suggestions…"+msgstr "Öneriler oluşturuluyor…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "Carbon'da canlı yayına geçin: alıntı alma, satın alma, atölye tabanı, envanter ve finansmanı çalıştıran ve mevcut araçları değiştiren tek bir sistem."@@ -7113,6 +7257,9 @@ msgstr "Tarihi Oran (Öz Sermaye)"msgid "History"msgstr "Geçmiş"+msgid "Hold the journal as a warning to fix."+msgstr "Günlüğü uyarı olarak tut ve düzelt."+msgid "Holiday"msgstr "Tatil"@@ -7281,6 +7428,9 @@ msgstr "Kimlik"msgid "Ideas, suggestions or problems?"msgstr "Fikirler, öneriler veya sorunlar?"+msgid "Idempotency key"+msgstr "İdempotentlik Anahtarı"+msgid "Identifiers"msgstr "Tanımlayıcılar"@@ -7549,6 +7699,9 @@ msgstr "Talimatlar"msgid "Instructions are inherited from the procedure."msgstr "Talimatlar prosedürden miras alınır."+msgid "Integration"+msgstr "Entegrasyon"+msgid "Integration not found"msgstr "Entegrasyon bulunamadı"@@ -7585,6 +7738,9 @@ msgstr "Bankacılık faaliyetlerinden faiz geliri veya gideri"msgid "Internal"msgstr "Dahili"+msgid "Internal Delta"+msgstr "Dahili Fark"+msgid "Internal notes"msgstr "İç notlar"@@ -7967,6 +8123,9 @@ msgstr "Bu dönemde tarihli ve hâlâ Taslak durumunda olan muhasebe kayıtlarımsgid "Journal Entry"msgstr "Muhasebe Kaydı"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "Bu tarih veya öncesine tarihlenmiş yevmiyeler kilitli olarak kabul edilir. Her ikisi de mevcut olduğunda sağlayıcı tarafından bildirilen kilitlenme tarihi ile birleştirilir."+msgid "Just one"msgstr "Sadece bir"@@ -8067,6 +8226,12 @@ msgstr "Dil"msgid "Last 6 Months"msgstr "Son 6 Ay"+msgid "Last attempt"+msgstr "Son deneme"++msgid "Last Attempt"+msgstr "Son Deneme"+msgid "Last Calibration"msgstr "Son Kalibrasyon"@@ -8558,6 +8723,12 @@ msgstr "Üretici Parça Numarası"msgid "Manufacturing"msgstr "Üretim"+msgid "Map accounts"+msgstr "Hesapları Eşle"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "Carbon hesaplarını sağlayıcının hesap planına haritalayın. Deftere nakledilen yevmiyeler, haritalanan sağlayıcı hesap kodunu kullanarak gönderilir."+msgid "Map Extracted Invoice Lines"msgstr "Çıkarılan Fatura Satırlarını Eşle"@@ -8570,6 +8741,12 @@ msgstr "Satırları Şimdi Eşle"msgid "Map your current process, systems, and data"msgstr "Mevcut sürecinizi, sistemlerinizi ve verilerinizi eşleyin"+msgid "Mapped accounts"+msgstr "Haritalanan hesaplar"++msgid "Mapped values"+msgstr "Eşlenen değerler"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "\"{0}\" olarak işaretlensin mi?"@@ -8640,6 +8817,12 @@ msgstr "Herhangi birine uyacak"msgid "Match any (OR)"msgstr "Herhangi bir eşleşme (VEYA)"+msgid "Match by code"+msgstr "Koda göre eşleştir"++msgid "Match by name"+msgstr "Ada göre eşleştir"+msgid "Match none"msgstr "Hiçbiriyle eşleşme"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "Mesaj"+msgid "Metadata"+msgstr "Meta Veri"+msgid "Method"msgstr "Yöntem"@@ -8856,6 +9042,12 @@ msgstr "Dakika/1000 Parça"msgid "Minutes/Piece"msgstr "Dakika/Adet"+msgid "Mismatch"+msgstr "Uyuşmazlık"++msgid "Missing"+msgstr "Eksik"+msgid "Missing Information"msgstr "Eksik Bilgi"@@ -9372,6 +9564,10 @@ msgstr "Hayır"msgid "No {0} found"msgstr "Hiç {0} bulunamadı"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "{0} eşitleme işlemi yok"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "Henüz {0} yok"@@ -9382,6 +9578,9 @@ msgstr "Ek yetenek eklenmedi"msgid "No Access"msgstr "Erişim Yok"+msgid "No accounts mapped yet"+msgstr "Henüz hiçbir hesap haritalanmamış"+msgid "No action needed"msgstr "Yapılacak işlem yok"@@ -9470,6 +9669,12 @@ msgstr "Planlanmış izin yok"msgid "No default attachments yet."msgstr "Henüz varsayılan ek dosya yok."+msgid "No dimension slots configured"+msgstr "Yapılandırılmış boyut yuvası yok"++msgid "No dimension values mapped yet"+msgstr "Henüz hiçbir boyut değeri eşlenmedi"+msgid "No draft make method for this item yet."msgstr "Bu öğe için henüz taslak yapım yöntemi yok."@@ -9635,6 +9840,9 @@ msgstr "Henüz ödeme yok."msgid "No planning data"msgstr "Planlama verisi yok"+msgid "No posted journals in this period for this account"+msgstr "Bu dönem için bu hesapta hiçbir muhasebe kaydı yayınlanmadı"+msgid "No pricing for selected quantity"msgstr "Seçilen miktar için fiyat yok"@@ -9716,6 +9924,9 @@ msgstr "Depolama birimi yok"msgid "No suppliers yet"msgstr "Henüz tedarikçi yok"+msgid "No sync operations yet"+msgstr "Henüz hiçbir eşitleme işlemi yok"+msgid "No time entries for this week"msgstr "Bu hafta için zaman girişi yok"@@ -9728,6 +9939,12 @@ msgstr "Bu adım için araç yok"msgid "No transactions in this period"msgstr "Bu dönemde işlem yok"+msgid "No unmapped accounts match a provider code"+msgstr "Haritalanmamış hesaplar sağlayıcı kodundan herhangi biriyle uyuşmıyor"++msgid "No unmapped values match a provider option name"+msgstr "Eşlenmemiş değerler hiçbir sağlayıcı seçeneğinin adıyla eşleşmiyor"+msgid "No value needed"msgstr "Değer gerekmiyor"@@ -9803,6 +10020,9 @@ msgstr "Miktarı karşılayacak yeterli iş yok"msgid "Not reached"msgstr "Ulaşılmadı"+msgid "Not recorded"+msgstr "Kaydedilmedi"+msgid "Not referenced anywhere yet."msgstr "Henüz hiçbir yerde referans verilmemiş."@@ -9891,6 +10111,9 @@ msgstr "OEM (Orijinal Ekipman Üreticisi)"msgid "of"msgstr "adet"+msgid "Off — handled outside the sync"+msgstr "Kapalı — senkronizasyon dışında işlenir"+msgid "Off — released revisions stay editable"msgstr "Kapalı — yayınlanan revizyonlar düzenlenebilir kalır"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "Paketleme Fişi"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "Miktarları para biriminin ondalık basamaklarına göre doldur, böylece 300, 300.00 olarak görünür ve sayı sütunları hizalı kalır. Yalnızca değer taşıyan rakamları göstermek için bunu kapatın. Yazdırılan belgeler ve depolanan miktarlar her iki durumda da etkilenmez."msgid "Page"msgstr "Sayfa"@@ -10418,6 +10641,12 @@ msgstr "Üst Depolama Birimi"msgid "Pareto by Type"msgstr "Tür Tipine Göre Pareto"+msgid "Park as error"+msgstr "Hata olarak kaydet"++msgid "Park the journal with a warning until the value is mapped"+msgstr "Değer eşlenene kadar defterin uyarıyla beklet"+msgid "part"msgstr "parçalar"@@ -10478,6 +10707,9 @@ msgstr "Ödeme Oranı"msgid "Payables"msgstr "Ödenecek Hesaplar (varsayılan)"+msgid "Payables (AP)"+msgstr "Ödenecek Hesaplar (AP)"+msgid "Payables (default)"msgstr "ödeme terimi"@@ -10574,6 +10806,9 @@ msgstr "Dönem Kapanışı"msgid "Period End"msgstr "Dönem Sonu"+msgid "Period lock policy"+msgstr "Dönem kilit politikası"+msgid "Periodic depreciation expense for fixed assets"msgstr "Toplama, izlenen varlıkları en erken son kullanma tarihine göre sunar, bu nedenle en erken son kullanma tarihine sahip stok varsayılan olarak ilk olarak çıkar."@@ -10613,6 +10848,9 @@ msgstr "Atama için kullanılabilecek fiziksel yazıcılar."msgid "Pick"msgstr "Topla"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "Bir Carbon boyutu ve gönderdiği sağlayıcı hedefini seçin. Otomatik oluştur, gönderim sırasında eksik sağlayıcı seçeneklerini ada göre ekler."+msgid "Pick a column to sort by"msgstr "Sıralamak için bir sütun seçin"@@ -10834,6 +11072,9 @@ msgstr "Yayınlayan"msgid "Posted By"msgstr "Gönderen"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "Bu kaynak türlerine sahip nakledilen yevmiye defterleri her zaman senkronize olur. Günlük özet, bir günün yevmiye defteri kayıtlarını sağlayıcı hesabı başına bir girişe gruplandırır."+msgid "Posted once, corrected {corrections} times."msgstr "Bir kez deftere kaydedildi, {corrections} kez düzeltildi."@@ -11124,6 +11365,12 @@ msgstr "Özellikler"msgid "Property"msgstr "Özellik"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "Carbon hesap numarasının sağlayıcı hesap koduyla tam olarak eşleştiği önerilen eşleşmeler."++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "Carbon boyut değerinin adı sağlayıcı seçeneğinin adıyla tamamen eşleştiği önerilen eşlemeler."+msgid "Protect the go-live date"msgstr "Go-live tarihini koruyun"@@ -11133,6 +11380,15 @@ msgstr "Eğitim zamanını koru ve katıl"msgid "Provide process knowledge and inputs"msgstr "Süreç bilgisi ve girdileri sağlayın"+msgid "Provider"+msgstr "Sağlayıcı"++msgid "Provider account"+msgstr "Sağlayıcı hesabı"++msgid "Provider option"+msgstr "Sağlayıcı seçeneği"+msgid "Public"msgstr "Herkese açık"@@ -11146,9 +11402,15 @@ msgstr "Sürüm {0} yayınlanmış mı?"msgid "Published by Carbon"msgstr "Carbon tarafından yayınlandı"+msgid "Pull"+msgstr "Çek"+msgid "Pull From"msgstr "Çekme Kaynağından"+msgid "Pull from accounting"+msgstr "Muhasebeden çek"+msgid "Pull from Inventory"msgstr "Stoktan Çek"@@ -11272,9 +11534,21 @@ msgstr "Satın Alma Faturaları"msgid "Purchasing Unit of Measure"msgstr "Satın Alma Birimi"+msgid "Push"+msgstr "Gönder"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "İlk açık güne yeniden tarihlendir, orijinal tarihi açıklamada tut."+msgid "Push record changes to external systems the moment they happen."msgstr "Kayıt değişikliklerini gerçekleştiği anda harici sistemlere gönderin."+msgid "Push the journal without the dimension"+msgstr "Boyutu olmadan defterin gönder"++msgid "Push to accounting"+msgstr "Muhasebede gönder"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "Bu kanban için bir {0} oluşturmak için QR Kod"@@ -11481,9 +11755,15 @@ msgstr "Ham Maddeler"msgid "Raw Materials (default)"msgstr "Ham Maddeler (varsayılan)"+msgid "Re-date to first open day"+msgstr "İlk açık güne yeniden tarihlendir"+msgid "Re-keying between quoting, the floor, and finance"msgstr "Tekliflendirme, üretim ve muhasebe arasında veri yeniden girişi"+msgid "Re-send"+msgstr "Yeniden gönder"+msgid "Reactivate"msgstr "Yeniden etkinleştir"@@ -11505,6 +11785,9 @@ msgstr "Revizyon içeren okunabilir kimlik"msgid "Reading the document..."msgstr "Belge okunuyor..."+msgid "Ready"+msgstr "Hazır"+msgid "Ready for Quote"msgstr "Teklif İçin Hazır"@@ -11577,6 +11860,9 @@ msgstr "Hâlâ Taslak veya Bekleme durumunda olan makbuzlar, sevkiyatlar, satımsgid "Receivables"msgstr "Alacak Hesapları (varsayılan)"+msgid "Receivables (AR)"+msgstr "Alacak Hesapları (AR)"+msgid "Receivables (default)"msgstr "Bir satın alma siparişini alınan ve faturalandırılan tutarla uzlaştırma — Carbon'da kapalı, satır miktarları ve GR/IR bakiyesi aracılığıyla."@@ -11635,6 +11921,9 @@ msgstr "Son Oluşturulanlar"msgid "Reconcile"msgstr "Uzlaştır"+msgid "Reconciliation found discrepancies with the provider"+msgstr "Mutabakat sağlayıcıyla tutarsızlıklar buldu"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "Geri Kazanım Süresi"@@ -11813,6 +12102,9 @@ msgstr "Satırı kaldır"msgid "Remove slide"msgstr "Slaytı kaldır"+msgid "Remove slot"+msgstr "Yuva kaldır"+msgid "Remove sort by column"msgstr "Sıralamayı kaldır"@@ -12047,6 +12339,9 @@ msgstr "Bir varlığı hurdaya ayırarak veya satarak hizmetten çekmek; net defmsgid "Retry"msgstr "Tekrar Dene"+msgid "Retry all"+msgstr "Tümünü yeniden dene"+msgid "Return Home"msgstr "Ana Sayfaya Dön"@@ -12098,6 +12393,9 @@ msgstr "Her ürünün değişikliklerini gözden geçirin, sonra onaylayın —msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "Dönemin bilançosunu ve gelir tablosunu gözden geçirin ve rakamların doğru göründüğünü doğrulayın. Bu manuel bir onay — bunları gözden geçirdikten sonra bitti olarak işaretleyin."+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "Uygulamadan önce önerilen eşleşmeleri gözden geçirin. Bunlar en iyi tahmindir — her birini onaylayın."+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "Aşağıdaki uyarıları gözden geçirin, ardından ayarlamaları uygulamak için sayımı gönderin."@@ -12153,6 +12451,9 @@ msgstr "Teklif Numarası"msgid "RFQs"msgstr "Teklif Talepleri"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "Carbon boyutlarını gönderilen defterlerle birlikte taşıyın. Her yuva bir Carbon boyutunu bir sağlayıcı analitik hedefine eşler; aşağıdaki değer eşlemesi bireysel boyut değerlerini sağlayıcı seçenekleriyle eşleştirir."+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "Uygulamaları kaydet"msgid "Save contacts"msgstr "Kişileri kaydet"+msgid "Save dimension settings"+msgstr "Boyut ayarlarını kaydet"+msgid "Save Method"msgstr "Yöntemi Kaydet"@@ -12759,6 +13063,9 @@ msgstr "Müşteri türü seçin"msgid "Select customers"msgstr "Müşterileri seçin"+msgid "Select dimension"+msgstr "Boyut seç"+msgid "Select Employee"msgstr "Çalışan Seç"@@ -12795,6 +13102,15 @@ msgstr "Yöntem seçin..."msgid "Select Printer"msgstr "Yazıcı Seçin"+msgid "Select provider account"+msgstr "Sağlayıcı hesabı seç"++msgid "Select provider target"+msgstr "Sağlayıcı hedefini seç"++msgid "Select provider value"+msgstr "Sağlayıcı değerini seç"+msgid "Select Quantities"msgstr "Miktarları Seçin"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "Senkronizasyon seçeneklerini göster"msgid "Show Trailing Zeros"-msgstr ""+msgstr "Sondaki Sıfırları Göster"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "{parentCurrency} cinsinden gösteriliyor"msgid "Showing the first 500 lines"msgstr "İlk 500 satır gösteriliyor"+msgid "Showing the newest 200 journals"+msgstr "En yeni 200 muhasebe kaydı gösteriliyor"+msgid "Showing the top 1,000 groups by amount"msgstr "Miktar açısından ilk 1.000 grup gösteriliyor"@@ -13383,6 +13702,9 @@ msgstr "Kaynak listesi"msgid "Source Method"msgstr "Kaynak Yöntem"+msgid "Source types"+msgstr "Kaynak türleri"+msgid "Source Version"msgstr "Kaynak Sürüm"@@ -13721,6 +14043,15 @@ msgstr "Halef Parça"msgid "Suffix"msgstr "Sonek"+msgid "Suggest mappings"+msgstr "Eşlemeleri Öner"++msgid "Suggest mappings with AI"+msgstr "Yapay Zeka ile Eşlemeleri Öner"++msgid "Suggest with AI"+msgstr "Yapay Zeka ile Öner"+msgid "Suggested orders you haven't placed yet."msgstr "Henüz yerleştirmediğiniz önerilen siparişler."@@ -13926,6 +14257,18 @@ msgstr "Çalışan türünü burada değiştirmek mevcut izinlerini değiştirmemsgid "Sync"msgstr "Senkronize Et"+msgid "Sync Activity"+msgstr "Senkronizasyon Etkinliği"++msgid "Sync operation"+msgstr "Senkronizasyon işlemi"++msgid "Sync Tie-Out"+msgstr "Senkronizasyon Uyumu"++msgid "Synced"+msgstr "Eşitlendi"+msgid "System"msgstr "Sistem"@@ -14599,6 +14942,9 @@ msgstr "Teknikerin bu bakım gerçekleştirildiğinde izlediği prosedür; kronomsgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "Bu iş merkezinin çalıştırabileceği süreçler; işlem planlanırken işlem seçicilerinde görünür ve hangi işlerin bu iş merkezi aracılığıyla yönlendirilebileceğini sınırlar."+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "Sağlayıcı boyut hedefleri sunmaz. Önce sağlayıcıda özelliği etkinleştirin (örneğin, izleme kategorileri, sınıf izleme veya alanlar)."+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Bu satırın fiyatlandırıldığı miktar kırılım noktaları; her sütun, alıcı-tedarikçi müzakere ve aşağı akış belgelere dönüştürme için kendi birim fiyatını taşır."@@ -15077,6 +15423,9 @@ msgstr "Perşembe"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Sevkiyatları faturaya bağlayın, yeniden veri girişi olmadan"+msgid "Tie-out"+msgstr "Uyum"+msgid "Tie-Out"msgstr "Mutabakat Kontrolü"@@ -15533,9 +15882,18 @@ msgstr "İş emrini satış siparişinden ayır?"msgid "Unlock"msgstr "Kilidi Aç"+msgid "Unmapped accounts"+msgstr "Eşleştirilmemiş hesaplar"++msgid "Unmapped dimension values"+msgstr "Eşlenmemiş boyut değerleri"+msgid "Unmapped Extracted Lines"msgstr "Eşlenmemiş Çıkarılan Satırlar"+msgid "Unmapped values"+msgstr "Eşlenmemiş değerler"+msgid "Unmatched"msgstr "Eşleşmemiş"@@ -16077,6 +16435,9 @@ msgstr "Öneri Görüntüle"msgid "View Suppliers"msgstr "Tedarikçileri Görüntüle"+msgid "View tie-out"+msgstr "Uyumu Görüntüle"+msgid "View Traceability Graph"msgstr "İzlenebilirlik Grafiğini Görüntüle"@@ -16283,6 +16644,9 @@ msgstr "Hangi veri"msgid "What drove inventory up or down, by any dimension"msgstr "Envanterin yükselmesine veya düşmesine neyin sebep olduğu, herhangi bir boyuta göre"+msgid "What happens when a journal is dated in a locked period."+msgstr "Kilitli bir dönemde günlüğe tarih atanırsa ne olur?"+msgid "What is {translatedTerm}?"msgstr "{translatedTerm} nedir?"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 90da12d161..f8d212ddbd 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -15,6 +15,10 @@ msgstr ""msgid " A supplier is a business or person who sells you parts or services."msgstr "供应商是向您销售零件或服务的企业或个人。"+#. placeholder {0}: formatDateTime(lastReconciliation.runAt)+msgid "— last checked {0}"+msgstr "— 上次检查于 {0}"+msgid ", {residual}% residual"msgstr ", {residual}% 残差"@@ -56,6 +60,10 @@ msgstr "{0} 个账户"msgid "{0} ago"msgstr "{0} 前"+#. placeholder {0}: tieOut.deltaCellCount+msgid "{0} cells with deltas"+msgstr "{0} 个单元格有差异"+#. placeholder {0}: ar.countmsgid "{0} customers with a balance"msgstr "{0}个有余额的客户"@@ -81,6 +89,15 @@ msgstr "{0} 个作业已创建"msgid "{0} lines to map"msgstr "{0} 行待映射"+#. placeholder {0}: mappingReadiness.mapped+#. placeholder {1}: mappingReadiness.required+msgid "{0} of {1} posting accounts mapped"+msgstr "{0} / {1} 个过账科目已映射"++#. placeholder {0}: rows.length+msgid "{0} of {maxSlots} provider slots used"+msgstr "{0} / {maxSlots} 个提供商插槽已使用"+#. placeholder {0}: history.lengthmsgid "{0} orders"msgstr "{0} 个订单"@@ -101,6 +118,11 @@ msgstr "{0}个有余额的供应商"msgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} 个未采样的实体将被释放到可用状态。已采样的合格品保持可用状态,已采样的不合格品保持被拒绝状态。"+#. placeholder {0}: unmapped.length+#. placeholder {1}: chart.length+msgid "{0} unmapped accounts will be matched against {1} provider accounts."+msgstr "{0} 个未映射的账户将与 {1} 个提供商账户相匹配。"+#. placeholder {0}: task.autoCheck.countmsgid "{0} unposted documents"msgstr "{0} 份未过账单据"@@ -109,6 +131,11 @@ msgstr "{0} 份未过账单据"msgid "{0} uploaded successfully"msgstr "{0} 上传成功"+#. placeholder {0}: dimension.valueCount+#. placeholder {0}: selectedDimension?.valueCount+msgid "{0} values"+msgstr "{0} 个值"+#. placeholder {0}: unmatchedValues.lengthmsgid "{0} values missing"msgstr "{0} 个值缺失"@@ -134,6 +161,9 @@ msgstr "{done} 个,共 {total} 个阶段已完成"msgid "{from}–{to} of {count}"msgstr "{from}–{to} 共 {count}"+msgid "{from}–{to} of {count} operations"+msgstr "{from}–{to} / {count} 条操作"+#. placeholder {0}: errors.length#. placeholder {1}: skipped.lengthmsgid "{inserted} inserted, {updated} updated, {0} need fixing, {1} skipped."@@ -145,6 +175,15 @@ msgstr "{linesCount, plural, one {# 行} other {# 行}}"msgid "{maxSizeMB}MB limit"msgstr "{maxSizeMB}MB 限制"+msgid "{mismatchCount} months with mismatched totals"+msgstr "{mismatchCount} 个月的总额不匹配"++msgid "{missingCount} journals missing in the provider"+msgstr "提供商中缺少 {missingCount} 份日记账"++msgid "{missingCount} missing journals and {mismatchCount} mismatched months"+msgstr "{missingCount} 份缺失日记账和 {mismatchCount} 个月不匹配"+msgid "{name} deleted"msgstr "{name} 已删除"@@ -198,6 +237,9 @@ msgstr "↩ {0} 从已淘汰的 {1} 重定向"msgid "<0>Add a supplier part</0> for this item to set a preferred supplier."msgstr "<0>为此项目添加供应商零件</0>以设置首选供应商。"+msgid "0 operations"+msgstr "0 条操作"+msgid "0-4 weeks"msgstr "0-4 周"@@ -813,6 +855,9 @@ msgstr "账户经理"msgid "Account Manager"msgstr "账户经理"+msgid "Account Mapping"+msgstr "账户映射"+msgid "Account Number"msgstr "账户编号"@@ -870,6 +915,9 @@ msgstr "应收账款"msgid "Accounts receivable for amounts owed by customers"msgstr "客户应付金额的应收账款。"+msgid "Accounts referenced by posting defaults or journal history that have no provider mapping yet."+msgstr "由过账默认值或日记账历史记录引用但尚无提供商映射的账户。"+msgid "Accumulated Depreciation"msgstr "累计折旧"@@ -1128,6 +1176,9 @@ msgstr "添加发货"msgid "Add Shipping"msgstr "添加运费"+msgid "Add slot"+msgstr "添加插槽"+msgid "Add Spare Part"msgstr "添加备件"@@ -1219,6 +1270,9 @@ msgstr "就范围达成一致"msgid "Agree who owns what and set a working rhythm"msgstr "同意谁拥有什么并设定工作节奏"+msgid "AI couldn't confidently match any accounts"+msgstr "AI 无法自信地匹配任何账户"+msgid "AI Tokens"msgstr "AI 代币"@@ -1228,6 +1282,10 @@ msgstr "对齐范围"msgid "All"msgstr "全部"+#. placeholder {0}: tieOut.cellCount+msgid "All {0} cells tie out"+msgstr "全部 {0} 个单元格对账"+msgid "All {total} phases are done. Nice work — your team is up and running."msgstr "所有 {total} 个阶段已完成。做得很好——你的团队已启动并运行。"@@ -1264,9 +1322,15 @@ msgstr "所有位置"msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "所选组的所有成员和所选个人将能够批准请求"+msgid "All posting accounts are mapped"+msgstr "所有过账账户已映射"+msgid "All rows imported — {inserted} inserted, {updated} updated."msgstr "所有行已导入—{inserted}行插入,{updated}行更新。"+msgid "All slotted dimension values are mapped"+msgstr "所有分配维度的值都已映射"+msgid "All Suppliers"msgstr "所有供应商"@@ -1464,6 +1528,9 @@ msgstr "任何物品类型"msgid "Anything not explicitly listed in scope above"msgstr "未在上述范围内明确列出的任何内容"+msgid "AP"+msgstr "AP"+msgid "AP Aging"msgstr "应付账款账龄"@@ -1540,6 +1607,9 @@ msgstr "应用定价规则"msgid "Apply Rules On Top"msgstr "在顶部应用规则"+msgid "Apply suggestions"+msgstr "应用建议"+msgid "Apply To"msgstr "应用于"@@ -1582,6 +1652,12 @@ msgstr "AQL"msgid "AQL (Z1.4 / ISO 2859-1)"msgstr "AQL (Z1.4 / ISO 2859-1)"+msgid "AR"+msgstr "AR"++msgid "AR / AP representation"+msgstr "AR / AP 表示法"+msgid "AR Aging"msgstr "应收账款账龄"@@ -1594,6 +1670,9 @@ msgstr "应收账款未结"msgid "AR Overdue"msgstr "应收账款逾期"+msgid "AR/AP"+msgstr "AR/AP"+msgid "Archive"msgstr "存档"@@ -2146,6 +2225,9 @@ msgstr "附件"msgid "Attachments"msgstr "附件"+msgid "Attempts"+msgstr "尝试次数"+msgid "Attribute"msgstr "属性"@@ -2194,6 +2276,9 @@ msgstr "必须启用自动发布才能自动启动作业"msgid "Auto Start Job"msgstr "自动启动作业"+msgid "Auto-create"+msgstr "自动创建"+msgid "Auto-generated QR Code"msgstr "自动生成的二维码"@@ -2440,6 +2525,9 @@ msgstr "与 Carbon 预约通话"msgid "Book Depreciation"msgstr "账面折旧"+msgid "Books lock date (manual)"+msgstr "账册锁定日期(手动)"+msgid "Both"msgstr "两者"@@ -2671,6 +2759,9 @@ msgstr "Carbon"msgid "Carbon + you"msgstr "Carbon + 你"+msgid "Carbon account"+msgstr "Carbon 账户"+msgid "Carbon client is not available"msgstr "Carbon 客户端不可用"@@ -2695,9 +2786,19 @@ msgstr "Carbon 标志"msgid "Carbon only"msgstr "仅限 Carbon"+msgid "Carbon Posted"+msgstr "Carbon 已记账"++msgid "Carbon value"+msgstr "Carbon 值"+msgid "Carbon Value"msgstr "碳值"+#. placeholder {0}: unmapped.length+msgid "Carbon will use AI to guess a provider account for each of your {0} unmapped accounts. Suggestions are a starting point — you can review them before anything is saved."+msgstr "Carbon 将使用 AI 为您的每个 {0} 个未映射的账户猜测一个提供商账户。建议是一个起点 — 您可以在保存任何内容之前审查它们。"+msgid "Carbon-only"msgstr "仅限Carbon"@@ -3112,6 +3213,13 @@ msgstr "完成条码"msgid "Completion Time"msgstr "完成时间"+#. placeholder {0}: formatRelativeTime(tieOut.computedAt)+msgid "computed {0}"+msgstr "计算于 {0}"++msgid "Computed At"+msgstr "计算于"+msgid "Condensed P&L with margins and key subtotals"msgstr "精简损益表,含利润率和关键小计"@@ -3209,6 +3317,9 @@ msgstr "确认 {0}"msgid "Confirm & release"msgstr "确认并发布"+msgid "Confirm all"+msgstr "全部确认"+msgid "Confirm and sign the scope"msgstr "确认并签署范围"@@ -3661,6 +3772,9 @@ msgstr "无法加载文档"msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "无法加载相关文档。创建新文档前请先刷新以避免重复。"+msgid "Couldn't load the provider's dimension targets — check the connection and reload."+msgstr "无法加载提供商的维度目标 — 检查连接并重新加载。"+msgid "Couldn't reschedule the job. Please try again."msgstr "无法重新安排作业。请重试。"@@ -4210,6 +4324,9 @@ msgstr "每日"msgid "Daily check-ins while your team finds its feet on the live system"msgstr "每日检查,帮助您的团队在实时系统上站稳脚跟"+msgid "Daily summary"+msgstr "每日汇总"+msgid "Daily Usage"msgstr "日常使用"@@ -4926,6 +5043,12 @@ msgstr "维度"msgid "Dimension"msgstr "尺寸"+msgid "Dimension slots"+msgstr "维度插槽"++msgid "Dimension values on posted journals that have no provider mapping yet."+msgstr "已发布日记账上尚未映射到提供商的维度值。"+msgid "dimensions"msgstr "维度"@@ -5026,6 +5149,9 @@ msgstr "处置"msgid "Do you want to overwrite the user's current permissions with the default permissions for this employee type?"msgstr "您想用此员工类型的默认权限覆盖该用户的当前权限吗?"+msgid "Doc-Backed"+msgstr "文档支持"+msgid "Docs"msgstr "文档"@@ -5050,6 +5176,9 @@ msgstr "文档:"msgid "Documents"msgstr "文档"+msgid "Documents pushes invoices, bills and payments as native provider documents; their journals are recorded as covered by the document. It also pulls payments recorded in the provider back into Carbon, closing the matching invoice or bill and posting a Carbon GL journal. Off records them as deliberately excluded."+msgstr "文档将发票、账单和付款推送为原生提供商文档;其日记被记录为由文档覆盖。它还将在提供商中记录的付款拉回到Carbon,关闭匹配的发票或账单并发布Carbon GL日记。关闭时将其记录为故意排除。"+msgid "Don't Cancel"msgstr "不要取消"@@ -5975,6 +6104,12 @@ msgstr "豁免证书"msgid "Exemption Reason"msgstr "豁免原因"+msgid "Existing mappings. Pick a different provider account to re-map."+msgstr "现有映射。选择不同的提供商账户以重新映射。"++msgid "Existing mappings. Pick a different provider option to re-map."+msgstr "现有映射。选择不同的提供商选项以重新映射。"+msgid "Expand"msgstr "展开"@@ -6111,9 +6246,15 @@ msgstr "扩展价格"msgid "External"msgstr "外部"+msgid "External Delta"+msgstr "外部差异"+msgid "External document"msgstr "外部文档"+msgid "External ID"+msgstr "外部 ID"+msgid "External link"msgstr "外部链接"@@ -6830,6 +6971,9 @@ msgstr "生成的ID已禁用"msgid "Generated IDs are enabled"msgstr "生成的ID已启用"+msgid "Generating suggestions…"+msgstr "正在生成建议…"+msgid "Get live on Carbon: one system running quoting, purchasing, the shop floor, inventory, and finance, replacing the current tools."msgstr "在 Carbon 上线:一个系统运行报价、采购、车间、库存和财务,替代当前工具。"@@ -7113,6 +7257,9 @@ msgstr "历史汇率(权益)"msgid "History"msgstr "历史"+msgid "Hold the journal as a warning to fix."+msgstr "暂存该日记帐作为警告以供修复"+msgid "Holiday"msgstr "假期"@@ -7281,6 +7428,9 @@ msgstr "ID"msgid "Ideas, suggestions or problems?"msgstr "想法、建议或问题?"+msgid "Idempotency key"+msgstr "幂等键"+msgid "Identifiers"msgstr "标识符"@@ -7549,6 +7699,9 @@ msgstr "说明"msgid "Instructions are inherited from the procedure."msgstr "说明继承自工序。"+msgid "Integration"+msgstr "集成"+msgid "Integration not found"msgstr "集成未找到"@@ -7585,6 +7738,9 @@ msgstr "来自银行活动的利息收入或支出"msgid "Internal"msgstr "内部"+msgid "Internal Delta"+msgstr "内部差异"+msgid "Internal notes"msgstr "内部备注"@@ -7967,6 +8123,9 @@ msgstr "本期日期的日记账条目如仍为草稿状态,必须进行过账msgid "Journal Entry"msgstr "日记账条目"+msgid "Journals dated on or before this date are treated as locked. Merged with the provider-reported lock date when both exist."+msgstr "日期在此日期及之前的日记账被视为已锁定。当两者都存在时,与提供商报告的锁定日期合并。"+msgid "Just one"msgstr "仅一个"@@ -8067,6 +8226,12 @@ msgstr "语言"msgid "Last 6 Months"msgstr "最近6个月"+msgid "Last attempt"+msgstr "上次尝试"++msgid "Last Attempt"+msgstr "上次尝试"+msgid "Last Calibration"msgstr "最后校准"@@ -8558,6 +8723,12 @@ msgstr "制造商零件号"msgid "Manufacturing"msgstr "制造"+msgid "Map accounts"+msgstr "映射科目"++msgid "Map Carbon accounts to the provider's chart of accounts. Posted journals push using the mapped provider account code."+msgstr "将 Carbon 账户映射到提供商的科目表。已过账日记账使用映射的提供商账户代码推送。"+msgid "Map Extracted Invoice Lines"msgstr "映射提取的发票行项目"@@ -8570,6 +8741,12 @@ msgstr "立即映射行"msgid "Map your current process, systems, and data"msgstr "映射您当前的流程、系统和数据"+msgid "Mapped accounts"+msgstr "已映射账户"++msgid "Mapped values"+msgstr "已映射的值"+#. placeholder {0}: i18n._(step.gate)msgid "Mark \"{0}\" as passed?"msgstr "将\"{0}\"标记为已通过?"@@ -8640,6 +8817,12 @@ msgstr "匹配任意"msgid "Match any (OR)"msgstr "匹配任意项 (OR)"+msgid "Match by code"+msgstr "按代码匹配"++msgid "Match by name"+msgstr "按名称匹配"+msgid "Match none"msgstr "不匹配任何条件"@@ -8790,6 +8973,9 @@ msgstr "MES"msgid "Message"msgstr "消息"+msgid "Metadata"+msgstr "元数据"+msgid "Method"msgstr "方法"@@ -8856,6 +9042,12 @@ msgstr "分钟/1000件"msgid "Minutes/Piece"msgstr "分钟/件"+msgid "Mismatch"+msgstr "不匹配"++msgid "Missing"+msgstr "缺失"+msgid "Missing Information"msgstr "缺少信息"@@ -9372,6 +9564,10 @@ msgstr "否"msgid "No {0} found"msgstr "未找到 {0}"+#. placeholder {0}: status.toLowerCase()+msgid "No {0} sync operations"+msgstr "没有 {0} 同步操作"+#. placeholder {0}: copy.pluralNounmsgid "No {0} yet"msgstr "还没有{0}"@@ -9382,6 +9578,9 @@ msgstr "未添加任何能力"msgid "No Access"msgstr "无权限"+msgid "No accounts mapped yet"+msgstr "尚未映射账户"+msgid "No action needed"msgstr "无需操作"@@ -9470,6 +9669,12 @@ msgstr "未安排休息日"msgid "No default attachments yet."msgstr "还没有默认附件。"+msgid "No dimension slots configured"+msgstr "未配置维度插槽"++msgid "No dimension values mapped yet"+msgstr "尚未映射维度值"+msgid "No draft make method for this item yet."msgstr "此项目还没有草稿制造方法。"@@ -9635,6 +9840,9 @@ msgstr "还没有付款。"msgid "No planning data"msgstr "没有规划数据"+msgid "No posted journals in this period for this account"+msgstr "此期间此账户没有已记账日记账"+msgid "No pricing for selected quantity"msgstr "所选数量无定价"@@ -9716,6 +9924,9 @@ msgstr "无存储单元"msgid "No suppliers yet"msgstr "还没有供应商"+msgid "No sync operations yet"+msgstr "尚无同步操作"+msgid "No time entries for this week"msgstr "本周没有时间条目"@@ -9728,6 +9939,12 @@ msgstr "此步骤没有工具"msgid "No transactions in this period"msgstr "此期间无交易"+msgid "No unmapped accounts match a provider code"+msgstr "没有未映射的账户与提供商代码匹配"++msgid "No unmapped values match a provider option name"+msgstr "没有未映射的值与提供商选项名称匹配"+msgid "No value needed"msgstr "不需要值"@@ -9803,6 +10020,9 @@ msgstr "工作数量不足以覆盖数量"msgid "Not reached"msgstr "未到达"+msgid "Not recorded"+msgstr "未记录"+msgid "Not referenced anywhere yet."msgstr "还没有在任何地方被引用。"@@ -9891,6 +10111,9 @@ msgstr "OEM (原始设备制造商)"msgid "of"msgstr "的"+msgid "Off — handled outside the sync"+msgstr "关闭 — 在同步外处理"+msgid "Off — released revisions stay editable"msgstr "关闭 — 已发布的版本保持可编辑"@@ -10371,7 +10594,7 @@ msgid "Packing Slip"msgstr "装箱单"msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."-msgstr ""+msgstr "将金额填充到其货币的小数位数,使300显示为300.00,数字列保持对齐。关闭此选项可仅显示有效数字。打印文档和存储的金额无论如何都不受影响。"msgid "Page"msgstr "页面"@@ -10418,6 +10641,12 @@ msgstr "父存储单元"msgid "Pareto by Type"msgstr "按类型的帕累托"+msgid "Park as error"+msgstr "停靠为错误"++msgid "Park the journal with a warning until the value is mapped"+msgstr "将日记账停放,并显示警告,直到该值被映射"+msgid "part"msgstr "零件"@@ -10478,6 +10707,9 @@ msgstr "支付汇率"msgid "Payables"msgstr "应付账款(默认)"+msgid "Payables (AP)"+msgstr "应付账款 (AP)"+msgid "Payables (default)"msgstr "付款条件"@@ -10574,6 +10806,9 @@ msgstr "期间关闭"msgid "Period End"msgstr "期末"+msgid "Period lock policy"+msgstr "期间锁定政策"+msgid "Periodic depreciation expense for fixed assets"msgstr "拣选按最早过期日期优先提供跟踪实体,因此最快过期的库存默认首先出库。"@@ -10613,6 +10848,9 @@ msgstr "可用于分配的物理打印机。"msgid "Pick"msgstr "拣选"+msgid "Pick a Carbon dimension and the provider target it posts to. Auto-create adds missing provider options by name at push time."+msgstr "选择一个 Carbon 维度和它发布到的提供商目标。自动创建在推送时按名称添加缺失的提供商选项。"+msgid "Pick a column to sort by"msgstr "选择要排序的列"@@ -10834,6 +11072,9 @@ msgstr "发布者"msgid "Posted By"msgstr "发布者"+msgid "Posted journals with these source types always sync. Daily summary groups a day's journals into one provider entry per account."+msgstr "这些来源类型的已过账日记账始终进行同步。每日汇总将一天的日记账合并为每个账户的一条提供商记录。"+msgid "Posted once, corrected {corrections} times."msgstr "发布一次,修正了 {corrections} 次。"@@ -11124,6 +11365,12 @@ msgstr "属性"msgid "Property"msgstr "属性"+msgid "Proposed matches where the Carbon account number equals the provider account code exactly."+msgstr "提议的匹配项,其中 Carbon 账户编号与提供商账户代码完全相等。"++msgid "Proposed matches where the Carbon dimension value's name equals a provider option name exactly."+msgstr "建议的匹配,其中 Carbon 维度值的名称与提供商选项名称完全相同。"+msgid "Protect the go-live date"msgstr "保护上线日期"@@ -11133,6 +11380,15 @@ msgstr "保护培训时间并参加"msgid "Provide process knowledge and inputs"msgstr "提供流程知识和输入"+msgid "Provider"+msgstr "提供商"++msgid "Provider account"+msgstr "提供商账户"++msgid "Provider option"+msgstr "提供商选项"+msgid "Public"msgstr "公开"@@ -11146,9 +11402,15 @@ msgstr "发布版本{0}?"msgid "Published by Carbon"msgstr "由 Carbon 发布"+msgid "Pull"+msgstr "拉取"+msgid "Pull From"msgstr "从以下位置提取"+msgid "Pull from accounting"+msgstr "从会计系统拉取"+msgid "Pull from Inventory"msgstr "从库存中提取"@@ -11272,9 +11534,21 @@ msgstr "采购发票"msgid "Purchasing Unit of Measure"msgstr "采购计量单位"+msgid "Push"+msgstr "推送"++msgid "Push it re-dated to the first open day, keeping the original date in the narration."+msgstr "将其推送至第一个可用日期,在备注中保留原始日期"+msgid "Push record changes to external systems the moment they happen."msgstr "将记录更改实时推送到外部系统。"+msgid "Push the journal without the dimension"+msgstr "推送不包含维度的日记账"++msgid "Push to accounting"+msgstr "推送到会计系统"+#. placeholder {0}: row.original.replenishmentSystem === "Make" ? "Job" : "Order"msgid "QR Code to create a {0} for this kanban"msgstr "二维码以为此看板创建{0}"@@ -11481,9 +11755,15 @@ msgstr "原材料"msgid "Raw Materials (default)"msgstr "原材料(默认)"+msgid "Re-date to first open day"+msgstr "重新日期至第一个开放日"+msgid "Re-keying between quoting, the floor, and finance"msgstr "在报价、车间和财务之间重复输入数据"+msgid "Re-send"+msgstr "重新发送"+msgid "Reactivate"msgstr "重新激活"@@ -11505,6 +11785,9 @@ msgstr "可读 ID(含版本)"msgid "Reading the document..."msgstr "正在读取文档..."+msgid "Ready"+msgstr "就绪"+msgid "Ready for Quote"msgstr "准备报价"@@ -11577,6 +11860,9 @@ msgstr "仍为草稿或待处理状态的收据、装运、销售发票、采购msgid "Receivables"msgstr "应收账款(默认)"+msgid "Receivables (AR)"+msgstr "应收账款 (AR)"+msgid "Receivables (default)"msgstr "将采购订单与所收货物和发票进行对账——在Carbon中隐含进行,通过行数量和GR/IR余额。"@@ -11635,6 +11921,9 @@ msgstr "最近创建"msgid "Reconcile"msgstr "对账"+msgid "Reconciliation found discrepancies with the provider"+msgstr "对账发现与提供商的差异"+msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."msgstr "回收期"@@ -11813,6 +12102,9 @@ msgstr "删除行"msgid "Remove slide"msgstr "移除幻灯片"+msgid "Remove slot"+msgstr "移除插槽"+msgid "Remove sort by column"msgstr "删除按列排序"@@ -12047,6 +12339,9 @@ msgstr "通过报废或出售将资产退出使用,将收益或损失计入账msgid "Retry"msgstr "重试"+msgid "Retry all"+msgstr "全部重试"+msgid "Return Home"msgstr "返回首页"@@ -12098,6 +12393,9 @@ msgstr "审查每个项目的更改,然后确认 — 发布无法撤销。"msgid "Review the period's balance sheet and income statement and confirm the figures look right. This is a manual sign-off — mark it done once you have reviewed them."msgstr "审查期间的资产负债表和损益表,并确认数字正确。这是手动签核 — 审查后标记为完成。"+msgid "Review the suggested matches before applying. These are a best guess — confirm each is correct."+msgstr "在应用之前审查建议的匹配项。这些是最佳猜测 — 确认每个都是正确的。"+msgid "Review the warnings below, then post the count to apply the adjustments."msgstr "查看下面的警告,然后过账盘点以应用调整。"@@ -12153,6 +12451,9 @@ msgstr "询价单号"msgid "RFQs"msgstr "询价单"+msgid "Ride Carbon dimensions along on pushed journals. Each slot maps one Carbon dimension to one provider analytics target; the value mapping below pairs individual dimension values with provider options."+msgstr "在推送的日记账上附加 Carbon 维度。每个插槽将一个 Carbon 维度映射到一个提供商分析目标;下面的值映射将单个维度值与提供商选项配对。"+#. placeholder {0}: certification.docVersionmsgid "Rider v{0}"msgstr "Rider v{0}"@@ -12443,6 +12744,9 @@ msgstr "保存应用"msgid "Save contacts"msgstr "保存联系人"+msgid "Save dimension settings"+msgstr "保存维度设置"+msgid "Save Method"msgstr "保存方法"@@ -12759,6 +13063,9 @@ msgstr "选择客户类型"msgid "Select customers"msgstr "选择客户"+msgid "Select dimension"+msgstr "选择维度"+msgid "Select Employee"msgstr "选择员工"@@ -12795,6 +13102,15 @@ msgstr "选择方法..."msgid "Select Printer"msgstr "选择打印机"+msgid "Select provider account"+msgstr "选择提供商账户"++msgid "Select provider target"+msgstr "选择提供商目标"++msgid "Select provider value"+msgstr "选择提供商值"+msgid "Select Quantities"msgstr "选择数量"@@ -13227,7 +13543,7 @@ msgid "Show sync options"msgstr "显示同步选项"msgid "Show Trailing Zeros"-msgstr ""+msgstr "显示尾随零"#. placeholder {0}: data.lengthmsgid "Showing {0} of {totalCount} — refine your search"@@ -13239,6 +13555,9 @@ msgstr "显示货币:{parentCurrency}"msgid "Showing the first 500 lines"msgstr "显示前500行"+msgid "Showing the newest 200 journals"+msgstr "显示最新的 200 条日记账"+msgid "Showing the top 1,000 groups by amount"msgstr "按金额显示前1,000个分组"@@ -13383,6 +13702,9 @@ msgstr "源列表"msgid "Source Method"msgstr "源方法"+msgid "Source types"+msgstr "源类型"+msgid "Source Version"msgstr "源版本"@@ -13721,6 +14043,15 @@ msgstr "后继零件"msgid "Suffix"msgstr "后缀"+msgid "Suggest mappings"+msgstr "建议映射"++msgid "Suggest mappings with AI"+msgstr "使用 AI 建议映射"++msgid "Suggest with AI"+msgstr "使用 AI 建议"+msgid "Suggested orders you haven't placed yet."msgstr "您尚未下达的建议订单。"@@ -13926,6 +14257,18 @@ msgstr "在此处更改员工类型不会更改其现有权限;后续对话框msgid "Sync"msgstr "同步"+msgid "Sync Activity"+msgstr "同步活动"++msgid "Sync operation"+msgstr "同步操作"++msgid "Sync Tie-Out"+msgstr "同步对账"++msgid "Synced"+msgstr "已同步"+msgid "System"msgstr "系统"@@ -14599,6 +14942,9 @@ msgstr "技术人员在执行此维护时遵循的程序;在已生成计划之msgid "The processes this work center can run; appears in process-pickers when scheduling operations, and limits which jobs can route through this work center."msgstr "该工作中心可以运行的流程;在安排操作时显示在流程选择器中,并限制哪些工作可以通过该工作中心路由。"+msgid "The provider offers no dimension targets. Enable the feature in the provider first (e.g. tracking categories, class tracking, or fields)."+msgstr "提供商不提供维度目标。首先在提供商中启用该功能(例如跟踪类别、类跟踪或字段)。"+msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "此行定价的数量断点;每列为买卖方谈判和转换为下游文件的自己的单价。"@@ -15077,6 +15423,9 @@ msgstr "星期四"msgid "Tie shipments through to an invoice with no re-keying"msgstr "将发货与发票关联,无需重新输入"+msgid "Tie-out"+msgstr "对账"+msgid "Tie-Out"msgstr "对账"@@ -15533,9 +15882,18 @@ msgstr "从销售订单取消关联工作?"msgid "Unlock"msgstr "解锁"+msgid "Unmapped accounts"+msgstr "未映射的账户"++msgid "Unmapped dimension values"+msgstr "未映射的维度值"+msgid "Unmapped Extracted Lines"msgstr "未映射的提取行"+msgid "Unmapped values"+msgstr "未映射的值"+msgid "Unmatched"msgstr "未匹配"@@ -16077,6 +16435,9 @@ msgstr "查看建议"msgid "View Suppliers"msgstr "查看供应商"+msgid "View tie-out"+msgstr "查看对账"+msgid "View Traceability Graph"msgstr "查看可追溯性图表"@@ -16283,6 +16644,9 @@ msgstr "什么数据"msgid "What drove inventory up or down, by any dimension"msgstr "按任何维度推动库存上升或下降的因素"+msgid "What happens when a journal is dated in a locked period."+msgstr "当日记帐日期在锁定期间时会发生什么"+msgid "What is {translatedTerm}?"msgstr "{translatedTerm}是什么?"diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex 300d048f73..433c9500dd 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -16,6 +16,10 @@ export enum NotificationEvent {ChangeNoticeDone = "change-order-done",DigitalQuoteResponse = "digital-quote-response",GaugeCalibrationExpired = "gauge-calibration-expired",+ // Accounting sync needs attention (failed sync operations); like Workflow,+ // the text is carried on the payload — documentId is the provider id, not a+ // readable document.+ IntegrationSync = "integrationSync",JobAssignment = "job-assignment",JobCompleted = "job-completed",JobOperationAssignment = "job-operation-assignment",@@ -166,6 +170,7 @@ export function getNotificationTopic(// No topic of its own: topicLabels in the account settings route is an// exhaustive Record<NotificationTopic, string>.case NotificationEvent.Workflow:+ case NotificationEvent.IntegrationSync:return NotificationTopic.General;default:return NotificationTopic.General;@@ -246,6 +251,8 @@ export function getNotificationEmailHeading(event: NotificationEvent): string {return "Change notice complete";case NotificationEvent.Workflow:return "Workflow";+ case NotificationEvent.IntegrationSync:+ return "Accounting sync needs attention";default:return "You have a new notification";}@@ -279,6 +286,8 @@ export function getNotificationEmailCtaLabel(event: NotificationEvent): string {return "View response";case NotificationEvent.Workflow:return "View details";+ case NotificationEvent.IntegrationSync:+ return "View sync activity";default:return "View details";}diff --git a/packages/onboarding/src/ui/GuidedUpsellCard.tsx b/packages/onboarding/src/ui/GuidedUpsellCard.tsxindex 8855ce9b55..9a22b95094 100644--- a/packages/onboarding/src/ui/GuidedUpsellCard.tsx+++ b/packages/onboarding/src/ui/GuidedUpsellCard.tsx@@ -14,7 +14,7 @@ export function GuidedUpsellCard({const { i18n } = useLingui();return (<Card>- <CardContent className="flex-row items-start gap-4 p-6 border-0">+ <CardContent className="flex-row items-start gap-4 p-6"><div className="shrink-0 size-11 rounded-lg bg-primary/15 flex items-center justify-center text-primary"><LuSparkles className="text-xl" /></div>diff --git a/packages/onboarding/src/ui/HowWeWorkView.tsx b/packages/onboarding/src/ui/HowWeWorkView.tsxindex 12976ec82f..da9d726e3a 100644--- a/packages/onboarding/src/ui/HowWeWorkView.tsx+++ b/packages/onboarding/src/ui/HowWeWorkView.tsx@@ -1,3 +1,4 @@+import { Card } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { CADENCE, ESCALATION } from "../content/howwework";import { EditableField } from "./EditableField";@@ -58,7 +59,7 @@ export function HowWeWorkView() {</ol></Panel>- <div className="rounded-lg border-l-2 border-l-primary bg-muted/30 px-5 py-4">+ <Card className="p-5 border border-primary/30 bg-primary/5 dark:bg-primary/5"><p className="text-sm text-muted-foreground"><span className="font-medium text-foreground"><Trans>The principle:</Trans>@@ -68,7 +69,7 @@ export function HowWeWorkView() {small fix; the same problem at go-live is a delay.</Trans></p>- </div>+ </Card></div>);}diff --git a/packages/onboarding/src/ui/OnboardingHub.tsx b/packages/onboarding/src/ui/OnboardingHub.tsxindex 28b0605cf9..e434eea5bb 100644--- a/packages/onboarding/src/ui/OnboardingHub.tsx+++ b/packages/onboarding/src/ui/OnboardingHub.tsx@@ -163,7 +163,7 @@ export function OnboardingHub({) : null}<Card className="overflow-hidden">- <CardHeader className="flex-row items-end justify-between gap-4 flex-wrap border-b border-border">+ <CardHeader className="flex-row items-end justify-between gap-4 flex-wrap"><CardTitle className="line-clamp-none"><Trans>{done} of {total} phases complete@@ -179,7 +179,7 @@ export function OnboardingHub({{stateText}</span></CardHeader>- <CardContent className="p-0 border-0">+ <CardContent className="p-0"><div className="flex gap-1.5 px-6 py-4">{spine.map((step) => {const st = effectiveGateStatus(@@ -254,7 +254,7 @@ function NextStepCard({return (<Card className="motion-safe:animate-in motion-safe:fade-in-50 motion-safe:slide-in-from-bottom-2 motion-safe:duration-300">- <CardContent className="flex-row items-start gap-4 p-5 border-0">+ <CardContent className="flex-row items-start gap-4 p-5"><div className="shrink-0 size-9 rounded-xl bg-primary/15 flex items-center justify-center text-sm font-medium tabular-nums">{action.gateNumber}</div>@@ -370,7 +370,10 @@ function GateRow({</span>) : null}{tier !== "self_serve" ? (- <Badge variant="outline" className="ml-auto">+ <Badge+ variant={OWNER_TOKENS[ownerForStep(step, tier)].variant}+ className="ml-auto"+ >{i18n._(OWNER_TOKENS[ownerForStep(step, tier)].label)}</Badge>) : null}diff --git a/packages/onboarding/src/ui/PlanView.tsx b/packages/onboarding/src/ui/PlanView.tsxindex ffe1e99450..ace5dda679 100644--- a/packages/onboarding/src/ui/PlanView.tsx+++ b/packages/onboarding/src/ui/PlanView.tsx@@ -199,7 +199,7 @@ function PhaseCard({return (<Card id={planAnchorId(step.key)} className="overflow-hidden scroll-mt-6">- <CardHeader className="flex-row items-start gap-4 px-5 py-4 border-b border-border">+ <CardHeader className="flex-row items-start gap-4 px-5 py-4"><spanclassName={cn("shrink-0 size-9 rounded-lg border flex items-center justify-center text-sm font-semibold tabular-nums",@@ -232,7 +232,7 @@ function PhaseCard({</Badge>) : null}</CardHeader>- <CardContent className="p-0 border-0">+ <CardContent className="p-0"><div className="px-5 py-4">{step.desc ? (<p className="text-sm text-muted-foreground">{i18n._(step.desc)}</p>diff --git a/packages/onboarding/src/ui/RequirementsView.tsx b/packages/onboarding/src/ui/RequirementsView.tsxindex 44e37d11d2..5cd743b5f3 100644--- a/packages/onboarding/src/ui/RequirementsView.tsx+++ b/packages/onboarding/src/ui/RequirementsView.tsx@@ -1,4 +1,4 @@-import { cn, IconButton } from "@carbon/react";+import { Badge, cn, IconButton } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { LuTrash } from "react-icons/lu";import { COLLECTIONS, PAGE_COPY, REQUIREMENTS } from "../content";@@ -52,9 +52,7 @@ export function RequirementsView() {key={module.code}title={<span className="flex items-center gap-2">- <span className="text-xs font-mono font-semibold rounded bg-foreground text-background px-1.5 py-0.5">- {module.code}- </span>+ <Badge className="font-mono">{module.code}</Badge>{i18n._(module.name)}</span>}diff --git a/packages/onboarding/src/ui/RolesView.tsx b/packages/onboarding/src/ui/RolesView.tsxindex fa3032938a..23edea7370 100644--- a/packages/onboarding/src/ui/RolesView.tsx+++ b/packages/onboarding/src/ui/RolesView.tsx@@ -1,4 +1,4 @@-import { cn } from "@carbon/react";+import { Badge } from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { PAGE_COPY } from "../content";import { ROLES } from "../content/roles";@@ -24,15 +24,9 @@ export function RolesView() {</p><div className="flex items-center gap-4 mt-1">{(Object.keys(OWNER_TOKENS) as Owner[]).map((o) => (- <span- key={o}- className="inline-flex items-center gap-1.5 text-xs text-muted-foreground"- >- <span- className={cn("size-2 rounded-full", OWNER_TOKENS[o].dot)}- />+ <Badge key={o} variant={OWNER_TOKENS[o].variant}>{i18n._(OWNER_TOKENS[o].label)}- </span>+ </Badge>))}</div></header>@@ -68,20 +62,12 @@ export function RolesView() {{step.lines.map((line, i) => (<li key={i} className="flex items-center gap-3 px-5 py-3"><span className="flex-1 text-sm">{i18n._(line.label)}</span>- <span- className={cn(- "shrink-0 inline-flex items-center gap-1.5 rounded-full pl-2 pr-2.5 py-0.5 text-xs font-medium",- OWNER_TOKENS[line.owner].cls- )}+ <Badge+ variant={OWNER_TOKENS[line.owner].variant}+ className="shrink-0">- <span- className={cn(- "size-1.5 rounded-full",- OWNER_TOKENS[line.owner].dot- )}- />{i18n._(OWNER_TOKENS[line.owner].label)}- </span>+ </Badge></li>))}</SectionList>diff --git a/packages/onboarding/src/ui/SetupControls.tsx b/packages/onboarding/src/ui/SetupControls.tsxindex 33859a9341..91dd3558b5 100644--- a/packages/onboarding/src/ui/SetupControls.tsx+++ b/packages/onboarding/src/ui/SetupControls.tsx@@ -259,7 +259,7 @@ function Card({}) {return (<UICard>- <CardContent className="p-5 border-0">+ <CardContent className="p-5"><h2 className="text-sm font-semibold">{title}</h2>{subtitle ? (<p className="text-xs text-muted-foreground mt-1 mb-4 max-w-xl">diff --git a/packages/onboarding/src/ui/TeamView.tsx b/packages/onboarding/src/ui/TeamView.tsxindex 3fd8b9250a..cf95c5e920 100644--- a/packages/onboarding/src/ui/TeamView.tsx+++ b/packages/onboarding/src/ui/TeamView.tsx@@ -33,7 +33,7 @@ export function TeamView() {<div className="flex flex-col gap-3">{TEAM_ROLES.map((member, i) => (<Card key={i}>- <CardContent className="flex-row items-start gap-4 p-5 border-0">+ <CardContent className="flex-row items-start gap-4 p-5"><span className="shrink-0 size-10 rounded-full border bg-background flex items-center justify-center"><LuUser className="text-muted-foreground" /></span>diff --git a/packages/onboarding/src/ui/primitives/Section.tsx b/packages/onboarding/src/ui/primitives/Section.tsxindex aaa86e1023..c4626cd7bf 100644--- a/packages/onboarding/src/ui/primitives/Section.tsx+++ b/packages/onboarding/src/ui/primitives/Section.tsx@@ -1,12 +1,7 @@// Card-shell + list primitives. The hub's surfaces are all "titled card wrapping-// a divided list", composed the design-system way: a `CardHeader` (title bar,-// sitting on the `Card` shell) over a `CardContent` (the white `bg-card` surface-// holding the list — the `Card` shell itself is the muted `bg-accent` tray in-// light mode, so the body must live in a `CardContent` or it reads gray).-// `CardContent` is `border-0`: the `Card`'s `shadow-button-base` already draws-// the crisp outer edge, so a `CardContent` border on top of it reads as a blurry-// double line. The header/body divider is a `border-b` on the `CardHeader`.-// Compose: <Section title aside><SectionList>{rows}</SectionList></Section>.+// a divided list", composed the design-system way from `CardHeader` + `CardContent`+// with their default styling — no custom borders/padding overrides, so they read+// as standard cards. Compose: <Section title aside><SectionList>{rows}</SectionList></Section>.import {Card,@@ -39,7 +34,7 @@ export function Section({return (<Card id={id} className={cn("overflow-hidden", className)}>{hasHeader ? (- <CardHeader className="flex-row items-start justify-between gap-3 px-5 py-3 border-b border-border">+ <CardHeader><div className="flex items-start gap-3 min-w-0">{number != null ? (<span className="shrink-0 size-6 rounded-lg border bg-background flex items-center justify-center text-xs font-semibold tabular-nums">@@ -58,7 +53,7 @@ export function Section({{aside != null ? <div className="shrink-0">{aside}</div> : null}</CardHeader>) : null}- <CardContent className="p-0 border-0">{children}</CardContent>+ <CardContent>{children}</CardContent></Card>);}@@ -92,16 +87,14 @@ export function Panel({return (<Card className="overflow-hidden">{hasHeader ? (- <CardHeader className="flex-row items-start justify-between gap-3 px-5 py-3 border-b border-border">+ <CardHeader>{title != null ? (<CardTitle className="text-sm font-semibold">{title}</CardTitle>) : null}{aside != null ? <div className="shrink-0">{aside}</div> : null}</CardHeader>) : null}- <CardContent className={cn("p-5 border-0", className)}>- {children}- </CardContent>+ <CardContent className={className}>{children}</CardContent></Card>);}diff --git a/packages/onboarding/src/ui/primitives/StatusToggle.tsx b/packages/onboarding/src/ui/primitives/StatusToggle.tsxindex 7f918a590c..9c7124430c 100644--- a/packages/onboarding/src/ui/primitives/StatusToggle.tsx+++ b/packages/onboarding/src/ui/primitives/StatusToggle.tsx@@ -1,8 +1,9 @@-// Binary status pill button (validated / in-scope / done toggles). Active =-// emerald, inactive = muted. `withIcon` shows a check when active (the-// "Validated / Not yet" style); off gives the compact "In scope / Out" style.+// Binary status pill button (validated / in-scope / done toggles). Renders the+// design-system `Badge` (green when active, outline when inactive) inside a+// button so the toggle stays interactive. `withIcon` shows a check when active+// (the "Validated / Not yet" style); off gives the compact "In scope / Out" style.-import { cn } from "@carbon/react";+import { Badge, cn } from "@carbon/react";import { LuCheck } from "react-icons/lu";export function StatusToggle({@@ -25,22 +26,20 @@ export function StatusToggle({type="button"onClick={onToggle}className={cn(- "shrink-0 inline-flex items-center gap-1.5 rounded-full text-xs font-medium cursor-pointer active:scale-[0.96] transition-[transform,background-color,border-color,color]",- withIcon ? "pl-2 pr-2.5 py-1" : "px-2.5 py-0.5",- active- ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 hover:bg-emerald-500/20"- : "border bg-background text-muted-foreground hover:bg-muted hover:text-foreground",+ "shrink-0 cursor-pointer active:scale-[0.96] transition-transform",className)}>- {withIcon ? (- active ? (- <LuCheck className="size-3" />- ) : (- <span className="size-1.5 rounded-full bg-muted-foreground/50" />- )- ) : null}- {active ? activeLabel : inactiveLabel}+ <Badge variant={active ? "green" : "outline"} className="gap-1.5">+ {withIcon ? (+ active ? (+ <LuCheck className="size-3" />+ ) : (+ <span className="size-1.5 rounded-full bg-muted-foreground/50" />+ )+ ) : null}+ {active ? activeLabel : inactiveLabel}+ </Badge></button>);}diff --git a/packages/onboarding/src/ui/primitives/tokens.ts b/packages/onboarding/src/ui/primitives/tokens.tsindex 014b205e49..8825c13954 100644--- a/packages/onboarding/src/ui/primitives/tokens.ts+++ b/packages/onboarding/src/ui/primitives/tokens.ts@@ -8,27 +8,23 @@ import type { Owner, TaskValue } from "../../types";export interface OwnerToken {label: MessageDescriptor;- // pill background + text- cls: string;- // accompanying dot- dot: string;+ // `Badge` variant used to render the owner pill (single source of truth so+ // every surface — legend, role rows, gate rows — reads the same).+ variant: "blue" | "green" | "outline";}export const OWNER_TOKENS: Record<Owner, OwnerToken> = {carbon: {label: msg`Carbon`,- cls: "bg-blue-500/10 text-blue-600 dark:text-blue-400",- dot: "bg-blue-500"+ variant: "blue"},you: {label: msg`You`,- cls: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",- dot: "bg-emerald-500"+ variant: "green"},shared: {label: msg`Shared`,- cls: "border text-muted-foreground",- dot: "bg-muted-foreground"+ variant: "outline"}};diff --git a/packages/react/src/Badge.tsx b/packages/react/src/Badge.tsxindex 7c3a146167..33cb563cf9 100644--- a/packages/react/src/Badge.tsx+++ b/packages/react/src/Badge.tsx@@ -11,7 +11,7 @@ import { LuX } from "react-icons/lu";import { cn } from "./utils/cn";const badgeVariants = cva(- "inline-flex items-center rounded-md px-2 min-h-[1.25rem] font-medium transition-[color,box-shadow] border focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 font-bold text-[11px] uppercase truncate tracking-tight whitespace-nowrap",+ "inline-flex items-center rounded-md px-2 min-h-[1.5rem] font-medium transition-[color,box-shadow] border focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 font-bold text-[12px] uppercase truncate tracking-tight whitespace-nowrap",{variants: {variant: {diff --git a/packages/react/src/Select.tsx b/packages/react/src/Select.tsxindex da74743583..a8287f9153 100644--- a/packages/react/src/Select.tsx+++ b/packages/react/src/Select.tsx@@ -21,7 +21,7 @@ const SelectGroup = SelectPrimitive.Group;const SelectValue = SelectPrimitive.Value;const selectTriggerVariants = cva(- "bg-transparent text-foreground flex w-full items-center justify-between whitespace-nowrap rounded-md border border-input shadow-xs transition-[color,box-shadow] data-[placeholder]:text-muted-foreground outline-none focus:border-ring focus:ring-[3px] focus:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>span]:line-clamp-1",+ "bg-transparent text-foreground flex w-full items-center justify-between whitespace-nowrap rounded-md border border-input shadow-xs transition-[color,box-shadow] data-[placeholder]:text-muted-foreground outline-none focus:border-ring focus:ring-[3px] focus:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>span]:min-w-0 [&>span]:truncate",{variants: {size: {@@ -61,7 +61,7 @@ const SelectTrigger = forwardRef<{children}{!hideIcon && !inline && (<SelectPrimitive.Icon asChild>- <LuChevronsUpDown className="h-4 w-4 opacity-50" />+ <LuChevronsUpDown className="h-4 w-4 flex-shrink-0 opacity-50" /></SelectPrimitive.Icon>)}</SelectPrimitive.Trigger>diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.tsindex b4badb9da3..42e8dc53d9 100644--- a/packages/utils/src/themes.ts+++ b/packages/utils/src/themes.ts@@ -48,7 +48,7 @@ export const themes = ["active-foreground": "0 0% 100%",secondary: "0 0% 7%","secondary-foreground": "0 0% 93%",- muted: "0 0% 13.6%",+ muted: "0 10% 10%","muted-foreground": "0 0% 63%",accent: "0 0% 10%","accent-foreground": "0 0% 93%",@@ -108,7 +108,7 @@ export const themes = ["active-foreground": "0 0% 98%",secondary: "0 0% 14.9%","secondary-foreground": "0 0% 98%",- muted: "0 0% 13.6%",+ muted: "0 10% 10%","muted-foreground": "0 0% 63.9%",accent: "0 0% 14.9%","accent-foreground": "0 0% 98%",@@ -168,7 +168,7 @@ export const themes = ["active-foreground": "0 80% 63%",secondary: "0 0% 14.9%","secondary-foreground": "0 0% 98%",- muted: "0 0% 13.6%",+ muted: "0 10% 10%","muted-foreground": "0 0% 63.9%",accent: "0 0% 14.9%","accent-foreground": "0 0% 98%",@@ -228,7 +228,7 @@ export const themes = ["active-foreground": "18 80% 63%",secondary: "12 6.5% 15.1%","secondary-foreground": "60 9.1% 97.8%",- muted: "12 0% 13.6%",+ muted: "12 10% 10%","muted-foreground": "24 5.4% 63.9%",accent: "12 6.5% 15.1%","accent-foreground": "60 9.1% 97.8%",@@ -289,7 +289,7 @@ export const themes = [secondary: "12 6.5% 15.1%","secondary-foreground": "61 9.1% 97.8%",- muted: "12 0% 13.6%",+ muted: "12 10% 10%","muted-foreground": "24 5.4% 63.9%",accent: "12 6.5% 15.1%","accent-foreground": "61 9.1% 97.8%",@@ -338,26 +338,26 @@ export const themes = ["success-foreground": "0 0% 98%"},dark: {- background: "151 14.3% 6.1%",+ background: "171 14.3% 6.1%",foreground: "0 0% 95%",- popover: "151 0% 9%",- "popover-foreground": "151 0% 95%",- card: "151 10% 3.9%",- "card-foreground": "151 0% 95%",+ popover: "171 0% 9%",+ "popover-foreground": "171 0% 95%",+ card: "171 10% 3.9%",+ "card-foreground": "171 0% 95%",primary: "171 98% 59%","primary-foreground": "144.9 80.4% 10%",active: "171 98% 15%","active-foreground": "171 98% 59%",- secondary: "151 3.7% 15.9%",+ secondary: "171 3.7% 15.9%","secondary-foreground": "0 0% 98%",- muted: "151 0% 13.6%",- "muted-foreground": "151 5% 64.9%",- accent: "151 6.5% 15.1%",+ muted: "171 10% 10%",+ "muted-foreground": "171 5% 64.9%",+ accent: "171 6.5% 15.1%","accent-foreground": "0 0% 98%",destructive: "0 62.8% 30.6%","destructive-foreground": "0 85.7% 97.3%",- border: "151 3.7% 15.9%",- input: "151 3.7% 15.9%",+ border: "171 3.7% 15.9%",+ input: "171 3.7% 15.9%",ring: "171 71.8% 29.2%",success: "142 70% 45%","success-foreground": "0 0% 98%"@@ -410,7 +410,7 @@ export const themes = ["active-foreground": "216 98% 58%",secondary: "220 10% 15.9%","secondary-foreground": "220 0% 98%",- muted: "220 0% 13.6%",+ muted: "220 10% 10%","muted-foreground": "220 5% 64.9%",accent: "220 10% 15.9%","accent-foreground": "0 0% 98%",@@ -470,7 +470,7 @@ export const themes = ["active-foreground": "327 80% 63%",secondary: "263 27.9% 16.9%","secondary-foreground": "263 20% 98%",- muted: "263 27.9% 12.9%",+ muted: "263 10% 10%","muted-foreground": "217.9 10.6% 64.9%",accent: "263 27.9% 12.9%","accent-foreground": "210 20% 98%",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 17bcfd3d2d..5b3c0fb93a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2040,6 +2040,12 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config+ '@logtape/logtape':+ specifier: 'catalog:'+ version: 2.2.3+ '@logtape/testing':+ specifier: 'catalog:'+ version: 2.2.3(@logtape/[email protected])'@types/nodemailer':specifier: 6.4.21version: 6.4.21diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 1849d7dbec..c4c761a750 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -75,6 +75,7 @@ catalog:cookie: 1.1.1cross-env: 7.0.3dompurify: 3.4.0+ fast-xml-parser: 5.3.1framer-motion: 11.18.2intl-parse-accept-language: 1.0.0isbot: '5'diff --git a/scripts/generate-mcp.ts b/scripts/generate-mcp.tsindex 55914806d4..28f00b6420 100644--- a/scripts/generate-mcp.ts+++ b/scripts/generate-mcp.ts@@ -611,6 +611,12 @@ function loadModelsContent(mod: string): string | null {if (fs.existsSync(modelsPath)) {return fs.readFileSync(modelsPath, "utf-8");}+ // Fall back to the `.ee`-licensed variant (see root LICENSE) when a module+ // keeps its single models file under that name.+ const eeModelsPath = path.join(MODULES_DIR, mod, `${mod}.ee.models.ts`);+ if (fs.existsSync(eeModelsPath)) {+ return fs.readFileSync(eeModelsPath, "utf-8");+ }// Try shared models for cross-module validatorsconst sharedPath = path.join(MODULES_DIR, "shared", "index.ts");if (fs.existsSync(sharedPath)) {@@ -625,10 +631,21 @@ export function generateToolMetadata(): void {const allTools: ToolMetadata[] = [];for (const mod of MODULE_LIST) {- const serviceFile = path.join(MODULES_DIR, mod, `${mod}.service.ts`);+ let serviceFile = path.join(MODULES_DIR, mod, `${mod}.service.ts`);if (!fs.existsSync(serviceFile)) {- console.warn(` ⚠ Service file not found: ${serviceFile}`);- continue;+ // Fall back to the `.ee`-licensed variant (see root LICENSE) when a+ // module keeps its single service file under that name (e.g.+ // accounting.ee.service.ts).+ const eeServiceFile = path.join(+ MODULES_DIR,+ mod,+ `${mod}.ee.service.ts`+ );+ if (!fs.existsSync(eeServiceFile)) {+ console.warn(` ⚠ Service file not found: ${serviceFile}`);+ continue;+ }+ serviceFile = eeServiceFile;}const content = fs.readFileSync(serviceFile, "utf-8");